qspec logo qspec logo

A physics toolbox for laser spectroscopy.

Static Badge Static Badge Static Badge

Static Badge Static Badge

© 2026 Patrick Müller. All rights reserved.

qspec.analyze. curve_fit  (  f ,  x ,  y ,  p0=None ,  p0_fixed=None ,  sigma=None ,  absolute_sigma=False ,  check_finite=True ,  bounds=(-inf, inf) ,  method=None ,  jac=None ,  full_output=False ,  report=False ,  **kwargs  )[source]

Use non-linear least squares to fit a function $f$ to data. Assumes y = f(x, *params) + eps. This is a reimplementation of scipy.optimize.curve_fit with the additional features of fixing parameters with p0_fixed and the option to use the parameter sigma dynamically as a function g(x, y, f(x, *params), *params) -> sigma.

Parameters:
fCallable

The model function $f$ to fit to the data.

xarray_like | object

The $x$ data.

yarray_like

The $y$ data.

p0array_like | None

A numpy array or an Iterable of the initial guesses for the parameters. Must have at least the same length as the minimum number of parameters required by the function f. If p0 is None, 1 is taken as an initial guess for all non-keyword parameters.

p0_fixedarray_like | None

A numpy array or an Iterable of bool values specifying whether to fix a parameter. Must have the same length as p0.

sigmaarray_like | Callable | None

The $1\sigma$ uncertainty of the y data. This can also be a function $g$ such that g(x, y, f(x, *params), *params) -> sigma.

absolute_sigmabool

Whether sigma is used in an absolute sense (True) and the covariance matrix reflects these absolute values, or only the relative magnitudes of sigma matter (False) and the covariance matrix is scaled by the reduced $\chi^2$.

check_finitebool

See scipy.optimize.curve_fit.

boundstuple[array_like, array_like] | Bounds

See scipy.optimize.curve_fit.

methodLiteral["trf", "dogbox", "lm"] | None

See scipy.optimize.curve_fit.

jacCallable | Literal["2-point", "3-point", "cs"] | None

See scipy.optimize.curve_fit. Must not be callable if sigma is callable.

full_outputbool

See scipy.optimize.curve_fit.

reportbool

Whether to print the result of the fit.

kwargs

See scipy.optimize.curve_fit.

Returns:
(popt, pcov)Any

The optimal parameters and their covariance matrix. Additional output if full_output is True. See scipy.optimize.curve_fit. An OptimizeWarning is issued if the covariance of the parameters cannot be estimated.

Raises:
ValueError

If either x or y contain NaNs, if sigma has an invalid shape or if incompatible options are used.

RuntimeError

If the least-squares minimization fails.

TypeError

If the number of parameters exceeds the number of data points for the method "lm".