AbstractFitFunction

class plasmapy.analysis.fit_functions.AbstractFitFunction(params: tuple[float, ...] | None = None, param_errors: tuple[float, ...] | None = None)[source]

Bases: ABC

Abstract class for defining fit functions \(f(x)\) and the tools for fitting the function to a set of data.

Parameters:
  • params (tuple[float, ...], optional) – Tuple of values for the function parameters. Equal in size to param_names.

  • param_errors (tuple[float, ...], optional) – Tuple of values for the errors associated with the function parameters. Equal in size to param_names.

Attributes Summary

FitParamTuple

A namedtuple used for attributes params and param_errors.

curve_fit_results

The results returned by the curve fitting routine used by curve_fit.

latex_str

LaTeX friendly representation of the fit function.

param_errors

The associated errors of the fitted params.

param_names

Names of the fitted parameters.

params

The fitted parameters for the fit function.

rsq

Coefficient of determination (r-squared) value of the fit.

Methods Summary

__call__(x[, x_err, reterr])

Direct call of the fit function \(f(x)\).

curve_fit(xdata, ydata, **kwargs)

Use a non-linear least squares method to fit the fit function to (xdata, ydata), using scipy.optimize.curve_fit.

func(x, *args)

The fit function.

func_err(x[, x_err, rety])

Calculate dependent variable uncertainties \(\delta y\) for dependent variables \(y=f(x)\).

root_solve(x0)

Solve for the root of the fit function (i.e. \(f(x_r) = 0\)).

Attributes Documentation

FitParamTuple

A namedtuple used for attributes params and param_errors. The attribute param_names defines the tuple field names.

curve_fit_results

The results returned by the curve fitting routine used by curve_fit. This is typically from scipy.stats.linregress or scipy.optimize.curve_fit.

latex_str

LaTeX friendly representation of the fit function.

param_errors

The associated errors of the fitted params.

param_names

Names of the fitted parameters.

params

The fitted parameters for the fit function.

rsq

Coefficient of determination (r-squared) value of the fit.

\[ \begin{align}\begin{aligned}r^2 &= 1 - \frac{SS_{res}}{SS_{tot}}\\SS_{res} &= \sum\limits_{i} (y_i - f(x_i))^2\\SS_{tot} &= \sum\limits_{i} (y_i - \bar{y})^2\end{aligned}\end{align} \]

where \((x_i, y_i)\) are the sample data pairs, \(f(x_i)\) is the fitted dependent variable corresponding to \(x_i\), and \(\bar{y}\) is the average of the \(y_i\) values.

The \(r^2\) value is an indicator of how close the points \((x_i, y_i)\) lie to the model \(f(x)\). \(r^2\) values range between 0 and 1. Values close to 0 indicate that the points are uncorrelated and have little tendency to lie close to the model, whereas, values close to 1 indicate a high correlation to the model.

Methods Documentation

__call__(x, x_err=None, reterr: bool = False)[source]

Direct call of the fit function \(f(x)\).

Parameters:
  • x (array_like) – Dependent variables.

  • x_err (array_like, optional) – Errors associated with the independent variables x. Must be of size one or equal to the size of x.

  • reterr (bool, optional) – (Default: False) If True, return an array of uncertainties associated with the calculated independent variables

Returns:

  • y (numpy.ndarray) – Corresponding dependent variables \(y=f(x)\) of the independent variables x.

  • y_err (numpy.ndarray) – Uncertainties associated with the calculated dependent variables \(\delta y\)

curve_fit(xdata, ydata, **kwargs) None[source]

Use a non-linear least squares method to fit the fit function to (xdata, ydata), using scipy.optimize.curve_fit. This will set the attributes params, param_errors, and rsq.

The results of scipy.optimize.curve_fit can be obtained via curve_fit_results.

Parameters:
  • xdata (array_like) – The independent variable where data is measured. Should be 1D of length M.

  • ydata (array_like) – The dependent data associated with xdata.

  • **kwargs – Any keywords accepted by scipy.optimize.curve_fit.

Raises:
  • ValueError – If either ydata or xdata contain numpy.nan’s, or if incompatible options are used.

  • RuntimeError – If the least-squares minimization fails.

  • OptimizeWarning – If covariance of the parameters can not be estimated.

abstract func(x, *args)[source]

The fit function. This signature of the function must first take the independent variable followed by the parameters to be fitted as separate arguments.

Parameters:
  • x (array_like) – Independent variables to be passed to the fit function.

  • *args (tuple[Union[float, int],...]) – The parameters that will be adjusted to make the fit.

Returns:

The calculated dependent variables of the independent variables x.

Return type:

numpy.ndarray

Notes

  • When sub-classing the definition should look something like:

    def func(self, x, a, b, c):
        x = self._check_x(x)
        self._check_params(a, b, c)
    
        return a * x**2 + b * x + c
    
abstract func_err(x, x_err=None, rety: bool = False)[source]

Calculate dependent variable uncertainties \(\delta y\) for dependent variables \(y=f(x)\).

Parameters:
  • x (array_like) – Independent variables to be passed to the fit function.

  • x_err (array_like, optional) – Errors associated with the independent variables x. Must be of size one or equal to the size of x.

  • rety (bool) – Set to True to also return the associated dependent variables \(y = f(x)\).

Returns:

  • err (numpy.ndarray) – The calculated uncertainties \(\delta y\) of the dependent variables (\(y = f(x)\)) of the independent variables x.

  • y (numpy.ndarray, optional) – (if rety == True) The associated dependent variables \(y = f(x)\).

Notes

  • A good reference for formulating propagation of uncertainty expressions is:

    J. R. Taylor. An Introduction to Error Analysis: The Study of Uncertainties in Physical Measurements. University Science Books, second edition, August 1996 (ISBN: 093570275X)

  • When sub-classing the definition should look something like:

    @modify_docstring(append=AbstractFitFunction.func_err.__original_doc__)
    def func_err(self, x, x_err=None, rety=False):
        '''
        A simple docstring giving the equation for error propagation, but
        excluding the parameter descriptions.  The @modify_docstring
        decorator will append the docstring from the parent class.
        '''
        x, x_err = self._check_func_err_params(x, x_err)
    
        a, b, c = self.params
        a_err, b_err, c_err = self.param_errors
    
        # calculate error
    
        if rety:
            y = self.func(x, a, b, c)
            return err, y
    
        return err
    
root_solve(x0)[source]

Solve for the root of the fit function (i.e. \(f(x_r) = 0\)). This method used scipy.optimize.fsolve to find the function roots.

Parameters:

x0 (ndarray) – The starting estimate for the roots of \(f(x_r) = 0\).

Returns:

  • x (ndarray) – The solution (or the result of the last iteration for an unsuccessful call).

  • x_err (ndarray) – The uncertainty associated with the root calculation. Currently this returns an array of numpy.nan values equal in shape to x , since there is no determined way to calculate the uncertainties.

Notes

If the full output of scipy.optimize.fsolve is desired then one can do:

>>> func = Linear()
>>> func.params = (1.0, 5.0)
>>> func.param_errors = (0.0, 0.0)
>>> roots = fsolve(func, -4.0, full_output=True)
>>> roots
(array([-5.]),
 {'nfev': 4,
  'fjac': array([[-1.]]),
  'r': array([-1.]),
  'qtf': array([2.18...e-12]),
  'fvec': 0.0},
 1,
 'The solution converged.')