本文整理汇总了Python中lmfit.minimize方法的典型用法代码示例。如果您正苦于以下问题:Python lmfit.minimize方法的具体用法?Python lmfit.minimize怎么用?Python lmfit.minimize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lmfit
的用法示例。
在下文中一共展示了lmfit.minimize方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import lmfit [as 别名]
# 或者: from lmfit import minimize [as 别名]
def __init__(self, model: Type[CompartmentalModel], parameters: tuple = None, data: np.array = None,
initial_conditions: list = None, fit_method: str = 'leastsq', error: callable = None,
fit_period: float = None):
"""
A class to standardize fitting and solving epidemiological models.
:param model: the model to use, currently a class in the form of SIR, SEIR above
:param parameters: tuple, parameters to use for the model, defaults to the output of [model].get_parameters
:param data: np.array, data that can be used to calibrate the model
:param initial_conditions: list, initial conditions for the model
:param fit_method: str, the method to use to minimize the (given) error. Available methods are those in the
lmfit.minimizer.minimize function. Default is Levenberg-Marquardt least squares minimization.
:param error: callable, control which residuals (and in what form) to minimize for fitting.
:param fit_period: float, how far back to fit the data, defaults to fitting all data
"""
self.model = model
self.parameters = parameters
self.data = data
self.initial_conditions = initial_conditions
self.fit_method = fit_method
self.error = error
self.fit_period = fit_period
self.result = None
self.fitted_parameters = None
示例2: residual
# 需要导入模块: import lmfit [as 别名]
# 或者: from lmfit import minimize [as 别名]
def residual(self, parameters: Parameters, time_range: np.arange, data: np.ndarray) -> np.ndarray:
"""
Obtain fit error (to minimize).
:param parameters: parameters to use (which we are usually minimizing the residual for)
:param time_range: time range for solution (over which we obtain the residual)
:param data: data to fit the models too (i.e. compute residuals in terms of)
:return:
"""
initial_conditions = []
for variable in self.initial_conditions:
initial_conditions.append(parameters[variable].value)
# obtain solution given current initial conditions and parameters
solution = self.solve(time_range, initial_conditions, parameters)
# compute residual, using custom error function if it has been passed in
residual = solution - data if self.error is None else self.error(solution, data, parameters)
if self.fit_period is not None:
residual = residual[-self.fit_period:]
return residual.ravel()
示例3: fit
# 需要导入模块: import lmfit [as 别名]
# 或者: from lmfit import minimize [as 别名]
def fit(self, time_range: np.arange = None, parameters: [Parameters, tuple] = None, initial_conditions: list = None,
residual=None, verbose: bool = False, data: np.array = None, fit_period: float = None):
"""
Fit the model based on data in the form np.array([X1,...,Xn])
"""
if data is None:
if self.data is None:
raise ValueError("No data to fit the model on!")
data = self.data
if initial_conditions is not None:
self.initial_conditions = initial_conditions
if self.initial_conditions is None:
raise ValueError("No initial conditions to fit the model with!")
if parameters is None:
if self.parameters is None:
raise ValueError("No parameters to fit the model with!")
parameters = self.parameters
if time_range is None:
time_range = np.arange(data.shape[0])
if fit_period is not None:
self.fit_period = fit_period
if residual is None:
residual = self.residual
result = minimize(residual, parameters, args=(time_range, data), method=self.fit_method)
self.result = result
self.fitted_parameters = result.params.valuesdict()
if verbose:
report_fit(result)
return result
示例4: fit
# 需要导入模块: import lmfit [as 别名]
# 或者: from lmfit import minimize [as 别名]
def fit(self, ems_data, on_engine, drive_battery_state_of_charges,
after_treatment_warm_up_phases):
import lmfit
k = np.where(~on_engine, *self.reference(ems_data)['k_reference'].T)
# Filter data.
b = ~after_treatment_warm_up_phases & ~ems_data['force_on_engine']
b &= np.isfinite(k)
s = np.where(on_engine[b], 1, -1)
soc = drive_battery_state_of_charges[b]
def _(x):
x = x.valuesdict()
time = x['starter_time']
return np.float32(np.maximum(0, s * (self._k(x, soc) - np.where(
~on_engine, *self.reference(ems_data, time)['k_reference'].T
)[b].T)).sum())
p = lmfit.Parameters()
starter_time = self.starter_model.time
p.add('starter_time', 1, min=starter_time, max=starter_time * 10)
p.add('k0', 0, min=0)
p.add('soc0', 0, min=0, max=100)
p.add('alpha', 0, min=0)
p.add('beta', 0, min=0)
with co2_utl.numpy_random_seed(0):
# noinspection PyUnresolvedReferences
self.params = lmfit.minimize(_, p, 'ampgo').params.valuesdict()
return self
示例5: fit_pixel_nonlinear_per_line
# 需要导入模块: import lmfit [as 别名]
# 或者: from lmfit import minimize [as 别名]
def fit_pixel_nonlinear_per_line(row_num, data, x0,
param, reg_mat,
use_snip): # c_weight, fit_num, ftol):
# c_weight = 1
# fit_num = 100
# ftol = 1e-3
elist = param['non_fitting_values']['element_list'].split(', ')
elist = [e.strip(' ') for e in elist]
# LinearModel = lmfit.Model(simple_spectrum_fun_for_nonlinear)
# for i in np.arange(reg_mat.shape[0]):
# LinearModel.set_param_hint('a'+str(i), value=0.1, min=0, vary=True)
logger.info('Row number at {}'.format(row_num))
out = []
snip_bg = 0
for i in range(data.shape[0]):
if use_snip is True:
bg = snip_method_numba(data[i, :],
param['e_offset']['value'],
param['e_linear']['value'],
param['e_quadratic']['value'],
width=param['non_fitting_values']['background_width'])
y0 = data[i, :] - bg
snip_bg = np.sum(bg)
else:
y0 = data[i, :]
fit_params = lmfit.Parameters()
for i in range(reg_mat.shape[1]):
fit_params.add('a'+str(i), value=1.0, min=0, vary=True)
result = lmfit.minimize(residual_nonlinear_fit,
fit_params, args=(x0,),
kws={'data': y0, 'reg_mat': reg_mat})
# result = MS.model_fit(x0, y0,
# weights=1/np.sqrt(c_weight+y0),
# maxfev=fit_num,
# xtol=ftol, ftol=ftol, gtol=ftol)
# namelist = list(result.keys())
temp = {}
temp['value'] = [result.params[v].value for v in list(result.params.keys())]
temp['err'] = [result.params[v].stderr for v in list(result.params.keys())]
temp['snip_bg'] = snip_bg
out.append(temp)
return out