Core
FitResult
Stores the result of a fitting procedure.
This class encapsulates the fitted parameters, their standard errors, optimizer output, and fit quality metrics. It also provides functionality for summarizing the results and making predictions using the fitted model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
dict
|
Array of fitted parameters. |
required |
std_err
|
dict
|
Array of standard errors of the fitted parameters. |
required |
fit_output
|
any
|
Raw output from the optimization routine. |
required |
metrics
|
dict
|
Dictionary of fit quality metrics (e.g., R-squared, reduced chi-squared). |
{}
|
predict
|
callable
|
Function of x that returns predictions based on the fitted parameters. If not provided, an exception will be raised when calling it. |
None
|
param_names
|
list
|
List of parameter names, defaulting to a range based on the number of parameters. |
None
|
model_name
|
str
|
Name of the model used to fit the data. |
None
|
metadata
|
dict
|
Additional information that can be passed in the fit result. |
{}
|
Methods:
Name | Description |
---|---|
summary |
Prints a detailed summary of the fit results, including parameter values, standard errors, and fit quality metrics. |
_no_prediction |
Raises an exception when no prediction function is available. |
Source code in sqil_core/fit/_core.py
summary(no_print=False)
Prints a detailed summary of the fit results.
Source code in sqil_core/fit/_core.py
compute_adjusted_standard_errors(pcov, residuals, red_chi2=None, cov_rescaled=True, sigma=None)
Compute adjusted standard errors for fitted parameters.
This function adjusts the covariance matrix based on the reduced chi-squared value and calculates the standard errors for each parameter. It accounts for cases where the covariance matrix is not available or the fit is nearly perfect.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pcov
|
ndarray
|
Covariance matrix of the fitted parameters, typically obtained from an optimization routine. |
required |
residuals
|
ndarray
|
Residuals of the fit, defined as the difference between observed and model-predicted values. |
required |
red_chi2
|
float
|
Precomputed reduced chi-squared value. If |
None
|
cov_rescaled
|
bool
|
Whether the fitting process already rescales the covariance matrix with the reduced chi-squared. |
True
|
sigma
|
ndarray
|
Experimental uncertainties. Only used if |
None
|
Returns:
Type | Description |
---|---|
ndarray
|
Standard errors for each fitted parameter. If the covariance matrix is
undefined, returns |
Warnings
- If the covariance matrix is not available (
pcov is None
), the function issues a warning about possible numerical instability or a near-perfect fit. - If the reduced chi-squared value is
NaN
, the function returnsNaN
for all standard errors.
Notes
- The covariance matrix is scaled by the reduced chi-squared value to adjust for under- or overestimation of uncertainties.
- If
red_chi2
is not provided, it is computed internally using the residuals. - If a near-perfect fit is detected (all residuals close to zero), the function warns that standard errors may not be necessary.
Examples:
>>> pcov = np.array([[0.04, 0.01], [0.01, 0.09]])
>>> residuals = np.array([0.1, -0.2, 0.15])
>>> compute_adjusted_standard_errors(pcov, residuals)
array([0.2, 0.3])
Source code in sqil_core/fit/_core.py
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
compute_aic(residuals, n_params)
Computes the Akaike Information Criterion (AIC) for a given model fit.
The AIC is a metric used to compare the relative quality of statistical models for a given dataset. It balances model fit with complexity, penalizing models with more parameters to prevent overfitting.
Interpretation: The AIC has no maeaning on its own, only the difference between the AIC of model1 and the one of model2. ΔAIC = AIC_1 - AIC_2 If ΔAIC > 10 -> model 2 fits much better.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
residuals
|
ndarray
|
Array of residuals between the observed data and model predictions. |
required |
n_params
|
int
|
Number of free parameters in the fitted model. |
required |
Returns:
Type | Description |
---|---|
float
|
The Akaike Information Criterion value. |
Source code in sqil_core/fit/_core.py
compute_chi2(residuals, n_params=None, cov_rescaled=True, sigma=None)
Compute the chi-squared (χ²) and reduced chi-squared (χ²_red) statistics.
This function calculates the chi-squared value based on residuals and an
estimated or provided uncertainty (sigma
). If the number of model parameters
(n_params
) is specified, it also computes the reduced chi-squared.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
residuals
|
ndarray
|
The difference between observed and model-predicted values. |
required |
n_params
|
int
|
Number of fitted parameters. If provided, the function also computes the reduced chi-squared (χ²_red). |
None
|
cov_rescaled
|
bool
|
Whether the covariance matrix has been already rescaled by the fit method.
If |
True
|
sigma
|
ndarray
|
Experimental uncertainties. Should only be used when the fitting process does not account for experimental errors AND known uncertainties are available. |
None
|
Returns:
Name | Type | Description |
---|---|---|
chi2 |
float
|
The chi-squared statistic (χ²), which measures the goodness of fit. |
red_chi2 |
float (if `n_params` is provided)
|
The reduced chi-squared statistic (χ²_red), computed as χ² divided by
the degrees of freedom (N - p). If |
Warnings
- If the degrees of freedom (N - p) is non-positive, a warning is issued, and χ²_red is set to NaN. This may indicate overfitting or an insufficient number of data points.
- If any uncertainty value in
sigma
is zero, it is replaced with machine epsilon to prevent division by zero.
Notes
- If
sigma
is not provided andcov_rescaled=False
, the function estimates the uncertainty using the standard deviation of residuals. - The reduced chi-squared value (χ²_red) should ideally be close to 1 for a good fit. Values significantly greater than 1 indicate underfitting, while values much less than 1 suggest overfitting.
Examples:
>>> residuals = np.array([0.1, -0.2, 0.15, -0.05])
>>> compute_chi2(residuals, n_params=2)
(0.085, 0.0425) # Example output
Source code in sqil_core/fit/_core.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 |
|
compute_nrmse(residuals, y_data)
Computes the Normalized Root Mean Squared Error (NRMSE) of a model fit.
Lower is better.
The NRMSE is a scale-independent metric that quantifies the average magnitude of residual errors normalized by the range of the observed data. It is useful for comparing the fit quality across different datasets or models.
For complex data it's computed using the L2 norm and the span of the magnitude.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
residuals
|
ndarray
|
Array of residuals between the observed data and model predictions. |
required |
y_data
|
ndarray
|
The original observed data used in the model fitting. |
required |
Returns:
Type | Description |
---|---|
float
|
The normalized root mean squared error (NRMSE). |
Source code in sqil_core/fit/_core.py
fit_input(fit_func)
Decorator to handle optional fitting inputs like initial guesses, bounds, and fixed parameters for a fitting function.
guess
: list or np.ndarray, optional, default=None The initial guess for the fit. If None it's not passed to the fit function.bounds
: list or np.ndarray, optional, default=(-np.inf, np.inf) The bounds on the fit parameters in the form [(min, max), (min, max), ...].fixed_params
: list or np.ndarray, optional, default=None Indices of the parameters that must remain fixed during the optimization. For example fittingf(x, a, b)
, if we want to fix the value ofa
we would passfit_f(guess=[a_guess, b_guess], fixed_params=[0])
fixed_bound_factor
: float, optional, default=1e-6 The relative tolerance allowed for parameters that must remain fixed (fixed_params
).
IMPORTANT: This decorator requires the x and y input vectors to be named x_data
and y_data
.
The initial guess must be called guess
and the bounds bounds
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fit_func
|
callable
|
The fitting function to be decorated. This function should accept |
required |
Returns:
Type | Description |
---|---|
callable
|
A wrapper function that processes the input arguments and then calls the original fitting function with the preprocessed inputs. This function also handles warnings if unsupported parameters are passed to the fit function. |
Notes
- The parameters in
guess
,bounds
andfixed_params
must be in the same order as in the modeled function definition. - The decorator can fix certain parameters by narrowing their bounds based on an initial guess
and a specified
fixed_bound_factor
. - The decorator processes bounds by setting them as
(-np.inf, np.inf)
if they are not specified (None
).
Examples:
>>> @fit_input
... def my_fit_func(x_data, y_data, guess=None, bounds=None, fixed_params=None):
... # Perform fitting...
... return fit_result
>>> x_data = np.linspace(0, 10, 100)
>>> y_data = np.sin(x_data) + np.random.normal(0, 0.1, 100)
>>> result = my_fit_func(x_data, y_data, guess=[1, 1], bounds=[(0, 5), (-np.inf, np.inf)])
Source code in sqil_core/fit/_core.py
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
|
fit_output(fit_func)
Decorator to standardize the output of fitting functions.
This decorator processes the raw output of various fitting libraries
(such as SciPy's curve_fit, least_squares leastsq, and minimize, as well as lmfit)
and converts it into a unified FitResult
object. It extracts
optimized parameters, their standard errors, fit quality metrics,
and a prediction function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fit_func
|
Callable
|
A function that performs fitting and returns raw fit output, possibly along with metadata. |
required |
Returns:
Type | Description |
---|---|
Callable
|
A wrapped function that returns a |
Raises:
Type | Description |
---|---|
TypeError
|
If the fitting function's output format is not recognized. |
Notes
- If the fit function returns a tuple
(raw_output, metadata)
, the metadata is extracted and applied to enhance the fit results. In case of any conflicts, the metadata overrides the computed values.
Examples:
>>> @fit_output
... def my_fitting_function(x, y):
... return some_raw_fit_output
...
>>> fit_result = my_fitting_function(x_data, y_data)
>>> print(fit_result.params)
Source code in sqil_core/fit/_core.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
|