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). |
None
|
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
|
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()
Prints a detailed summary of the fit results.
_format_lmfit(result)
Formats the output of an lmfit model fitting result into a standardized dictionary.
This function processes the result of an lmfit model fitting (e.g., from lmfit.Model.fit
) and
structures the fitting parameters, their standard errors, reduced chi-squared, and a prediction function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
`lmfit.ModelResult`
|
The result of an lmfit model fitting procedure. It must contain the following fields:
- |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing:
- |
Notes
- lmfit already rescales standard errors by the reduced chi-squared, so no further adjustments are made.
- The independent variable name used in the fit is determined from
result.userkws
andresult.model.independent_vars
. - The function creates a prediction function (
predict
) from the fitted model.
Source code in sqil_core/fit/_core.py
_format_scipy_least_squares(result, has_sigma=False)
Formats the output of a SciPy least-squares optimization into a standardized dictionary.
This function processes the result of a SciPy least-squares fitting function (e.g., scipy.optimize.least_squares
)
and structures the fitting parameters, standard errors, and reduced chi-squared values for consistent downstream use.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
`scipy.optimize.OptimizeResult`
|
The result of a least-squares optimization (e.g., from |
required |
has_sigma
|
bool
|
Indicates whether the fitting procedure considered experimental errors ( |
False
|
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing:
- |
Source code in sqil_core/fit/_core.py
_format_scipy_minimize(result, residuals=None, has_sigma=False)
Formats the output of a SciPy minimize optimization into a standardized dictionary.
This function processes the result of a SciPy minimization optimization (e.g., scipy.optimize.minimize
)
and structures the fitting parameters, standard errors, and reduced chi-squared values for consistent downstream use.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
`scipy.optimize.OptimizeResult`
|
The result of a minimization optimization (e.g., from |
required |
residuals
|
array - like
|
The residuals (differences between observed data and fitted model). If not provided, standard errors will be computed based on the inverse Hessian matrix. |
None
|
has_sigma
|
bool
|
Indicates whether the fitting procedure considered experimental errors ( |
False
|
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing:
- |
Source code in sqil_core/fit/_core.py
_format_scipy_tuple(result, has_sigma=False)
Formats the output of a SciPy fitting function into a standardized dictionary.
This function takes the tuple returned by SciPy optimization functions (e.g., curve_fit
, leastsq
)
and extracts relevant fitting parameters, standard errors, and reduced chi-squared values. It ensures
the result is structured consistently for further processing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
tuple
|
A tuple containing the fitting results from a SciPy function. Expected structure:
- |
required |
has_sigma
|
bool
|
Indicates whether the fitting procedure considered experimental errors ( |
False
|
Returns:
Type | Description |
---|---|
dict
|
A dictionary containing:
- |
Source code in sqil_core/fit/_core.py
_get_covariance_from_scipy_optimize_result(result)
Extracts the covariance matrix (or an approximation) from a scipy optimization result.
This function attempts to retrieve the covariance matrix of the fitted parameters from the
result object returned by a scipy optimization method. It first checks for the presence of
the inverse Hessian (hess_inv
), which is used to estimate the covariance. If it's not available,
the function attempts to compute the covariance using the Hessian matrix (hess
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
`scipy.optimize.OptimizeResult`
|
The result object returned by a scipy optimization function, such as |
required |
Returns:
Type | Description |
---|---|
ndarray or None
|
The covariance matrix of the optimized parameters, or |
Notes
- If the Hessian matrix (
hess
) is singular or nearly singular, the covariance matrix cannot be computed. - In some cases, the inverse Hessian (
hess_inv
) is directly available and provides the covariance without further computation.
Source code in sqil_core/fit/_core.py
_get_xy_data_from_fit_args(*args, **kwargs)
Extracts x and y data from the given arguments and keyword arguments.
This helper function retrieves the x and y data (1D vectors) from the function's arguments or keyword arguments. The function checks for common keyword names like "x_data", "xdata", "x", "y_data", "ydata", and "y", and returns the corresponding data. If no keyword arguments are found, it attempts to extract the first two consecutive 1D vectors from the positional arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
variable length argument list
|
The positional arguments passed to the function, potentially containing the x and y data. |
()
|
**kwargs
|
keyword arguments
|
The keyword arguments passed to the function, potentially containing keys such as "x_data", "x", "y_data", or "y". |
{}
|
Returns:
Type | Description |
---|---|
tuple of (np.ndarray, np.ndarray)
|
A tuple containing the x data and y data as 1D numpy arrays or lists. If no valid data is found, returns (None, None). |
Raises:
Type | Description |
---|---|
ValueError
|
If both x and y data cannot be found in the input arguments. |
Notes
- The function looks for the x and y data in the keyword arguments first, in the order of x_keys and y_keys.
- If both x and y data are not found in keyword arguments, the function will look for the first two consecutive 1D vectors in the positional arguments.
- If the data cannot be found, the function will return (None, None).
- The function validates that the extracted x and y data are 1D vectors (either lists or numpy arrays).
Source code in sqil_core/fit/_core.py
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 |
|
_is_lmfit(result)
_is_scipy_least_squares(result)
Check whether the given result follows the expected structure of a SciPy least_squares.
Source code in sqil_core/fit/_core.py
_is_scipy_minimize(result)
Check whether the given result follows the expected structure of a SciPy minimize.
Source code in sqil_core/fit/_core.py
_is_scipy_tuple(result)
Check whether the given result follows the expected structure of a SciPy optimization tuple.
Source code in sqil_core/fit/_core.py
_process_metadata(metadata, sqil_dict)
Process metadata by computing values that cannot be calculated before having the sqil_dict. For example use the standard errors to compute a different metric.
Treats items whose key starts with @ as functions that take sqil_dict as input. So it evaluates them and renames the key removing the @.
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
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 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 |
|
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
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 501 502 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 |
|
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
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 270 271 272 273 274 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 |
|
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
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 |
|