本文整理汇总了Python中lmfit.Model.set_param_hint方法的典型用法代码示例。如果您正苦于以下问题:Python Model.set_param_hint方法的具体用法?Python Model.set_param_hint怎么用?Python Model.set_param_hint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lmfit.Model
的用法示例。
在下文中一共展示了Model.set_param_hint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gauss_step_const
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def gauss_step_const(signal, guess):
"""
Fits high contrast data very well
"""
if guess == False:
return [0, 0]
else:
amp, centre, stdev, offset = guess
data = np.array([range(len(signal)), signal]).T
X = data[:,0]
Y = data[:,1]
# gauss_mod = Model(gaussian)
gauss_mod = Model(gaussian)
const_mod = ConstantModel()
step_mod = StepModel(prefix='step')
pars = gauss_mod.make_params(height=amp, center=centre, width=stdev / 3., offset=offset)
# pars = gauss_mod.make_params(amplitude=amp, center=centre, sigma=stdev / 3.)
gauss_mod.set_param_hint('sigma', value = stdev / 3., min=stdev / 2., max=stdev)
pars += step_mod.guess(Y, x=X, center=centre)
pars += const_mod.guess(Y, x=X)
mod = const_mod + gauss_mod + step_mod
result = mod.fit(Y, pars, x=X)
# write error report
#print result.fit_report()
print "contrast fit", result.redchi
return X, result.best_fit, result.redchi
示例2: fit_model
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def fit_model(ms_dx, guess_s, hours_per_frame=5/60):
fitfunc = lambda T, s, p: (s**2 * p**2) * (T/p - 1 + exp(-T/p))
n = len(ms_dx)//2
model = Model(fitfunc)
model.set_param_hint('s', value=guess_s, min=0, max=250)
# Constrain persistence time to ≥ 1 minute
model.set_param_hint('p', value=0.5, min=1/60.)
T = (arange(len(ms_dx)) + 1) * hours_per_frame
result = model.fit(ms_dx[:n], T=T[:n])
return result, (T, result.best_fit)
示例3: center_on_cos
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def center_on_cos(raw_quadratures, phi0=None, omega=None, snap_omega=False):
mean = scipy.average(raw_quadratures, axis=1)
no_angles, no_pulses = raw_quadratures.shape
model = Model(cos_model)
offset, amplitude, phi0, omega = guess_initial_parameters(mean, phi0, omega)
model.set_param_hint("offset", value=offset)
model.set_param_hint("amplitude", min=0., value=amplitude)
model.set_param_hint("phi0", value=phi0)
model.set_param_hint("omega", min=0., value=omega)
model.make_params(verbose=False)
steps = scipy.arange(no_angles)
res = model.fit(mean, x=steps, verbose=False)
omega_param = res.params["omega"]
if snap_omega:
appx_omega = float(omega_param)
no_pi_intervals = int(round(pi/appx_omega))
omega = pi/no_pi_intervals
omega_param.set(omega, vary=False)
res.fit(mean, x=steps, verbose=False)
d_value, p_value_ks = kstest(res.residual, 'norm')
mean_fit = res.eval(x=steps)
offset = mean-mean_fit
aligned_quadratures = raw_quadratures - offset[:,None]
centered_quadratures = aligned_quadratures - float(res.params["offset"])
return (centered_quadratures,
float(omega_param), float(res.params["phi0"]), p_value_ks)
示例4: test_weird_param_hints
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def test_weird_param_hints(self):
# tests Github Issue 312, a very weird way to access param_hints
def func(x, amp):
return amp*x
m = Model(func)
models = {}
for i in range(2):
m.set_param_hint('amp', value=1)
m.set_param_hint('amp', value=25)
models[i] = Model(func, prefix='mod%i_' % i)
models[i].param_hints['amp'] = m.param_hints['amp']
self.assertEqual(models[0].param_hints['amp'],
models[1].param_hints['amp'])
示例5: test_constraints_function_call
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def test_constraints_function_call():
"""Test a constraint with simple function call in Model class."""
x = [1723, 1773, 1823, 1523, 1773, 1033.03078, 1042.98077, 1047.90937,
1053.95899, 1057.94906, 1063.13788, 1075.74218, 1086.03102]
y = [0.79934, -0.31876, -0.46852, 0.05, -0.21, 11.1708, 10.31844, 9.73069,
9.21319, 9.12457, 9.05243, 8.66407, 8.29664]
def VFT(T, ninf=-3, A=5e3, T0=800):
return ninf + A/(T-T0)
vftModel = Model(VFT)
vftModel.set_param_hint('D', vary=False, expr=r'A*log(10)/T0')
result = vftModel.fit(y, T=x)
assert 2600.0 < result.params['A'].value < 2650.0
assert 7.0 < result.params['D'].value < 7.5
示例6: test_hints_in_composite_models
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def test_hints_in_composite_models(self):
# test propagation of hints from base models to composite model
def func(x, amplitude):
pass
m1 = Model(func, prefix='p1_')
m2 = Model(func, prefix='p2_')
m1.set_param_hint('amplitude', value=1)
m2.set_param_hint('amplitude', value=2)
mx = (m1 + m2)
params = mx.make_params()
param_values = {name: p.value for name, p in params.items()}
self.assertEqual(param_values['p1_amplitude'], 1)
self.assertEqual(param_values['p2_amplitude'], 2)
示例7: _iterate
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def _iterate(simulation, expected, guess, bounds, variables, independent, callable_, global_, local_):
biased_parameters = np.zeros((len(local_['input']), len(expected)))
success_ar = np.zeros(len(local_['input']))
expected_dict = {key: value for key, value in zip(variables, expected)}
gmod = Model(callable_, independent_vars=independent.keys(), param_names=variables, method='lbfgsb')
for param, ini, limits in zip(variables, guess, bounds):
gmod.set_param_hint(param, value=ini, min=limits[0], max=limits[1])
independent[global_['param']] = global_['input']
for i, input_ in enumerate(local_['input']):
independent[local_['param']] = input_
result = gmod.fit(simulation, verbose=False, **independent)
print(result.fit_report())
success_ar[i] = result.success
biased_parameters[i] = np.array([result.params[key].value - expected_dict[key] for key in variables])
return biased_parameters, success_ar
示例8: lmfit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def lmfit(mjd,flux,fluxerr):
t0_guess = mjd[np.argmax(flux)]
tau_fall_guess = 40.
tau_rise_guess = -5.
A = 150.
B = 20.
# nflux = np.zeros(2+len(np.array(flux)))
# nfluxerr = np.ones(2+len(np.array(flux)))/10.
# nmjd = np.zeros(2+len(np.array(flux)))
#
# nflux[1:-1] = flux
# nfluxerr[1:-1] = fluxerr
# nmjd[1:-1] = mjd
# nmjd[1] = mjd[0]-100.
# nmjd[-1] = mjd[-1]+150
#
# flux = nflux
# fluxerr = nfluxerr
# mjd = nmjd
bmod = Model(bazinfunc)
bmod.set_param_hint('t0', value=t0_guess, min=t0_guess-20, max=t0_guess+20)
bmod.set_param_hint('tau_fall', value=tau_fall_guess)
bmod.set_param_hint('tau_rise', value=tau_rise_guess)
bmod.set_param_hint('A',value=A)
bmod.set_param_hint('B',value=B)
pars = bmod.make_params()
#print(bmod.param_names)
#print(bmod.independent_vars)
# print(np.array(flux))
# print(np.array(1./np.array(fluxerr)))
# print(np.array(mjd))
result = bmod.fit(np.array(flux),method='leastsq',weights=1./np.array(fluxerr), t=np.array(mjd))
#print(result.fit_report())
# plt.clf()
# plt.errorbar(np.array(mjd), np.array(flux), yerr=fluxerr,fmt='o')
# plt.plot(np.array(mjd), result.init_fit, 'k--')
# plt.plot(np.array(mjd), result.best_fit, 'r-')
# #plt.xlim(mjd[1],mjd[-2])
# plt.savefig('bazinfit.png')
chisq = result.redchi
ps = result.best_values
popt = [ps['t0'],ps['tau_fall'],ps['tau_rise'],ps['A'],ps['B']]
#print('popt',popt)
#sys.exit()
# if chisq < 2.:
# input('good chisq!')
# popt, pcov, infodict, errmsg, ier = curve_fit(bazinfunc, mjd, flux,
# sigma=fluxerr, p0=p0, maxfev=2000000, full_output=True)
#
# chisq = (infodict['fvec'] ** 2).sum() / (len(infodict['fvec']) - len(popt))
return chisq,popt
示例9: GaussStepConst
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def GaussStepConst(signal, guess):
"""
Fits high contrast data very well
"""
if guess == False:
return [0, 0, 0]
else:
amp, centre, stdev, offset = guess
data = np.array([range(len(signal)), signal]).T
X = data[:,0]
Y = data[:,1]
# gauss_mod = Model(gaussian)
gauss_mod = Model(gaussian)
const_mod = ConstantModel()
step_mod = StepModel(prefix='step')
gauss_mod.set_param_hint('width', value = stdev / 2., min=stdev / 3., max=stdev)
gauss_mod.set_param_hint('fwhm', expr='2.3548*width')
pars = gauss_mod.make_params(height=amp, center=centre, width=stdev / 2., offset=offset)
pars += step_mod.guess(Y, x=X, center=centre)
pars += const_mod.guess(Y, x=X)
pars['width'].vary = False
mod = const_mod + gauss_mod + step_mod
result = mod.fit(Y, pars, x=X)
# write error report
#print result.fit_report()
fwhm = result.best_values['width'] * 2.3548
return X, result.best_fit, result.redchi, fwhm
示例10: tau_fitter
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def tau_fitter(data,nbins):
profile_peak = np.max(data)
binpeak = np.argmax(data)
modelname = GxETrain
model = Model(modelname)
model.set_param_hint('nbins', value=nbins, vary=False)
model.set_param_hint('sigma', value=15, vary=True, min =0, max = nbins)
model.set_param_hint('mu', value=binpeak, vary=True, min=0, max = nbins)
model.set_param_hint('A',value=profile_peak, vary=True)
model.set_param_hint('tau',value=200, vary=True, min=0)
model.set_param_hint('dc',value = 0, vary = True)
pars = model.make_params()
#"""Fit data"""
result = model.fit(data,pars,x=np.linspace(1,nbins,nbins))
# print(result.fit_report(show_correl = False))
noiselessmodel = result.best_fit
besttau = result.best_values['tau']
taustd = result.params['tau'].stderr ##estimated 1 sigma error
return noiselessmodel, besttau, taustd
示例11: example
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def example():
# possible values
from get_ssa import get_ssa
from Model import IrradianceModel
zenith = 53.1836240528
AMass = 1.66450160404
rel_h = 0.665
pressure = 950
AM = 5
ssa = get_ssa(rel_h, AM)
iteration = 20
alphas = np.zeros(len(range(1, iteration)) + 1)
x = np.linspace(200, 800, 100)
irr = IrradianceModel_python(AMass, rel_h, ssa, zenith, pressure)
irr_symbol = IrradianceModel(x, zenith, AMass, pressure, ssa)
func = irr_symbol._irradiance_ratio()
y = irr.irradiance_ratio(x, 2.5, 0.06, 0.0, 1.0, 1.0)
for i in range(0, iteration):
ssa = get_ssa(rel_h, AM)
print(ssa)
irr = IrradianceModel_python(AMass, rel_h, ssa, zenith, pressure)
yerror = np.random.normal(0, 0.009, len(x))
y = irr.irradiance_ratio(x, 1.5, 0.06, 0.0, 0.6, 0.9) + yerror
weights = 1 / yerror
gmod = Model(irr.irradiance_ratio, independent_vars=["x"], param_names=["alpha", "beta", "g_dsa", "g_dsr"])
gmod.set_param_hint("alpha", value=1.0, min=-0.2, max=2.5)
gmod.set_param_hint("beta", value=0.01, min=0.0, max=2.0)
gmod.set_param_hint("g_dsa", value=0.6, min=0.0, max=1.0)
gmod.set_param_hint("g_dsr", value=0.9, min=0.0, max=1.0)
print(gmod.param_hints)
print(gmod.param_names)
print(gmod.independent_vars)
result = gmod.fit(y, x=x)
print(result.fit_report())
alphas[i] = result.params["alpha"].value
# plt.plot(x, y, label='%s' % AM)
# plt.plot(x, result.best_fit, 'r-', label='fit')
y = irr.irradiance_ratio(x, 1.5, 0.06, 0.0, 0.6, 0.9)
y2 = irr.irradiance_ratio(x, 1.5, 0.08, 0.0, 0.6, 0.9)
plt.legend()
plt.show()
示例12: minimizefunction
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def minimizefunction(vars,low,high,data):
mymod=Model(myfitfunction)
newdata=[]
x=np.array(range(low,high),int)
for i in xrange(low,high):
newdata.append(data[i])
#params=getparams(vars)
mymod.set_param_hint('a',value=vars[0])
mymod.set_param_hint('b',value=vars[1],min=0,max=0.5)
mymod.set_param_hint('c',value=vars[2])
mymod.set_param_hint('d',value=vars[3],min=-1,max=1.1)
mymod.set_param_hint('e',value=vars[4])
mymod.set_param_hint('f',value=vars[5],min=-1,max=1.1)
mymod.set_param_hint('g',value=vars[6])
#print params
out=mymod.fit(newdata,x=x)
#result=getresult(out.params)
print(out.fit_report())
#x1=np.linspace(1,length,10000)
plt.plot(x,newdata,'blue',linestyle='dashed',marker='.')
plt.plot(x,out.init_fit,'y',linewidth=2)
plt.plot(x,out.best_fit,'r',linewidth=2)
plt.xlabel("circle(Time)")
plt.ylabel("fluorescence")
plt.legend()
plt.show()
file_result=open('./result/result_select_itera.txt','r+')
file_result.read()
file_result.write(out.fit_report())
file_result.write('\n\n')
file_result.close()
示例13: gauss_fit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def gauss_fit(x, y, a0=None, x0=None, sig0=None, emission=True):
""" Return ``curve_fit``, i.e., ``popt, pcov``.
def gauss_fit(x, y, a0=None, x0=None, sig0=None, emission=True, ssize=0.05):
# def gauss(x, a, x0, sigma):
# y0=1.
# return a*_np.exp(-(x-x0)**2/(2*sigma**2))+y0
if ssize < 0 or ssize > .5:
_warn.warn('Invalid ssize value...', stacklevel=2)
ssize = 0
ssize = int(ssize * len(y))
if ssize == 0:
ssize = 1
q = 95
func = _np.max
if not emission:
func = _np.min
q = 5
if a0 is None:
a0 = _np.abs(_np.percentile(y, q)) - _np.median(y)
if x0 is None:
x0 = x[_np.where(y == func(y))]
if sig0 is None:
sig0 = (_np.max(x)-_np.min(x))/10.
# if y0 is None:
# y0 = np.median(y)
# gmodel = _Model(gauss)
# gmodel.set_param_hint('a', min=0.2, max=20)
# if not emission:
# gmodel.set_param_hint('a', min=-0.2, max=-4)
# gmodel.set_param_hint('sigma', min=50, max=1000)
# result = gmodel.fit(y, x=x, a=a0, x0=x0, sigma=sig0)
# print(result.params['a'], result.params['sigma'], result.params['x0'])
# return result.params['a']*_np.sqrt(_np.pi*2)*result.params['sigma']
medx0, medx1 = _np.average(x[:ssize]), _np.average(x[-ssize:])
if ssize > 9:
medy0, medy1 = _np.median(y[:ssize]), _np.median(y[-ssize:])
else:
medy0, medy1 = _np.average(y[:ssize]), _np.average(y[-ssize:])
new_y = medy0 + (medy1 - medy0) * (x - medx0) / (medx1 - medx0)
g_init = _models.Gaussian1D(amplitude=a0, mean=x0, stddev=sig0)
fit_g = _fitting.LevMarLSQFitter()
g = fit_g(g_init, x, y-new_y)
"""
q = 95
func = np.max
if not emission:
func = np.min
q = 5
if a0 is None:
a0 = np.abs(np.percentile(y, q)) - np.median(y)
if x0 is None:
x0 = x[np.where(y == func(y))]
if sig0 is None:
sig0 = (np.max(x)-np.min(x))/10.
# if y0 is None:
# y0 = np.median(y)
gmodel = Model(gauss)
gmodel.set_param_hint('a', min=0.2, max=4)
if not emission:
gmodel.set_param_hint('a', min=-0.2, max=-4)
gmodel.set_param_hint('sigma', min=50, max=1000)
result = gmodel.fit(y, x=x, a=a0, x0=x0, sigma=sig0)
fig, (ax0, ax1) = plt.subplots(2, 1)
ax0.plot(x, y, 'bo')
ax0.plot(x, result.init_fit, 'k--')
ax0.plot(x, result.best_fit, 'r-')
ax0.set_title(fitsfile)
print(lbc, np.min(x))
idx = np.where((wl > lbc*0.98) & (wl < lbc*1.03))
ax1.plot(wl[idx], flux[idx], 'o')
plt.show(block=False)
cmd = phc.user_input('# Problem (y/other)? ')
if cmd.lower().startswith('y'):
raise ValueError
# phc.savefig(fig, figname=fitsfile)
return result.params['x0']
示例14: range
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
# Find Rupture Force
ruptureI = np.argmin(retractD)
ruptureF = k_L*(retractD[ruptureI] - y_shift)/contactS
ruptureL = (retractZ[ruptureI] - (retractD[ruptureI] - y_shift) - x_shift)
for x in range(len(retractZ)):
if (retractZ[x] - x_shift) < 0:
originPt = x
break
# Fit WLC model to rupture
separation = (retractZ - (retractD - y_shift) - x_shift)
skipPLT5 = True
gmod = Model(WLCmodel)
gmod.set_param_hint('L_C', value = -60.0)
gmod.set_param_hint('L_P', value = -0.38, min=-0.42, max=-0.34)
gmod.set_param_hint('a', value = 0.0, min=-10.0, max=10.0)
gmod.set_param_hint('b', value = 0.0, min=-10.0, max=10.0)
params = gmod.make_params()
try:
result = gmod.fit(smooth25[originPt:ruptureI], x=separation[originPt:ruptureI]) # method='cobyla'
except Exception:
skipPLT5 = False
sys.exc_clear()
if skipPLT5:
x_off = result.params['a'].value
y_off = result.params['b'].value
WLC_P = result.params['L_P'].value
WLC_L0 = result.params['L_C'].value
else:
示例15: fitfunction
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import set_param_hint [as 别名]
def fitfunction(vars,length,data,weight=None,method='leastsq'):
mymod=Model(myfitfunction)
x=np.array(range(1,length+1),int)
#params=getparams(vars)
mymod.set_param_hint('a',value=vars[0])
mymod.set_param_hint('b',value=vars[1],min=0,max=0.5)
mymod.set_param_hint('c',value=vars[2])
mymod.set_param_hint('d',value=vars[3],min=-1,max=1.1)
mymod.set_param_hint('e',value=vars[4])
mymod.set_param_hint('f',value=vars[5],min=-1,max=1.1)
mymod.set_param_hint('g',value=vars[6])
#print params
out=mymod.fit(data,x=x,weight=weight)
#result=getresult(out.params)
print(out.fit_report())
#x1=np.linspace(1,length,10000)
initialRMSE=printresult(data,out.init_fit)
bestRMSE=printresult(data,out.best_fit)
plt.plot(x,data,'blue',linestyle='dashed',marker='.')
plt.plot(x,out.init_fit,'y',linewidth=2)
print("RMSE of pso is{}".format(initialRMSE))
if initialRMSE<bestRMSE:
plt.plot(x,out.init_fit,'r',linewidth=2)
print("RMSE of iteration is {}".format(initialRMSE))
else:
plt.plot(x,out.best_fit,'r',linewidth=2)
print("RMSE of iteration is {}".format(bestRMSE))
plt.xlabel("circle(Time)")
plt.ylabel("fluorescence")
plt.legend()
plt.show()
file_result=open('./result/result_all_itera.txt','r+')
file_result.read()
file_result.write(out.fit_report())
file_result.write('\n\n')
file_result.close()