fitmanager: Fit functions manager

This module provides a tool to perform advanced fitting. The actual fit relies on silx.math.fit.leastsq().

This module deals with:

  • handling of the model functions (using a set of default functions or loading custom user functions)
  • handling of estimation function, that are used to determine the number of parameters to be fitted for functions with unknown number of parameters (such as the sum of a variable number of gaussian curves), and find reasonable initial parameters for input to the iterative fitting algorithm
  • handling of custom derivative functions that can be passed as a parameter to silx.math.fit.leastsq()
  • removal of constant and linear background signal prior to performing the actual fit

For a tutorial on how to use FitManager, see Using FitManager.

API

class silx.math.fit.fitmanager.FitManager(x=None, y=None, sigmay=None, weight_flag=False)[source]

Fit functions manager

Parameters:
  • x (Sequence or numpy array or None) – Abscissa data. If None, xdata is set to numpy.array([0.0, 1.0, 2.0, ..., len(y)-1])
  • y (Sequence or numpy array or None) – The dependant data y = f(x). y must have the same shape as x if x is not None.
  • sigmay (Sequence or numpy array or None) – The uncertainties in the ydata array. These can be used as weights in the least-squares problem, if weight_flag is True. If None, the uncertainties are assumed to be 1, unless weight_flag is True, in which case the square-root of y is used.
  • weight_flag (boolean) – If this parameter is True and sigmay uncertainties are not specified, the square root of y is used as weights in the least-squares problem. If False, the uncertainties are set to 1.
fitconfig = None

Dictionary of fit configuration parameters. These parameters can be modified using the configure() method.

Keys are:

  • ‘fitbkg’: name of the function used for fitting a low frequency background signal
  • ‘FwhmPoints’: default full width at half maximum value for the peaks’.
  • ‘Sensitivity’: Sensitivity parameter for the peak detection algorithm (silx.math.fit.peak_search())
fit_results = None

This list stores detailed information about all fit parameters. It is initialized in estimate() and completed with final fit values in runfit().

Each fit parameter is stored as a dictionary with following fields:

  • ‘name’: Parameter name.

  • ‘estimation’: Estimated value.

  • ‘group’: Group number. Group 0 corresponds to the background function parameters. Group n (for n>0) corresponds to the fit function parameters for the n-th peak.

  • ‘code’: Constraint code

    • 0 - FREE
    • 1 - POSITIVE
    • 2 - QUOTED
    • 3 - FIXED
    • 4 - FACTOR
    • 5 - DELTA
    • 6 - SUM
  • ‘cons1’:

    • Ignored if ‘code’ is FREE, POSITIVE or FIXED.
    • Min value of the parameter if code is QUOTED
    • Index of fitted parameter to which ‘cons2’ is related if code is FACTOR, DELTA or SUM.
  • ‘cons2’:

    • Ignored if ‘code’ is FREE, POSITIVE or FIXED.
    • Max value of the parameter if QUOTED
    • Factor to apply to related parameter with index ‘cons1’ if ‘code’ is FACTOR
    • Difference with parameter with index ‘cons1’ if ‘code’ is DELTA
    • Sum obtained when adding parameter with index ‘cons1’ if ‘code’ is SUM
  • ‘fitresult’: Fitted value.

  • ‘sigma’: Standard deviation for the parameter estimate

  • ‘xmin’: Lower limit of the x data range on which the fit was performed

  • ‘xmax’: Upeer limit of the x data range on which the fit was performed

addbackground(bgname, bgtheory)[source]

Add a new background theory to dictionary bgtheories.

Parameters:
addtheory(name, theory=None, function=None, parameters=None, estimate=None, configure=None, derivative=None, description=None, config_widget=None, pymca_legacy=False)[source]

Add a new theory to dictionary theories.

You can pass a name and a FitTheory object as arguments, or alternatively provide all arguments necessary to instantiate a new FitTheory object.

See loadtheories() for more information on estimation functions, configuration functions and custom derivative functions.

Parameters:
configure(**kw)[source]

Configure the current theory by filling or updating the fitconfig dictionary. Call the custom configuration function, if any. This allows the user to modify the behavior of the custom fit function or the custom estimate function.

This methods accepts only named parameters. All **kw parameters are expected to be fields of fitconfig to be updated, unless they have a special meaning for the custom configuration function of the currently selected theory..

This method returns the modified config dictionary returned by the custom configuration function.

estimate(callback=None)[source]

Fill fit_results with an estimation of the fit parameters.

At first, the background parameters are estimated, if a background model has been specified. Then, a custom estimation function related to the model function is called.

This process determines the number of needed fit parameters and provides an initial estimation for them, to serve as an input for the actual iterative fitting performed in runfit().

Parameters:callback – Optional callback function, conforming to the signature callback(data) with data being a dictionary. This callback function is called before and after the estimation process, and is given a dictionary containing the values of state ('Estimate in progress' or 'Ready to Fit') and chisq. This is used for instance in silx.gui.fit.FitWidget to update a widget displaying a status message.
Returns:Estimated parameters
fit()[source]

Convenience method to call estimate() followed by runfit().

Returns:Output of runfit()
gendata(x=None, paramlist=None)[source]

Return a data array using the currently selected fit function and the fitted parameters.

Parameters:
  • x – Independent variable where the function is calculated. If None, use xdata.
  • paramlist – List of dictionaries, each dictionary item being a fit parameter. The dictionary’s format is documented in fit_results. If None (default), use parameters from fit_results.
Returns:

fitfunction() calculated for parameters whose code is not set to "IGNORE".

This calculates fitfunction() on x data using fit parameters from a list of parameter dictionaries, if field code is not set to "IGNORE".

loadtheories(theories)[source]

Import user defined fit functions defined in an external Python source file, and save them in theories.

An example of such a file can be found in the sources of silx.math.fit.fittheories. It must contain a dictionary named THEORY with the following structure:

THEORY = {
    'theory_name_1':
        FitTheory(description='Description of theory 1',
                  function=fitfunction1,
                  parameters=('param name 1', 'param name 2', …),
                  estimate=estimation_function1,
                  configure=configuration_function1,
                  derivative=derivative_function1),
    'theory_name_2':
        FitTheory(…),
}

See documentation of silx.math.fit.fittheories and silx.math.fit.fittheory for more information on designing your fit functions file.

This method can also load user defined functions in the legacy format used in PyMca.

Parameters:theories – Name of python source file, or module containing the definition of fit functions.
Raise:ImportError if theories cannot be imported
setbackground(theory)[source]

Choose a background type from within bgtheories.

This updates selectedbg.

Parameters:theory – The name of the background to be used.
Raise:KeyError if theory is not a key of bgtheories`.
setdata(x, y, sigmay=None, xmin=None, xmax=None)[source]

Set data attributes:

  • xdata0, ydata0 and sigmay0 store the initial data and uncertainties. These attributes are not modified after initialization.
  • xdata, ydata and sigmay store the data after removing values where xdata < xmin or xdata > xmax. These attributes may be modified at a latter stage by filters.
Parameters:
  • x (Sequence or numpy array or None) – Abscissa data. If None, xdata` is set to numpy.array([0.0, 1.0, 2.0, ..., len(y)-1])
  • y (Sequence or numpy array or None) – The dependant data y = f(x). y must have the same shape as x if x is not None.
  • sigmay (Sequence or numpy array or None) – The uncertainties in the ydata array. These are used as weights in the least-squares problem. If None, the uncertainties are assumed to be 1.
  • xmin – Lower value of x values to use for fitting
  • xmax – Upper value of x values to use for fitting
enableweight()[source]

This method can be called to set sigmay. If sigmay0 was filled with actual uncertainties in setdata(), use these values. Else, use sqrt(self.ydata).

disableweight()[source]

This method can be called to set sigmay equal to None. As a result, leastsq() will consider that the weights in the least square problem are 1 for all samples.

settheory(theory)[source]

Pick a theory from theories.

Parameters:theory – Name of the theory to be used.
Raise:KeyError if theory is not a key of theories.
runfit(callback=None)[source]

Run the actual fitting and fill fit_results with fit results.

Before running this method, fit_results must already be populated with a list of all parameters and their estimated values. For this, run estimate() beforehand.

Parameters:callback – Optional callback function, conforming to the signature callback(data) with data being a dictionary. This callback function is called before and after the estimation process, and is given a dictionary containing the values of state ('Fit in progress' or 'Ready') and chisq. This is used for instance in silx.gui.fit.FitWidget to update a widget displaying a status message.
Returns:Tuple (fitted parameters, uncertainties, infodict). infodict is the dictionary returned by silx.math.fit.leastsq() when called with option full_output=True. Uncertainties is a sequence of uncertainty values associated with each fitted parameter.

Table Of Contents

Previous topic

Smoothing and background filters

Next topic

fittheory: Fit theory definition

This Page