Fit

class sherpa.fit.Fit(data: Data | DataSimulFit, model: Model, stat: Stat | None = None, method: OptMethod | None = None, estmethod: EstMethod | None = None, itermethod_opts: Mapping[str, Any] | None = None)[source] [edit on github]

Bases: NoNewAttributesAfterInit

Fit a model to a data set.

Changed in version 4.18.0: Prior to 4.18.0 changing the method field would not change the method used by fit and esterrors, just the label shown when a Fit object is printed.

Changed in version 4.17.0: Changing the stat field now changes the internal IterFit object as well.

Parameters:
datasherpa.data.Data or sherpa.data.DataSimulFit

The data to be fit.

modelsherpa.models.model.Model or sherpa.models.model.SimulFitModel

The model to fit to the data. It should match the data parameter (i.e. be a SimulFitModel object when data is a DataSimulFit).

statsherpa.stats.Stat or None, optional

The statistic object to use. If not given then Chi2Gehrels is used.

methodsherpa.optmethods.OptMethod instance or None, optional

The optimiser to use. If not given then sherpa.optmethods.LevMar is used.

estmethodsherpa.estmethods.EstMethod or None, optional

The class used to calculate errors. If not given then sherpa.estmethods.Covariance is used.

itermethod_optsdict or None, optional

If set, defines the iterated-fit method and options to use. It is passed through to IterFit.

Attributes:
method

Set or get the method object

stat

Set or get the statistic object

Methods

calc_chisqr()

Calculate the per-bin chi-squared statistic.

calc_stat()

Calculate the statistic value.

calc_stat_info()

Calculate the statistic value and related information.

est_errors([methoddict, parlist])

Estimate errors.

fit([outfile, clobber, numcores, record_steps])

Fit the model to the data.

guess(**kwargs)

Guess parameter values and limits.

simulfit(*others)

Fit multiple data sets and models simultaneously.

Attributes Summary

method

Set or get the method object

stat

Set or get the statistic object

Methods Summary

calc_chisqr()

Calculate the per-bin chi-squared statistic.

calc_stat()

Calculate the statistic value.

calc_stat_info()

Calculate the statistic value and related information.

est_errors([methoddict, parlist])

Estimate errors.

fit([outfile, clobber, numcores, record_steps])

Fit the model to the data.

guess(**kwargs)

Guess parameter values and limits.

simulfit(*others)

Fit multiple data sets and models simultaneously.

Attributes Documentation

method

Set or get the method object

stat

Set or get the statistic object

Methods Documentation

calc_chisqr() ndarray | None[source] [edit on github]

Calculate the per-bin chi-squared statistic.

Evaluate the per-bin statistic for the current model and data settings (e.g. parameter values and data filters).

Returns:
chisqarray or None

The chi-square value for each bin of the data, using the current statistic. A value of None is returned if the statistic is not a chi-square distribution.

calc_stat() float[source] [edit on github]

Calculate the statistic value.

Evaluate the statistic for the current model and data settings (e.g. parameter values and data filters).

Returns:
statnumber

The current statistic value.

calc_stat_info() StatInfoResults[source] [edit on github]

Calculate the statistic value and related information.

Evaluate the statistic for the current model and data settings (e.g. parameter values and data filters).

Returns:
statinfoStatInfoResults instance

The current statistic value.

est_errors(methoddict: Mapping[str, Any] | None = None, parlist: Sequence[Parameter] | None = None) ErrorEstResults[source] [edit on github]

Estimate errors.

Calculate the low and high errors for one or more of the thawed parameters in the fit.

Parameters:
methoddictdict or None, optional

A dictionary mapping from lower-cased method name to the associated optimisation method instance to use. This is only used if the method is changed, as described in the Notes section below.

parlistsequence of sherpa.models.parameter.Parameter or None, optional

The names of the parameters for which the errors should be calculated. If set to None then all the thawed parameters are used.

Returns:
resErrorEstResults
Raises:
sherpa.utils.err.EstErr

If any parameter in parlist is not valid (i.e. is not thawed or is not a member of the model expression being fit), or if the statistic is LeastSq, or if the reduced chi-square value of the current parameter values is larger than the max_rstat option (for chi-square statistics).

See also

fit

Notes

If a new minimum is found for any parameter then the calculation is automatically started for all the parameters using this new best-fit location. This can repeat until the maxfits option is reached.

Unless the Covariance estimator is being used, or the fast option is unset, then the method will be changed to NelderMead (for likelihood-based statistics) or LevMar (for chi-square based statistics) whilst calculating the errors.

fit(outfile: str | Path | WriteableTextFile | None = None, clobber: bool = False, numcores: int | None = 1, record_steps: bool = False) FitResults[source] [edit on github]

Fit the model to the data.

Changed in version 4.17.0: The outfile parameter can now be sent a Path object or a file handle instead of a string.

Changed in version 4.17.1: The parameter record_steps was added to keep parameter values of each iteration in the FitResults object that is returned.

Parameters:
outfilestr, Path, IO object, or None, optional

If not None then information on the fit is written to this file (as defined by a filename, path, or file handle).

clobberbool, optional

Determines if the output file can be overwritten. This is only used when outfile is a string or Path object.

numcoresint or None, optional

The number of cores to use in fitting simultaneous data. This argument is currently unused.

record_stepsbool, optional

If True, then the parameter values and statistic value are recorded at each iteration in a dictionary in the FitResults object that this method returns.

Returns:
fitresFitResults
Raises:
sherpa.utils.err.FitErr

This is raised if clobber is False and outfile already exists or if all the bins have been masked out of the fit.

See also

est_errors, simulfit

Notes

The file created when outfile is set is a simple ASCII file with a header line containing the text “# nfev statistic” and then a list of the thawed parameters, and then one line for each iteration, with the values separated by spaces. If outfile is sent a file handle it is not closed by this routine.

Examples

Fit a very-simple model (a constant value) to a small 1D dataset:

>>> from sherpa.data import Data1D
>>> from sherpa.models.basic import Const1D
>>> from sherpa.stats import LeastSq
>>> from sherpa.fit import Fit
>>> d = Data1D("x", [-3, 5, 17, 22], [12, 3, 8, 5])
>>> m = Const1D()
>>> s = LeastSq()
>>> f = Fit(d, m, stat=s)
>>> out = f.fit()
>>> if not out.succeeded: print("Fit failed")
>>> print(out.format())
Method                = levmar
Statistic             = leastsq
Initial fit statistic = 190
Final fit statistic   = 46 at function evaluation 4
Data points           = 4
Degrees of freedom    = 3
Change in statistic   = 144
   const1d.c0     7            +/- 0.5
>>> print(m)
const1d
   Param        Type          Value          Min          Max      Units
   -----        ----          -----          ---          ---      -----
   const1d.c0   thawed            7 -3.40282e+38  3.40282e+38

Repeat the fit, after resetting the model, so we can see how the optimiser searched the parameter space:

>>> m.reset()
>>> out = f.fit(record_steps=True)
>>> for row in out.record_steps:
...     print(f"{row['nfev']} {row['statistic']:8.6e} {row['const1d.c0']:6.4f}")
0 1.900000e+02 1.0000
1 1.900000e+02 1.0000
2 1.899834e+02 1.0003
3 4.600000e+01 7.0000
4 4.600002e+01 7.0024
5 4.600000e+01 7.0000

This format is also easy to plot, e.g. plt.plot(out.record_steps['nfev'], out.record_steps['statistic']).

Output could also be file-based or captured using io.StringIO:

>>> from io import StringIO
>>> m.reset()
>>> optdata = StringIO()
>>> out2 = f.fit(outfile=optdata)
>>> print(optdata.getvalue())
# nfev statistic const1d.c0
0.000000e+00 1.900000e+02 1.000000e+00
1.000000e+00 1.900000e+02 1.000000e+00
2.000000e+00 1.899834e+02 1.000345e+00
3.000000e+00 4.600000e+01 7.000000e+00
4.000000e+00 4.600002e+01 7.002417e+00
5.000000e+00 4.600000e+01 7.000000e+00
guess(**kwargs) None[source] [edit on github]

Guess parameter values and limits.

The model’s sherpa.models.model.Model.guess method is called with the data values (the dependent axis of the data set) and the kwargs arguments.

simulfit(*others: Fit) FitResults[source] [edit on github]

Fit multiple data sets and models simultaneously.

The current fit object is combined with the other fit objects and a simultaneous fit is made, using the object’s statistic and optimisation method.

Parameters:
*otherssherpa.fit.Fit instances

The data and model attributes of these arguments are used, along with those from the object.

Returns:
fitresFitResults

See also

fit