lsqfit - Nonlinear Least Squares Fitting¶
Introduction¶
This package contains tools for nonlinear least-squares curve fitting of data. In general a fit has four inputs:
- The dependent data
ythat is to be fit — typicallyyis a Python dictionary in anlsqfitanalysis. Its valuesy[k]are eithergvar.GVars or arrays (any shape or dimension) ofgvar.GVars that specify the values of the dependent variables and their errors.- A collection
xof independent data —xcan have any structure and contain any data (or no data).- A fit function
f(x, p)whose parameterspare adjusted by the fit untilf(x, p)equalsyto withinys errors — parameters p` are usually specified by a dictionary whose valuesp[k]are individual parameters or (numpy) arrays of parameters. The fit function is assumed independent ofx(that is,f(p)) ifx = False(or ifxis omitted from the input data).- Initial estimates or priors for each parameter in
p— priors are usually specified using a dictionarypriorwhose valuesprior[k]aregvar.GVars or arrays ofgvar.GVars that give initial estimates (values and errors) for parametersp[k].
A typical code sequence has the structure:
... collect x, y, prior ...
def f(x, p):
... compute fit to y[k], for all k in y, using x, p ...
... return dictionary containing the fit values for the y[k]s ...
fit = lsqfit.nonlinear_fit(data=(x, y), prior=prior, fcn=f)
print(fit) # variable fit is of type nonlinear_fit
The parameters p[k] are varied until the chi**2 for the fit is
minimized.
The best-fit values for the parameters are recovered after fitting
using, for example, p=fit.p. Then the p[k] are gvar.GVars or
arrays of gvar.GVars that give best-fit estimates and fit uncertainties
in those estimates. The print(fit) statement prints a summary of
the fit results.
The dependent variable y above could be an array instead of a
dictionary, which is less flexible in general but possibly more
convenient in simpler fits. Then the approximate y returned by fit
function f(x, p) must be an array with the same shape as the dependent
variable. The prior prior could also be represented by an array
instead of a dictionary.
The lsqfit tutorial contains extended explanations and examples.
The first appendix in the paper at http://arxiv.org/abs/arXiv:1406.2279
provides conceptual background on the techniques used in this
module for fits and, especially, error budgets.
nonlinear_fit Objects¶
-
class
lsqfit.nonlinear_fit(data, fcn, prior=None, p0=None, svdcut=1e-15, debug=False, **kargs)¶ Nonlinear least-squares fit.
lsqfit.nonlinear_fitfits a (nonlinear) functionf(x, p)to datayby varying parametersp, and stores the results: for example,fit = nonlinear_fit(data=(x, y), fcn=f, prior=prior) # do fit print(fit) # print fit results
The best-fit values for the parameters are in
fit.p, while thechi**2, the number of degrees of freedom, the logarithm of Gaussian Bayes Factor, the number of iterations, and the cpu time needed for the fit are infit.chi2,fit.dof,fit.logGBF,fit.nit, andfit.time, respectively. Results for individual parameters infit.pare of typegvar.GVar, and therefore carry information about errors and correlations with other parameters. The fit data and prior can be recovered usingfit.x(equalsFalseif there is nox),fit.y, andfit.prior; the data and prior are corrected for the svd cut, if there is one (that is, their covariance matrices have been modified in accordance with the svd cut).Parameters: - data –
Data to be fit by
lsqfit.nonlinear_fit. It can have any of the following formats:data = x, yxis the independent data that is passed to the fit function with the fit parameters:fcn(x, p).yis a dictionary (or array) ofgvar.GVars that encode the means and covariance matrix for the data that is to be fit being fit. The fit function must return a result having the same layout asy.data = yyis a dictionary (or array) ofgvar.GVars that encode the means and covariance matrix for the data being fit. There is no independent data so the fit function depends only upon the fit parameters:fit(p). The fit function must return a result having the same layout asy.data = x, ymean, ycovxis the independent data that is passed to the fit function with the fit parameters:fcn(x, p).ymeanis an array containing the mean values of the fit data.ycovis an array containing the covariance matrix of the fit data;ycov.shapeequals2*ymean.shape. The fit function must return an array having the same shape asymean.data = x, ymean, ysdevxis the independent data that is passed to the fit function with the fit parameters:fcn(x, p).ymeanis an array containing the mean values of the fit data.ysdevis an array containing the standard deviations of the fit data;ysdev.shapeequalsymean.shape. The data are assumed to be uncorrelated. The fit function must return an array having the same shape asymean.
Setting
x=Falsein the first, third or fourth of these formats implies that the fit function depends only on the fit parameters: that is,fcn(p)instead offcn(x, p). (This is not assumed ifx=None.) - fcn (function) – The function to be fit to
data. It is either a function of the independent dataxand the fit parametersp(fcn(x, p)), or a function of just the fit parameters (fcn(p)) when there is noxdata orx=False. The parameters are tuned in the fit until the function returns values that agree with theydata to within theys’ errors. The function’s return value must have the same layout as theydata (a dictionary or an array). The fit parameterspare either: 1) a dictionary where eachp[k]is a single parameter or an array of parameters (any shape); or, 2) a single array of parameters. The layout of the parameters is the same as that of priorpriorif it is specified; otherwise, it is inferred from of the starting valuep0for the fit. - prior (dictionary, array, or
None) – A dictionary (or array) containing a priori estimates for all parameterspused by fit functionfcn(x, p)(orfcn(p)). Fit parameterspare stored in a dictionary (or array) with the same keys and structure (or shape) asprior. The default value isNone;priormust be defined ifp0isNone. - p0 (dictionary, array, string or
None) – Starting values for fit parameters in fit.lsqfit.nonlinear_fitadjustsp0to make it consistent in shape and structure withpriorwhen the latter is specified: elements missing fromp0are filled in usingprior, and elements inp0that are not inpriorare discarded. Ifp0is a string, it is taken as a file name andlsqfit.nonlinear_fitattempts to read starting values from that file; best-fit parameter values are written out to the same file after the fit (for priming future fits). Ifp0isNoneor the attempt to read the file fails, starting values are extracted fromprior. The default value isNone;p0must be defined ifpriorisNone. - svdcut (
Noneorfloat) – Ifsvdcutis nonzero (notNone), svd cuts are applied to every block-diagonal sub-matrix of the covariance matrix for the datayandprior(if there is a prior). The blocks are first rescaled so that all diagonal elements equal 1 – that is, the blocks are replaced by the correlation matrices for the corresponding subsets of variables. Then, ifsvdcut > 0, eigenvalues of the rescaled matrices that are smaller thansvdcuttimes the maximum eigenvalue are replaced bysvdcuttimes the maximum eigenvalue. This makes the covariance matrix less singular and less susceptible to roundoff error. Whensvdcut < 0, eigenvalues smaller than|svdcut|times the maximum eigenvalue are discarded and the corresponding components inyandpriorare zeroed out. - debug (boolean) – Set to
Truefor extra debugging of the fit function and a check for roundoff errors. (Default isFalse.) - fitterargs – Dictionary of arguments passed on to
lsqfit.multifit, which does the fitting.
The results from the fit are accessed through the following attributes (of
fitwherefit = nonlinear_fit(...)):-
chi2¶ The minimum
chi**2for the fit.fit.chi2 / fit.dofis usually of order one in good fits; values much less than one suggest that the actual standard deviations in the input data and/or priors are smaller than the standard deviations used in the fit.
-
cov¶ Covariance matrix of the best-fit parameters from the fit.
-
dof¶ Number of degrees of freedom in the fit, which equals the number of pieces of data being fit when priors are specified for the fit parameters. Without priors, it is the number of pieces of data minus the number of fit parameters.
-
logGBF¶ The logarithm of the probability (density) of obtaining the fit data by randomly sampling the parameter model (priors plus fit function) used in the fit. This quantity is useful for comparing fits of the same data to different models, with different priors and/or fit functions. The model with the largest value of
fit.logGBFis the one prefered by the data. The exponential of the difference infit.logGBFbetween two models is the ratio of probabilities (Bayes factor) for those models. Differences infit.logGBFsmaller than 1 are not very significant. Gaussian statistics are assumed when computingfit.logGBF.
-
p¶ Best-fit parameters from fit. Depending upon what was used for the prior (or
p0), it is either: a dictionary (gvar.BufferDict) ofgvar.GVars and/or arrays ofgvar.GVars; or an array (numpy.ndarray) ofgvar.GVars.fit.prepresents a multi-dimensional Gaussian distribution which, in Bayesian terminology, is the posterior probability distribution of the fit parameters.
-
pmean¶ Means of the best-fit parameters from fit (dictionary or array).
-
psdev¶ Standard deviations of the best-fit parameters from fit (dictionary or array).
-
palt¶ Same as
fit.pexcept that the errors are computed directly fromfit.cov. This is faster but means that no information about correlations with the input data is retained (unlike infit.p); and, therefore,fit.paltcannot be used to generate error budgets.fit.pandfit.paltgive the same means and normally give the same errors for each parameter. They differ only when the input data’s covariance matrix is too singular to invert accurately (because of roundoff error), in which case an SVD cut is advisable.
-
transformed_p¶ Same as
fit.pbut augmented to include the transforms of any log-normal or other parameter implemented using decoratorlsqfit.transform_p. In the case of a log-normal variablefit.p['logXX'], for example,fit.transformed_p['XX']is defined equal toexp(fit.p['logXX']).
-
p0¶ The parameter values used to start the fit.
-
Q¶ The probability that the
chi**2from the fit could have been larger, by chance, assuming the best-fit model is correct. Good fits haveQvalues larger than 0.1 or so. Also called the p-value of the fit.
-
svdcorrection¶ The sum of all SVD corrections, if any, added to the fit data
yor the priorprior.
-
svdn¶ The number of eignemodes modified (and/or deleted) by the SVD cut.
-
nblocks¶ A dictionary where
nblocks[s]equals the number of block-diagonal sub-matrices of they–priorcovariance matrix that are sizes-by-s. This is sometimes useful for debugging.
-
time¶ CPU time (in secs) taken by fit.
The input parameters to the fit can be accessed as attributes. Note in particular attributes:
-
prior¶ Prior used in the fit. This may differ from the input prior if an SVD cut is used. It is either a dictionary (
gvar.BufferDict) or an array (numpy.ndarray), depending upon the input. EqualsNoneif no prior was specified.
-
x¶ The first field in the input
data. This is sometimes the independent variable (as in ‘y vs x’ plot), but may be anything. It is set equal toFalseif thexfield is omitted from the inputdata. (This also means that the fit function has noxargument: sof(p)rather thanf(x,p).)
-
y¶ Fit data used in the fit. This may differ from the input data if an SVD cut is used. It is either a dictionary (
gvar.BufferDict) or an array (numpy.ndarray), depending upon the input.
Additional methods are provided for printing out detailed information about the fit, testing fits with simulated data, doing bootstrap analyses of the fit errors, dumping (for later use) and loading parameter values, and checking for roundoff errors in the final error estimates:
-
format(maxline=0, pstyle='v')¶ Formats fit output details into a string for printing.
The output tabulates the
chi**2per degree of freedom of the fit (chi2/dof), the number of degrees of freedom, the logarithm of the Gaussian Bayes Factor for the fit (logGBF), and the number of fit-algorithm iterations needed by the fit. Optionally, it will also list the best-fit values for the fit parameters together with the prior for each (in[]on each line). It can also list all of the data and the corresponding values from the fit. At the end it lists the SVD cut, the number of eigenmodes modified by the SVD cut, the relative and absolute tolerances used in the fit, and the time in seconds needed to do the fit.Parameters: - maxline (integer or bool) – Maximum number of data points for which fit
results and input data are tabulated.
maxline<0implies that onlychi2,Q,logGBF, anditnsare tabulated; no parameter values are included. Settingmaxline=Trueprints all data points; setting it equalNoneorFalseis the same as setting it equal to-1. Default ismaxline=0. - pstyle (‘vv’, ‘v’, or ‘m’) – Style used for parameter list. Supported values are ‘vv’ for very verbose, ‘v’ for verbose, and ‘m’ for minimal. When ‘m’ is set, only parameters whose values differ from their prior values are listed.
Returns: String containing detailed information about fit.
- maxline (integer or bool) – Maximum number of data points for which fit
results and input data are tabulated.
-
fmt_errorbudget(outputs, inputs, ndecimal=2, percent=True)¶ Tabulate error budget for
outputs[ko]due toinputs[ki].For each output
outputs[ko],fmt_errorbudgetcomputes the contributions tooutputs[ko]‘s standard deviation coming from thegvar.GVars collected ininputs[ki]. This is done for each key combination(ko,ki)and the results are tabulated with columns and rows labeled bykoandki, respectively. If agvar.GVarininputs[ki]is correlated with othergvar.GVars, the contribution from the others is included in thekicontribution as well (since contributions from correlatedgvar.GVars cannot be distinguished). The table is returned as a string.Parameters: - outputs – Dictionary of
gvar.GVars for which an error budget is computed. - inputs – Dictionary of:
gvar.GVars, arrays/dictionaries ofgvar.GVars, or lists ofgvar.GVars and/or arrays/dictionaries ofgvar.GVars.fmt_errorbudgettabulates the parts of the standard deviations of eachoutputs[ko]due to eachinputs[ki]. - ndecimal (
int) – Number of decimal places displayed in table. - percent (boolean) – Tabulate % errors if
percent is True; otherwise tabulate the errors themselves. - colwidth (positive integer or None) – Width of each column. This is set automatically, to
accommodate label widths, if
colwidth=None(default). - verify (boolean) – If
True, a warning is issued if: 1) different inputs are correlated (and therefore double count errors); or 2) the sum (in quadrature) of partial errors is not equal to the total error to within 0.1% of the error (and the error budget is incomplete or overcomplete). No checking is done ifverify==False(default).
Returns: A table (
str) containing the error budget. Output variables are labeled by the keys inoutputs(columns); sources of uncertainty are labeled by the keys ininputs(rows).- outputs – Dictionary of
-
fmt_values(outputs, ndecimal=None)¶ Tabulate
gvar.GVars inoutputs.Parameters: - outputs – A dictionary of
gvar.GVarobjects. - ndecimal (
intorNone) – Format valuesvusingv.fmt(ndecimal).
Returns: A table (
str) containing values and standard deviations for variables inoutputs, labeled by the keys inoutputs.- outputs – A dictionary of
-
simulated_fit_iter(n=None, pexact=None, **kargs)¶ Iterator that returns simulation copies of a fit.
Fit reliability can be tested using simulated data which replaces the mean values in
self.ywith random numbers drawn from a distribution whose mean equalsself.fcn(pexact)and whose covariance matrix is the same asself.y‘s. Simulated data is very similar to the original fit data,self.y, but corresponds to a world where the correct values for the parameters (i.e., averaged over many simulated data sets) are given bypexact.pexactis usually taken equal tofit.pmean.Each iteration of the iterator creates new simulated data, with different random numbers, and fits it, returning the the
lsqfit.nonlinear_fitthat results. The simulated data has the same covariance matrix asfit.y. Typical usage is:... fit = nonlinear_fit(...) ... for sfit in fit.simulated_fit_iter(n=3): ... verify that sfit.p agrees with pexact=fit.pmean within errors ...
Only a few iterations are needed to get a sense of the fit’s reliability since we know the correct answer in each case. The simulated fit’s output results should agree with
pexact(=fit.pmeanhere) within the simulated fit’s errors.Simulated fits can also be used to estimate biases in the fit’s output parameters or functions of them, should non-Gaussian behavior arise. This is possible, again, because we know the correct value for every parameter before we do the fit. Again only a few iterations may be needed for reliable estimates.
The (possibly non-Gaussian) probability distributions for parameters, or functions of them, can be explored in more detail by setting option
bootstrap=Trueand collecting results from a large number of simulated fits. Withbootstrap=True, the means of the priors are also varied from fit to fit, as in a bootstrap simulation; the new prior means are chosen at random from the prior distribution. Variations in the best-fit parameters (or functions of them) from fit to fit define the probability distributions for those quantities. For example, one would use the following code to analyze the distribution of functiong(p)of the fit parameters:fit = nonlinear_fit(...) ... glist = [] for sfit in fit.simulated_fit_iter(n=100, bootstrap=True): glist.append(g(sfit.pmean)) ... analyze samples glist[i] from g(p) distribution ...
This code generates
n=100samplesglist[i]from the probability distribution ofg(p). If everything is Gaussian, the mean and standard deviation ofglist[i]should agree withg(fit.p).meanandg(fit.p).sdev.The only difference between simulated fits with
bootstrap=Trueandbootstrap=False(the default) is that the prior means are varied. It is essential that they be varied in a bootstrap analysis since one wants to capture the impact of the priors on the final distributions, but it is not necessary and probably not desirable when simply testing a fit’s reliability.Parameters: - n (integer or
None) – Maximum number of iterations (equals infinity ifNone). - pexact (
Noneor array or dictionary of numbers) – Fit-parameter values for the underlying distribution used to generate simulated data; replaced byself.pmeanif isNone(default). - bootstrap (bool) – Vary prior means if
True; otherwise vary only the means inself.y(default).
Returns: An iterator that returns
lsqfit.nonlinear_fits for different simulated data.Note that additional keywords can be added to overwrite keyword arguments in
lsqfit.nonlinear_fit.- n (integer or
-
bootstrap_iter(n=None, datalist=None)¶ Iterator that returns bootstrap copies of a fit.
A bootstrap analysis involves three steps: 1) make a large number of “bootstrap copies” of the original input data and prior that differ from each other by random amounts characteristic of the underlying randomness in the original data; 2) repeat the entire fit analysis for each bootstrap copy of the data, extracting fit results from each; and 3) use the variation of the fit results from bootstrap copy to bootstrap copy to determine an approximate probability distribution (possibly non-gaussian) for the fit parameters and/or functions of them: the results from each bootstrap fit are samples from that distribution.
Bootstrap copies of the data for step 2 are provided in
datalist. IfdatalistisNone, they are generated instead from the means and covariance matrix of the fit data (assuming gaussian statistics). The maximum number of bootstrap copies considered is specified byn(Noneimplies no limit).Variations in the best-fit parameters (or functions of them) from bootstrap fit to bootstrap fit define the probability distributions for those quantities. For example, one could use the following code to analyze the distribution of function
g(p)of the fit parameters:fit = nonlinear_fit(...) ... glist = [] for sfit in fit.bootstrapped_fit_iter(n=100, datalist=datalist, bootstrap=True): glist.append(g(sfit.pmean)) ... analyze samples glist[i] from g(p) distribution ...
This code generates
n=100samplesglist[i]from the probability distribution ofg(p). If everything is Gaussian, the mean and standard deviation ofglist[i]should agree withg(fit.p).meanandg(fit.p).sdev.Parameters: - n (integer) – Maximum number of iterations if
nis notNone; otherwise there is no maximum. - datalist (sequence or iterator or
None) – Collection of bootstrapdatasets for fitter.
Returns: Iterator that returns an
lsqfit.nonlinear_fitobject containing results from the fit to the next data set indatalist- n (integer) – Maximum number of iterations if
-
dump_p(filename)¶ Dump parameter values (
fit.p) into filefilename.fit.dump_p(filename)saves the best-fit parameter values (fit.p) from anonlinear_fitcalledfit. These values are recovered usingp = nonlinear_fit.load_parameters(filename)wherep‘s layout is the same as that offit.p.
-
dump_pmean(filename)¶ Dump parameter means (
fit.pmean) into filefilename.fit.dump_pmean(filename)saves the means of the best-fit parameter values (fit.pmean) from anonlinear_fitcalledfit. These values are recovered usingp0 = nonlinear_fit.load_parameters(filename)wherep0‘s layout is the same asfit.pmean. The saved values can be used to initialize a later fit (nonlinear_fitparameterp0).
-
static
load_parameters(filename)¶ Load parameters stored in file
filename.p = nonlinear_fit.load_p(filename)is used to recover the values of fit parameters dumped usingfit.dump_p(filename)(orfit.dump_pmean(filename)) wherefitis of typelsqfit.nonlinear_fit. The layout of the returned parameterspis the same as that offit.p(orfit.pmean).
-
check_roundoff(rtol=0.25, atol=1e-6)¶ Check for roundoff errors in fit.p.
Compares standard deviations from fit.p and fit.palt to see if they agree to within relative tolerance
rtoland absolute toleranceatol. Generates a warning if they do not (in which case an svd cut might be advisable).
- data –
Functions¶
-
lsqfit.empbayes_fit(z0, fitargs, **minargs)¶ Call
lsqfit.nonlinear_fit(**fitargs(z))varyingz, starting atz0, to maximizelogGBF(empirical Bayes procedure).The fit is redone for each value of
zthat is tried, in order to determinelogGBF.Parameters: - z0 (array) – Starting point for search.
- fitargs (function) – Function of array
zthat determines which fit parameters to use. The function returns these as an argument dictionary forlsqfit.nonlinear_fit(). - minargs (dictionary) – Optional argument dictionary, passed on to
lsqfit.multiminex, which finds the minimum.
Returns: A tuple containing the best fit (object of type
lsqfit.nonlinear_fit) and the optimal value for parameterz.
-
lsqfit.wavg(dataseq, prior=None, fast=False, **kargs)¶ Weighted average of
gvar.GVars or arrays/dicts ofgvar.GVars.The weighted average of several
gvar.GVars is what one obtains from a least-squares fit of the collection ofgvar.GVars to the one-parameter fit functiondef f(p): return N * [p[0]]
where
Nis the number ofgvar.GVars. The average is the best-fit value forp[0].gvar.GVars with smaller standard deviations carry more weight than those with larger standard deviations. The averages computed bywavgtake account of correlations between thegvar.GVars.If
prioris notNone, it is added to the list of data used in the average. Thuswavg([x2, x3], prior=x1)is the same aswavg([x1, x2, x3]).Typical usage is
x1 = gvar.gvar(...) x2 = gvar.gvar(...) x3 = gvar.gvar(...) xavg = wavg([x1, x2, x3]) # weighted average of x1, x2 and x3
where the result
xavgis agvar.GVarcontaining the weighted average.The individual
gvar.GVars in the last example can be replaced by multidimensional distributions, represented by arrays ofgvar.GVars or dictionaries ofgvar.GVars (or arrays ofgvar.GVars). For example,x1 = [gvar.gvar(...), gvar.gvar(...)] x2 = [gvar.gvar(...), gvar.gvar(...)] x3 = [gvar.gvar(...), gvar.gvar(...)] xavg = wavg([x1, x2, x3]) # xavg[i] is wgtd avg of x1[i], x2[i], x3[i]
where each array
x1,x2... must have the same shape. The resultxavgin this case is an array ofgvar.GVars, where the shape of the array is the same as that ofx1, etc.Another example is
x1 = dict(a=[gvar.gvar(...), gvar.gvar(...)], b=gvar.gvar(...)) x2 = dict(a=[gvar.gvar(...), gvar.gvar(...)], b=gvar.gvar(...)) x3 = dict(a=[gvar.gvar(...), gvar.gvar(...)]) xavg = wavg([x1, x2, x3]) # xavg['a'][i] is wgtd avg of x1['a'][i], x2['a'][i], x3['a'][i] # xavg['b'] is gtd avg of x1['b'], x2['b']
where different dictionaries can have (some) different keys. Here the result
xavgis agvar.BufferDict`having the same keys asx1, etc.Weighted averages can become costly when the number of random samples being averaged is large (100s or more). In such cases it might be useful to set parameter
fast=True. This causeswavgto estimate the weighted average by incorporating the random samples one at a time into a running average:result = prior for dataseq_i in dataseq: result = wavg([result, dataseq_i], ...)
This method is much faster when
len(dataseq)is large, and gives the exact result when there are no correlations between different elements of listdataseq. The results are approximately correct whendataseq[i]anddataseq[j]are correlated fori!=j.Parameters: - dataseq – The
gvar.GVars to be averaged.dataseqis a one-dimensional sequence ofgvar.GVars, or of arrays ofgvar.GVars, or of dictionaries containinggvar.GVars or arrays ofgvar.GVars. Alldataseq[i]must have the same shape. - prior (
gvar.GVaror array/dictionary ofgvar.GVars) – Prior values for the averages, to be included in the weighted average. Default value isNone, in which caseprioris ignored. - fast (bool) – Setting
fast=Truecauseswavgto compute an approximation to the weighted average that is much faster to calculate when averaging a large number of samples (100s or more). The default isfast=False. - kargs (dict) – Additional arguments (e.g.,
svdcut) to the fitter used to do the averaging.
The following function attributes are also set:
-
wavg.chi2¶ chi**2for weighted average.
-
wavg.dof¶ Effective number of degrees of freedom.
-
wavg.Q¶ The probability that the
chi**2could have been larger, by chance, assuming that the data are all Gaussain and consistent with each other. Values smaller than 0.1 or suggest that the data are not Gaussian or are inconsistent with each other. Also called the p-value.Quality factor Q (or p-value) for fit.
-
wavg.time¶ Time required to do average.
-
wavg.svdcorrection¶ The svd corrections made to the data when
svdcutis notNone.
-
wavg.fit¶ Fit output from average.
These same attributes are also attached to the output
gvar.GVar, array or dictionary fromgvar.wavg().- dataseq – The
-
lsqfit.gammaQ()¶ Return the normalized incomplete gamma function
Q(a,x) = 1-P(a,x).Q(a, x) = 1/Gamma(a) * \int_x^\infty dt exp(-t) t ** (a-1) = 1 - P(a, x)Note that
gammaQ(ndof/2., chi2/2.)is the probabilty that one could get achi**2larger thanchi2withndofdegrees of freedom even if the model used to constructchi2is correct.
Other Classes¶
-
class
lsqfit.transform_p(priorkeys, has_x=False)¶ Decorate fit function to allow log/sqrt-normal priors.
This decorator can be applied to fit functions whose parameters are stored in a dictionary-like object. It searches the parameter keys for string-valued keys of the form
"log(XX)","logXX","sqrt(XX)", or"sqrtXX"where"XX"is an arbitrary string. For each such key it adds a new entry to the parameter dictionary with key"XX"where:p["XX"] = exp(p[k]) for k = "log(XX)" or "logXX"
or
p["XX"] = p[k] ** 2 for k = "sqrt(XX)" or "sqrtXX"
This means that the fit function can be expressed entirely in terms of
p["XX"]even if the actual fit parameter is the logarithm or square root of that quantity. Since fit parameters have gaussian/normal priors,p["XX"]has a log-normal or “sqrt-normal” distribution in the first or second cases above, respectively. In either casep["XX"]is guaranteed to be postiive.This is a convenience function. It allows for the rapid replacement of a fit parameter by its logarithm or square root without having to rewrite the fit function — only the prior need be changed. The decorator needs to be told if the fit function has an
xas its first argument, followed by the parametersp:@lsqfit.transform_p(prior.keys(), has_x=True) def fitfcn(x, p): ...
versus
@lsqfit.transform_p(prior.keys()) def fitfcn(p): ...
A list of the specific keys that need transforming can be used instead of the list of all keys (
prior.keys()). The decorator assigns a copy of itself to the function as an attribute:fitfcn.transform_p.Parameters: - priorkeys (sequence) – The keys in the prior that are to be tranformed.
Other keys can be in
priorkeysprovided they do not begin with'log'or'sqrt'— they are ignored. - has_x – Set equal to
Trueif the fit function is a function ofxand parametersp(i.e.,f(x,p)). Set equal toFalseif the fit function is a function only of the parameters (i.e.,f(p)). Default isFalse. - pkey (string or None) – Name of the parameters-variable in the argument keyword
dictionary of the fit function. Default value is
None; one ofpkeyorpindexmust be specified (i.e.,not None), unless the fit function has only a single argument.
-
transform(p)¶ Create transformed copy of dictionary
p.Create a copy of parameter-dictionary
pthat includes new entries for each"logXX", etc entry corresponding to"XX". The values inpcan be any type that supports logarithms, exponentials, and arithmetic.
-
untransform(p)¶ Undo
self.transform(p).Reconstruct
p0wherep == self.transform(p0); that is remove entries for keys"XX"that were added by bytransform_p.transform()(because"logXX"or"sqrtXX"or ... appeared inp0).
-
static
paramkey(k)¶ Return parameter key corresponding to prior-key
k.Strip off any
"log"or"sqrt"prefix.
-
static
priorkey(prior, k)¶ Return key in
priorcorresponding tok.Add in
"log"or"sqrt"as needed to find a key inprior.
- priorkeys (sequence) – The keys in the prior that are to be tranformed.
Other keys can be in
-
class
lsqfit.multifit(x0, n, f, reltol=1e-4, abstol=0, maxit=1000, alg='lmsder', analyzer=None)¶ Fitter for nonlinear least-squares multidimensional fits.
Parameters: - x0 (
numpyarray of floats) – Starting point for minimization. - n (positive integer) – Length of vector returned by the fit function
f(x). - f (function) – Fit function:
multifitminimizessum_i f_i(x)**2by varying parametersx. The parameters are a 1-dnumpyarray of either numbers orgvar.GVars. - reltol (float) – The fit stops when
|dx_i| < abstol + reltol * |x_i|; default value is1e-4. - abstol (float) – The fit stops when
|dx_i| < abstol + reltol * |x_i|; default value is0.0. - maxit (integer) – Maximum number of iterations in search for minimum; default is 1000.
- alg (string) – GSL algorithm to use for minimization. Two options are
currently available:
"lmsder", the scaled LMDER algorithm (default); and"lmder", the unscaled LMDER algorithm. - analyzer (function) – Optional function of
x, [...f_i(x)...], [[..df_ij(x)..]]which is called after each iteration. This can be used to inspect intermediate steps in the minimization, if needed.
multifitis a function-class whose constructor does a least squares fit by minimizingsum_i f_i(x)**2as a function of vectorx. The following attributes are available:-
x¶ Location of the most recently computed (best) fit point.
-
cov¶ Covariance matrix at the minimum point.
-
f¶ The fit function
f(x)at the minimum in the most recent fit.
-
J¶ Gradient
J_ij = df_i/dx[j]for most recent fit.
-
nit¶ Number of iterations used in last fit to find the minimum.
-
error¶ Noneif fit successful; an error message otherwise.
multifitis a wrapper for themultifitGSL routine.- x0 (
-
class
lsqfit.multiminex(x0, f, tol=1e-4, maxit=1000, step=1, alg='nmsimplex2', analyzer=None)¶ Minimizer for multidimensional functions.
Parameters: - x0 (
numpyarray of floats) – Starting point for minimization search. - f (function) – Function
f(x)to be minimized by varying vectorx. - tol (float) – Minimization stops when
xhas converged to with tolerancetol; default is1e-4. - maxit (integer) – Maximum number of iterations in search for minimum; default is 1000.
- step (number) – Initial step size to use in varying components of
x; default is 1. - alg (string) – GSL algorithm to use for minimization. Three options are
currently available:
"nmsimplex", Nelder Mead Simplex algorithm;"nmsimplex2", an improved version of"nmsimplex"(default); and"nmsimplex2rand", a version of"nmsimplex2"with random shifts in the start position. - analyzer (function) – Optional function of
x, f(x), it, whereitis the iteration number, which is called after each iteration. This can be used to inspect intermediate steps in the minimization, if needed.
multiminexis a function-class whose constructor minimizes a multidimensional functionf(x)by varying vectorx. This routine does not use user-supplied information about the gradient off(x). The following attributes are available:-
x¶ Location of the most recently computed minimum (1-d array).
-
f¶ Value of function
f(x)at the most recently computed minimum.
-
nit¶ Number of iterations required to find most recent minimum.
-
error¶ Noneif fit successful; an error message otherwise.
multiminexis a wrapper for themultiminGSL routine.- x0 (