Fitter#

Module: exa.core.model_selection_fitter.fitter

class Fitter#

Bases: object

Fitter object that stores the models used for model-selection.

To get started, create an instance of the fitter and add the models you would like to compare. Calling fit() fits all the models to the given data, and selects the best one based on Bayesian information criterion.

Example:


from exa.core import model_selection_fitter as msf import xarray as xr import numpy as np

fitter = msf.Fitter() model = msf.models.LinearModel() fitter.add_model(model) # Add another linear model with fixed offset. model_fixed = msf.models.LinearModel(name=”Fixed”) model_fixed.set_param_hint(“b”, value=0.1, vary=False) fitter.add_model(model_fixed) data = xr.DataArray(np.linspace(-2,2,21) + 0.5, dims=[‘time’], coords={“time”: np.linspace(-1, 1, 21)}) fit_result = fitter.fit(data=data, x=”time”, plot_fit=True)

Create a new Fitter instance.

Methods

add_model

Adds a model to the fitter.

fit

Fits all the models known to the fitter and returns the best model.

plot

Plots the selected quantity.

add_model(model)#

Adds a model to the fitter.

When calling fit method, all the added models are fit and the best model is selected.

Parameters:

model (Model) – Model to add.

Return type:

None

fit(data, datavar='', plot_fit=False, add_plot_to_dataset=False, use_outlier_detection=False, take_indices=None, complex_action='rotate_to_real', reduction_action=None, fitter_options=None, outlier_detection_options=None, override_model_initial_guess=False, extra_parameter_penalty_factor=1, select_by_bic=False, weights=None, **independent_vars)#

Fits all the models known to the fitter and returns the best model.

The independent variables are first extracted from the dataset. After that, complex action is applied to all the data, and the remaining dimensions are reduced by first taking only the indices given by take_index . Reduction action is then applied to all extra dimensions. Finally, the fit is done separately for all the remaining coordinates.

At each step of the fit, all the models are fitted to the data, and the best model is chosen using the Akaike information criterion adjusted for small sample sizes.

Parameters:
  • data (Dataset | DataArray) – Dataset with the data to be fitted. Can be also DataArray, in which case datavar is ignored.

  • datavar (str) – Data variable name. Defaults to None.

  • plot_fit (bool) – If True , the best fit is plotted and shown immediately.

  • add_plot_to_dataset (bool) – If True , plot of the fit is created and added to the dataset. If performance is critical, set this to False and use the “plot_definitions” return callable instead.

  • use_outlier_detection (bool) – If True , uses leave-one-out outlier detection.

  • take_indices (tuple[int] | None) – Picks only the extra dimensions specified by the tuple.

  • complex_action (Literal['real', 'imag', 'rotate_to_real']) – Converts complex values to real. Either ‘real’, ‘imag’, ‘rotate_to_real’. If None, no conversion is done.

  • reduction_action (Literal['mean', 'median'] | None) – Applies the given operation to reduce the remaining dimensions. Either ‘mean’, ‘std’ or None.

  • fitter_options (dict[str, Any] | None) – Key-value pairs for setting lmfit fitter options. If using lmfit models, these are the fitter options accepted by lmfit. If not options are specified, defaults to fitter_options = {"method": "leastsq", "nan_policy": "omit"} Some fitter_options also have impact on how msf does fitting: * nan_policy: if number of independent variables is > 1, changed to “raise”.

  • outlier_detection_options (dict[str, Any] | None) – Key-value pairs for configuring outlier detection.

  • override_model_initial_guess (bool) – If True, initial guess is done using parameter values. If False model.guess function is used instead.

  • extra_parameter_penalty_factor (float) – Add an extra penalty on having more parameters in the model. Used to select the best model.

  • select_by_bic (bool) – If true, select the best fit based on the bayesian information criterion (BIC). If false, select based on the Akaike Information Criterion corrected for small sample sizes.

  • weights (DataArray | None) – Weight factor used to scale the residuals. The weight array must have the same shape as the data. Weights can also be applied through fitter_options, but then the same weights are used for all data points.

  • **independent_vars (str | list[str] | dict[Any, Any] | None) – Maps the given coordinate names in the dataset to the independent variables of the model. For example, if the x-coordinate of the model is called x, and the corresponding coordinate in the dataset is ‘time’, give x=’time’ as the argument. If the model acts on multidimensional data, this can be specified by giving a list of coordinates. For example x = ['time', 'frequency'] .

Returns:

  • fit_result: Data array which elements are the ModelResult s and the coordinates are the remaining

    coordinates of the dataset an extra dimension that contains the names of the fitted models.

  • fit: The evaluated values of the fitted models.

  • initial_guess: The values for the initial guess.

  • uncertainty: The evaluated values for the uncertainty in the fitted data points.

  • plots: Plot of the fit if add_plot_to_dataset is True .

  • plot_definitions: a callable that plots a matplotlib figure, and suggested arguments for the callable.

  • best_model: The best ModelResult for each of the remaining coordinates.

  • best_model_index: The index for the best model for each of the extra dimension.

  • model_probabilities: Probability that each of the model is the best according to AIC.

  • AICs: Akaike information criterion for all the models.

  • AICcs: Akaike information criterion for small samples of all the models.

  • redchis: Reduced chi-square for all the models.

  • r2s: R2 values for all the models.

  • parameters: Fitted parameter values for the best model as separate datavars.

  • parameter_stderr: Standard errors for all the parameters as separate datavars.

Return type:

Xarray Dataset containing the following data variables

plot(quantity, indices=None, coordinate=None, result_index=-1, ax=None, plot_style='point', uncertainty_style='errorbar')#

Plots the selected quantity.

Parameters:
  • quantity (str | list[str]) – Name of the quantity (datavar) or quantities to plot.

  • indices (list[tuple[int] | int] | None) – Coordinate indices to select for plotting. Can be either provided as a flat list of indices or a list of tuples of indices.

  • coordinate (str | list[str] | None) – Coordinate to plot. Can also provide a list of coordinates for mult-dimensinal plots.

  • result_index (int) – index of the fit result to use for plotting.

  • ax (Axes | None) – Axes object for plotting. If None, a new axes is created.

  • plot_style (Literal['point']) – Style of the plot.

  • uncertainty_style (Literal['errorbar', 'fill']) – Style for uncertainties, options are ‘errorbar’ or ‘fill’.

Returns:

Matplotlib figure which contains the axes.

Return type:

FigureBase | None

Inheritance

Inheritance diagram of exa.core.model_selection_fitter.fitter.Fitter