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
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 tonumpy.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 asx
ifx
is notNone
.sigmay (Sequence or numpy array or None) – The uncertainties in the
ydata
array. These can be used as weights in the least-squares problem, ifweight_flag
isTrue
. IfNone
, the uncertainties are assumed to be 1, unlessweight_flag
isTrue
, in which case the square-root ofy
is used.weight_flag (boolean) – If this parameter is
True
andsigmay
uncertainties are not specified, the square root ofy
is 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 inrunfit()
.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
(forn>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
bgname – String with the name describing the function
bgtheory (
silx.math.fit.fittheory.FitTheory
) –FitTheory
object
-
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
FitTheory
object as arguments, or alternatively provide all arguments necessary to instantiate a newFitTheory
object.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
) –FitTheory
object, defining a fit function and associated information (estimation function, description…). If this parameter is provided, all other parameters, except forname
, are ignored.function (callable) – Mandatory argument if
theory
is not provided. See documentation forsilx.math.fit.fittheory.FitTheory.function
.parameters (List[str]) – Mandatory argument if
theory
is not provided. See documentation forsilx.math.fit.fittheory.FitTheory.parameters
.estimate (callable) – See documentation for
silx.math.fit.fittheory.FitTheory.estimate
configure (callable) – See documentation for
silx.math.fit.fittheory.FitTheory.configure
derivative (callable) – 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
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 offitconfig
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)
withdata
being a dictionary. This callback function is called before and after the estimation process, and is given a dictionary containing the values ofstate
('Estimate in progress'
or'Ready to Fit'
) andchisq
. This is used for instance insilx.gui.fit.FitWidget
to update a widget displaying a status message.- Returns
Estimated parameters
-
fit
()[source]¶ Convenience method to call
estimate()
followed byrunfit()
.- 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 fieldcode
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 namedTHEORY
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
andsilx.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 ofbgtheories`
.
-
setdata
(x, y, sigmay=None, xmin=None, xmax=None)[source]¶ Set data attributes:
xdata0
,ydata0
andsigmay0
store the initial data and uncertainties. These attributes are not modified after initialization.xdata
,ydata
andsigmay
store the data after removing values wherexdata < xmin
orxdata > 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)
.y
must have the same shape asx
ifx
is notNone
.sigmay (Sequence or numpy array or None) – The uncertainties in the
ydata
array. 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
. Ifsigmay0
was filled with actual uncertainties insetdata()
, use these values. Else, usesqrt(self.ydata)
.
-
disableweight
()[source]¶ This method can be called to set
sigmay
equal toNone
. 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 oftheories
.
-
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, runestimate()
beforehand.- Parameters
callback – Optional callback function, conforming to the signature
callback(data)
withdata
being a dictionary. This callback function is called before and after the estimation process, and is given a dictionary containing the values ofstate
('Fit in progress'
or'Ready'
) andchisq
. This is used for instance insilx.gui.fit.FitWidget
to update a widget displaying a status message.- Returns
Tuple
(fitted parameters, uncertainties, infodict)
. infodict is the dictionary returned bysilx.math.fit.leastsq()
when called with optionfull_output=True
. Uncertainties is a sequence of uncertainty values associated with each fitted parameter.