Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def linear_chisq(params, x, data, errs=None):
''' Calcs chi-squared residuals linear model (weighted by errors if given)
'''
if type(params) is not lmfit.parameter.Parameters:
msg = "Params argument is not a lmfit parameter set"
raise TypeError(msg)
if "m" not in params.keys():
msg = "No slope parameter (m) defined in the model"
raise KeyError(msg)
if "c" not in params.keys():
msg = "No intercept parameter (c) defined in the model"
raise KeyError(msg)
model = params["m"]*x + params["c"]
residuals = (data-model)
if errs is not None:
residuals = residuals/errs
def prepare_fit(self, params=None):
"""
Prepares parameters for fitting,
return array of initial values
"""
# determine which parameters are actually variables
# and which are defined expressions.
self.result = MinimizerResult()
result = self.result
if params is not None:
self.params = params
if isinstance(self.params, Parameters):
result.params = deepcopy(self.params)
elif isinstance(self.params, (list, tuple)):
result.params = Parameters()
for par in self.params:
if not isinstance(par, Parameter):
raise MinimizerException(self.err_nonparam)
else:
result.params[par.name] = par
elif self.params is None:
raise MinimizerException(self.err_nonparam)
# determine which parameters are actually variables
# and which are defined expressions.
result.var_names = [] # note that this *does* belong to self...
result.init_vals = []
result.params.update_constraints()
result.nfev = 0
result.errorbars = False
user_fits = OrderedDict()
for dim, dfits in fits.items():
if dim not in ('1d', '2d', '3d'):
continue
user_fits[dim] = OrderedDict()
for name, fit in dfits.items():
try:
fname = fit['fit_function']
new_fit = {}
new_fit['fit_name'] = fname
new_fit['est_name'] = fit['estimator']
new_fit['make_fit'] = self.fit_list[dim][fname]['make_fit']
new_fit['make_model'] = self.fit_list[dim][fname]['make_model']
new_fit['estimator'] = self.fit_list[dim][fname][fit['estimator']]
try:
par = lmfit.parameter.Parameters()
par.loads(fit['parameters'])
except:
model, par = self.fit_list[dim][fname]['make_model']()
new_fit['parameters'] = par
user_fits[dim][name] = new_fit
except KeyError:
self.log.exception('Failed to validate fit {0}'.format(name))
continue
return user_fits
parms : lmfit.parameter.Parameters or ndarray
The input parameters.
parmid : str
The identifier for parameters. By default this is
"parm", i.e. parameters are named like this:
"parm0001", "parm0002", etc.
attribute : str
The attribute to return, e.g.
- "value" : return the current value of the parameter
- "vary" : return if the parameter is varied during fitting
Returns:
parr : ndarray
If the input is an ndarray, the input will be returned.
"""
if isinstance(parms, lmfit.parameter.Parameters):
items = parms.items()
parr = []
for p in sorted(items, key=lambda x: x[0]):
if p[0].startswith(parmid):
parr.append(getattr(p[1], attribute))
else:
parr = parms
return np.array(parr)
def clear_result(self):
""" Reset fit result and fit parameters from result for this container.
"""
self.current_fit_param = lmfit.parameter.Parameters()
self.current_fit_result = None
def __add__(self, other):
"""Add Parameters objects."""
if not isinstance(other, Parameters):
raise ValueError("'%s' is not a Parameters object" % other)
out = deepcopy(self)
out.add_many(*other.values())
for sym in other._asteval.user_defined_symbols():
if sym not in out._asteval.symtable:
out._asteval.symtable[sym] = other._asteval.symtable[sym]
return out
def residuals(self, parameters=None, tmin=None, tmax=None, solvemethod='lmfit',
noise=False):
"""
Method that is called by the solve function to calculate the residuals.
"""
if tmin is None:
tmin = self.oseries.index.min()
if tmax is None:
tmax = self.oseries.index.max()
tindex = self.oseries[tmin: tmax].index # times used for calibration
if isinstance(parameters, np.ndarray):
p = parameters
elif isinstance(parameters, lmfit.parameter.Parameters): # probably needs to be a function call
p = np.array([p.value for p in parameters.values()])
elif parameters is None:
p = self.parameters
# h_observed - h_simulated
r = self.oseries[tindex] - self.simulate(p, tmin, tmax)[tindex]
if noise and (self.noisemodel is not None):
r = self.noisemodel.simulate(r, self.odelt[tindex], tindex,
p[-self.noisemodel.nparam])
if np.isnan(sum(r ** 2)):
print 'nan problem in residuals' # quick and dirty check
return r
self.name = name
if dimension == '1d':
self.dim = 1
elif dimension == '2d':
self.dim = 2
elif dimension == '3d':
self.dim = 3
else:
raise Exception('Invalid dimension {0}'.format(dimension))
self.dimension = dimension
self.fit_list = OrderedDict()
# variables for fitting
self.fit_granularity_fact = 10
self.current_fit = 'No Fit'
self.current_fit_param = lmfit.parameter.Parameters()
self.current_fit_result = None
self.units = ['independent variable {0}'.format(i+1) for i in range(self.dim)]
self.units.append('dependent variable')
Smallest correlation in absolute value to show (default is 0.1).
sort_pars : bool or callable, optional
Whether to show parameter names sorted in alphanumerical order. If
False (default), then the parameters will be listed in the order they
were added to the Parameters dictionary. If callable, then this (one
argument) function is used to extract a comparison key from each
list element.
Returns
-------
string
Multi-line text of fit report.
"""
from .parameter import Parameters
if isinstance(inpars, Parameters):
result, params = None, inpars
if hasattr(inpars, 'params'):
result = inpars
params = inpars.params
if sort_pars:
if callable(sort_pars):
key = sort_pars
else:
key = alphanumeric_sort
parnames = sorted(params, key=key)
else:
# dict.keys() returns a KeysView in py3, and they're indexed
# further down
parnames = list(params.keys())