本文整理匯總了Python中lmfit.Model方法的典型用法代碼示例。如果您正苦於以下問題:Python lmfit.Model方法的具體用法?Python lmfit.Model怎麽用?Python lmfit.Model使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類lmfit
的用法示例。
在下文中一共展示了lmfit.Model方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: nena
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def nena(locs, info, callback=None):
bin_centers, dnfl_ = next_frame_neighbor_distance_histogram(locs, callback)
def func(d, a, s, ac, dc, sc):
f = a * (d / s ** 2) * _np.exp(-0.5 * d ** 2 / s ** 2)
fc = (
ac
* (d / sc ** 2)
* _np.exp(-0.5 * (d ** 2 + dc ** 2) / sc ** 2)
* _iv(0, d * dc / sc)
)
return f + fc
pdf_model = _lmfit.Model(func)
params = _lmfit.Parameters()
area = _np.trapz(dnfl_, bin_centers)
median_lp = _np.mean([_np.median(locs.lpx), _np.median(locs.lpy)])
params.add("a", value=area / 2, min=0)
params.add("s", value=median_lp, min=0)
params.add("ac", value=area / 2, min=0)
params.add("dc", value=2 * median_lp, min=0)
params.add("sc", value=median_lp, min=0)
result = pdf_model.fit(dnfl_, params, d=bin_centers)
return result, result.best_values["s"]
示例2: fit_base_param_decay
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def fit_base_param_decay(x: np.ndarray, y: np.ndarray, weights: np.ndarray = None,
param_guesses: tuple = (1., .9, 0.)) -> ModelResult:
"""
Fit experimental data x, y to an exponential decay parameterized by a base decay parameter.
:param x: The independent variable, e.g. depth or time
:param y: The dependent variable, e.g. survival probability
:param weights: Optional weightings of each point to use when fitting.
:param param_guesses: initial guesses for the parameters
:return: a lmfit Model
"""
_check_data(x, y, weights)
decay_model = Model(base_param_decay)
params = decay_model.make_params(amplitude=param_guesses[0], decay=param_guesses[1],
baseline=param_guesses[2])
return decay_model.fit(y, x=x, params=params, weights=weights)
示例3: fit_decay_time_param_decay
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def fit_decay_time_param_decay(x: np.ndarray, y: np.ndarray, weights: np.ndarray = None,
param_guesses: tuple = (1., 10, 0)) -> ModelResult:
"""
Fit experimental data x, y to an exponential decay parameterized by a decay time, or inverse
decay rate.
:param x: The independent variable, e.g. depth or time
:param y: The dependent variable, e.g. survival probability
:param weights: Optional weightings of each point to use when fitting.
:param param_guesses: initial guesses for the parameters
:return: a lmfit Model
"""
_check_data(x, y, weights)
decay_model = Model(decay_time_param_decay)
params = decay_model.make_params(amplitude=param_guesses[0], decay_time=param_guesses[1],
offset=param_guesses[2])
return decay_model.fit(y, x=x, params=params, weights=weights)
示例4: fit_decaying_cosine
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def fit_decaying_cosine(x: np.ndarray, y: np.ndarray, weights: np.ndarray = None,
param_guesses: tuple = (.5, 10, 0.0, 0.5, 5)) -> ModelResult:
"""
Fit experimental data x, y to an exponentially decaying cosine.
:param x: The independent variable, e.g. depth or time
:param y: The dependent variable, e.g. probability of measuring 1
:param weights: Optional weightings of each point to use when fitting.
:param param_guesses: initial guesses for the parameters
:return: a lmfit Model
"""
_check_data(x, y, weights)
decay_model = Model(decaying_cosine)
params = decay_model.make_params(amplitude=param_guesses[0], decay_time=param_guesses[1],
offset=param_guesses[2], baseline=param_guesses[3],
frequency=param_guesses[4])
return decay_model.fit(y, x=x, params=params, weights=weights)
示例5: fit_shifted_cosine
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def fit_shifted_cosine(x: np.ndarray, y: np.ndarray, weights: np.ndarray = None,
param_guesses: tuple = (.5, 0, .5, 1.)) -> ModelResult:
"""
Fit experimental data x, y to a cosine shifted vertically by amount baseline.
:param x: The independent variable, e.g. depth or time
:param y: The dependent variable, e.g. probability of measuring 1
:param weights: Optional weightings of each point to use when fitting.
:param param_guesses: initial guesses for the parameters
:return: a lmfit Model
"""
_check_data(x, y, weights)
decay_model = Model(shifted_cosine)
params = decay_model.make_params(amplitude=param_guesses[0], offset=param_guesses[1],
baseline=param_guesses[2],
frequency=param_guesses[3])
return decay_model.fit(y, x=x, params=params, weights=weights)
示例6: bridge_function2
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def bridge_function2(x, center1, center2, sigma1, sigma2, amplitude):
"""A "bridge" function, geometric complementary of two gaussian peaks.
Let `g` be a Gaussian function (with amplitude = 1), the bridge function
is defined as:
amplitude * (1 - g(x, center1, sigma1)) * (1 - g(x, center2, sigma2))
for center1 < x < center2. The function is 0 otherwise.
Arguments:
x (array): 1-D array for the independent variable
center1 (float): center of the first gaussian (left side)
center2 (float): center of the second gaussian (right side)
sigma1 (float): sigma of the left-side gaussian
sigma2 (float): sigma of the right-side gaussian
amplitude (float): maximum (asymptotic) value of the bridge (plateau)
Return:
An array (same shape as `x`) with the function values.
"""
assert center1 <= center2
assert amplitude >= 0
mask = (x > center1)*(x < center2)
y = np.zeros_like(x)
y[mask] = amplitude
y[mask] *= 1 - gaussian(x[mask], center1, sigma1)
y[mask] *= 1 - gaussian(x[mask], center2, sigma2)
y *= amplitude
return y
##
# Factory functions that return initialized `lmfit.Model` objects
#
示例7: factory_gaussian
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def factory_gaussian(center=0.1, sigma=0.1, amplitude=1):
"""Return an lmfit Gaussian model that can be used to fit data.
Arguments are initial values for the model parameters.
Returns
An `lmfit.Model` object with all the parameters already initialized.
"""
model = lmfit.models.GaussianModel()
model.set_param_hint('center', value=center, min=-1, max=2)
model.set_param_hint('sigma', value=sigma)
model.set_param_hint('amplitude', value=amplitude)
return model
示例8: factory_asym_gaussian
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def factory_asym_gaussian(center=0.1, sigma1=0.1, sigma2=0.1, amplitude=1):
"""Return a lmfit Asymmetric Gaussian model that can be used to fit data.
For the definition of asymmetric Gaussian see :func:`asym_gaussian`.
Arguments are initial values for the model parameters.
Returns
An `lmfit.Model` object with all the parameters already initialized.
"""
model = lmfit.model.Model(asym_gaussian)
model.set_param_hint('center', value=center, min=-1, max=2)
model.set_param_hint('sigma1', value=sigma1)
model.set_param_hint('sigma2', value=sigma2)
model.set_param_hint('amplitude', value=amplitude)
return model
示例9: factory_three_gaussians
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def factory_three_gaussians(p1_center=0., p2_center=0.5, p3_center=1,
sigma=0.05):
"""Return a 3-Gaussian model that can fit data.
The other arguments are initial values for the `center` for each
Gaussian component plus an single `sigma` argument that is used
as initial sigma for all the Gaussians. Note that during the fitting
the sigma of each Gaussian is varied independently.
Returns
An `lmfit.Model` object with all the parameters already initialized.
"""
peak1 = lmfit.models.GaussianModel(prefix='p1_')
peak2 = lmfit.models.GaussianModel(prefix='p2_')
peak3 = lmfit.models.GaussianModel(prefix='p3_')
model = peak1 + peak2 + peak3
model.set_param_hint('p1_center', value=p1_center, min=0, max=1)
model.set_param_hint('p2_center', value=p2_center, min=0, max=1)
model.set_param_hint('p3_center', value=p3_center, min=0, max=1)
model.set_param_hint('p1_sigma', value=sigma, min=0.02, max=0.2)
model.set_param_hint('p2_sigma', value=sigma, min=0.02, max=0.2)
model.set_param_hint('p3_sigma', value=sigma, min=0.02, max=0.2)
model.set_param_hint('p1_amplitude', value=1, min=0.01)
model.set_param_hint('p2_amplitude', value=1, min=0.01)
model.set_param_hint('p3_amplitude', value=1, min=0.01)
model.name = '3-gaussians'
return model
## lmfit composite model used for fitting
示例10: fit_histogram
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def fit_histogram(self, model=None, pdf=True, **fit_kwargs):
"""Fit the histogram of each channel using the same lmfit model.
A list of `lmfit.Minimizer` is stored in `.fit_res`.
The fitted values for all the parameters and all the channels are
save in a Pandas DataFrame `.params`.
Arguments:
model (lmfit.Model object): lmfit Model with all the parameters
already initialized used for fitting.
pdf (bool): if True fit the normalized histogram (.hist_pdf)
otherwise fit the raw counts (.hist_counts).
fit_kwargs (dict): keyword arguments passed to `model().fit`.
"""
if model is not None:
self.model = model
if not self._hist_computed:
self.histogram()
data_list = self.hist_pdf if pdf else self.hist_counts
self.params = pd.DataFrame(index=range(self.ndata),
columns=sorted(self.model.param_names))
self.fit_res = []
#init_params = copy.deepcopy(self.model.params)
for i, data in enumerate(data_list):
self.fit_res.append(
self.model.fit(data, x=self.hist_axis, **fit_kwargs))
self.params.iloc[i] = pd.Series(self.fit_res[-1].values)
示例11: emp_jacobian
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def emp_jacobian(pars, x, y):
"""
An empirical calculation of the Jacobian
Will work for a model that contains multiple Gaussians, and for which
some components are not being fit (don't vary).
Parameters
----------
pars : lmfit.Model
The model parameters
x, y : list
Locations at which the jacobian is being evaluated
Returns
-------
j : 2d array
The Jacobian.
See Also
--------
:func:`AegeanTools.fitting.jacobian`
"""
eps = 1e-5
matrix = []
model = ntwodgaussian_lmfit(pars)(x, y)
for i in range(pars['components'].value):
prefix = "c{0}_".format(i)
for p in ['amp', 'xo', 'yo', 'sx', 'sy', 'theta']:
if pars[prefix + p].vary:
pars[prefix + p].value += eps
dmdp = ntwodgaussian_lmfit(pars)(x, y) - model
matrix.append(dmdp / eps)
pars[prefix + p].value -= eps
matrix = np.array(matrix)
return matrix
示例12: base_param_decay
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def base_param_decay(x: np.ndarray, amplitude: float, decay: float, baseline: float):
"""
Model an exponential decay parameterized by a base parameter raised to the power of the
independent variable x.
:param numpy.ndarray x: Independent variable
:param float baseline: Offset value
:param float amplitude: Amplitude of exponential decay
:param float decay: Decay parameter
:return: Exponential decay fit function
"""
return np.asarray(baseline + amplitude * decay ** x)
示例13: decay_time_param_decay
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def decay_time_param_decay(x: np.ndarray, amplitude: float, decay_time: float,
offset: float = 0.0) -> np.ndarray:
"""
Model an exponential decay parameterized by a decay constant with constant e as the base.
:param x: The independent variable with respect to which decay is calculated.
:param amplitude: The amplitude of the decay curve.
:param decay_time: The inverse decay rate - e.g. T1 - of the decay curve.
:param offset: The offset of the curve, (typically take to be 0.0).
:return: Exponential decay fit function, parameterized with a decay constant
"""
return np.asarray(amplitude * np.exp(-1 * (x - offset) / decay_time))
示例14: fit_pixel_nonlinear_per_line
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [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
示例15: factory_two_gaussians
# 需要導入模塊: import lmfit [as 別名]
# 或者: from lmfit import Model [as 別名]
def factory_two_gaussians(add_bridge=False, p1_center=0.1, p2_center=0.9,
p1_sigma=0.03, p2_sigma=0.03):
"""Return a 2-Gaussian + (optional) bridge model that can fit data.
The optional "bridge" component (i.e. a plateau between the two peaks)
is a function that is non-zero only between `p1_center` and `p2_center`
and is defined as::
br_amplitude * (1 - g(x, p1_center, p1_sigma) - g(x, p1_center, p2_sigma))
where `g` is a gaussian function with amplitude = 1 and `br_amplitude`
is the height of the plateau and the only additional parameter introduced
by the bridge. Note that both centers and sigmas parameters in the bridge
are the same ones of the adjacent Gaussian peaks. Therefore a
2-Gaussian + bridge model has 7 free parameters: 3 for each Gaussian and
an additional one for the bridge.
The bridge function is implemented in :func:`bridge_function`.
Arguments:
p1_center, p2_center (float): initial values for the centers of the
two Gaussian components.
p1_sigma, p2_sigma (float): initial values for the sigmas of the
two Gaussian components.
add_bridge (bool): if True adds a bridge function between the two
gaussian peaks. If False the model has only two Gaussians.
Returns
An `lmfit.Model` object with all the parameters already initialized.
"""
peak1 = lmfit.models.GaussianModel(prefix='p1_')
peak2 = lmfit.models.GaussianModel(prefix='p2_')
model = peak1 + peak2
model.set_param_hint('p1_center', value=p1_center, min=-1, max=2)
model.set_param_hint('p2_center', value=p2_center, min=-1, max=2)
model.set_param_hint('p1_sigma', value=p1_sigma, min=0.01, max=0.2)
model.set_param_hint('p2_sigma', value=p2_sigma, min=0.01, max=0.2)
model.set_param_hint('p1_amplitude', value=1, min=0.01)
model.set_param_hint('p2_amplitude', value=1, min=0.01)
name = '2-gaussians'
if add_bridge:
bridge = lmfit.model.Model(bridge_function, prefix='br_')
model += bridge
model.set_param_hint('br_amplitude', value=0.0001, min=0)
model.set_param_hint('br_center1', min=0, expr='p1_center')
model.set_param_hint('br_center2', min=0, expr='p2_center')
model.set_param_hint('br_sigma1', min=0, expr='p1_sigma')
model.set_param_hint('br_sigma2', min=0, expr='p2_sigma')
name += '-bridge'
model.name = name
return model