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()- providing different background models
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,xdatais set tonumpy.array([0.0, 1.0, 2.0, ..., len(y)-1])
- y (Sequence or numpy array or None) – The dependant data y = f(x).ymust have the same shape asxifxis notNone.
- sigmay (Sequence or numpy array or None) – The uncertainties in the ydataarray. These can be used as weights in the least-squares problem, ifweight_flagisTrue. IfNone, the uncertainties are assumed to be 1, unlessweight_flagisTrue, in which case the square-root ofyis used.
- weight_flag (boolean) – If this parameter is Trueandsigmayuncertainties are not specified, the square root ofyis used as weights in the least-squares problem. IfFalse, 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 - xdata range on which the fit was performed
- ‘xmax’: Upeer limit of the - xdata range on which the fit was performed
 
 - 
addbackground(bgname, bgtheory)[source]¶
- Add a new background theory to dictionary - bgtheories.- Parameters: - bgname – String with the name describing the function
- bgtheory (silx.math.fit.fittheory.FitTheory) –FitTheoryobject
 
 - 
addtheory(name, theory=None, function=None, parameters=None, estimate=None, configure=None, derivative=None, description=None, pymca_legacy=False)[source]¶
- Add a new theory to dictionary - theories.- You can pass a name and a - FitTheoryobject as arguments, or alternatively provide all arguments necessary to instantiate a new- FitTheoryobject.- See - loadtheories()for more information on estimation functions, configuration functions and custom derivative functions.- Parameters: - name – String with the name describing the function
- theory (silx.math.fit.fittheory.FitTheory) –FitTheoryobject, defining a fit function and associated information (estimation function, description…). If this parameter is provided, all other parameters, except forname, are ignored.
- function (function) – Mandatory argument if theoryis not provided. See documentation forsilx.math.fit.fittheory.FitTheory.function.
- parameters (list[str]) – Mandatory argument if theoryis not provided. See documentation forsilx.math.fit.fittheory.FitTheory.parameters.
- estimate (function) – See documentation for
silx.math.fit.fittheory.FitTheory.estimate
- configure (function) – See documentation for
silx.math.fit.fittheory.FitTheory.configure
- derivative (function) – See documentation for
silx.math.fit.fittheory.FitTheory.derivative
- description (str) – See documentation for
silx.math.fit.fittheory.FitTheory.description
- config_widget – See documentation for
silx.math.fit.fittheory.FitTheory.config_widget
- pymca_legacy (bool) – See documentation for
silx.math.fit.fittheory.FitTheory.pymca_legacy
 
 - 
configure(**kw)[source]¶
- Configure the current theory by filling or updating the - fitconfigdictionary. 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 - **kwparameters are expected to be fields of- fitconfigto 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_resultswith 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- databeing 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.FitWidgetto 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, estimated=False)[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, usexdata.
- paramlist – List of dictionaries, each dictionary item being a
fit parameter. The dictionary’s format is documented in
fit_results. IfNone(default), use parameters fromfit_results.
- estimated – If True, use estimated parameters.
 - 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- codeis not set to- "IGNORE".
- x – Independent variable where the function is calculated.
If 
 - 
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- THEORYwith 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.fittheoriesand- silx.math.fit.fittheoryfor 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 - theoryis not a key of- bgtheories`.
 - 
setdata(x, y, sigmay=None, xmin=None, xmax=None)[source]¶
- Set data attributes: - xdata0,- ydata0and- sigmay0store the initial data and uncertainties. These attributes are not modified after initialization.
- xdata,- ydataand- sigmaystore the data after removing values where- xdata < xminor- 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 tonumpy.array([0.0, 1.0, 2.0, ..., len(y)-1])
- y (Sequence or numpy array or None) – The dependant data y = f(x).ymust have the same shape asxifxis notNone.
- sigmay (Sequence or numpy array or None) – The uncertainties in the ydataarray. These are used as weights in the least-squares problem. IfNone, 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- sigmay0was filled with actual uncertainties in- setdata(), use these values. Else, use- sqrt(self.ydata).
 - 
disableweight()[source]¶
- This method can be called to set - sigmayequal 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 - theoryis not a key of- theories.
 - 
runfit(callback=None)[source]¶
- Run the actual fitting and fill - fit_resultswith fit results.- Before running this method, - fit_resultsmust 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- databeing 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.FitWidgetto 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.
 
- x (Sequence or numpy array or None) – Abscissa data. If 
