本文整理汇总了Python中lmfit.Model.fit方法的典型用法代码示例。如果您正苦于以下问题:Python Model.fit方法的具体用法?Python Model.fit怎么用?Python Model.fit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lmfit.Model
的用法示例。
在下文中一共展示了Model.fit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_resvar
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def get_resvar(x, y, mod='linear', zero_intercept=False):
"""
If `mod == 'linear'` then uses linear regression; otherwise
`mod == 'sigmoid'` and uses sigmoid regression.
"""
assert len(x) == len(y)
if len(x) < 3 or mod == 'linear':
model = Model(linear)
params = model.make_params()
params['a'].value = (y.max() - y.min()) / (x.max() - x.min())
params['b'].value = y.min()
if zero_intercept:
params['b'].value = 0
params['b'].vary = False
modfit = model.fit(y, x=x, params=params)
else:
model = Model(sigmoid)
modfit = model.fit(y, x=x, a=y.max(), b=1 / (x.max() - x.min()),
c=x.max())
finex = np.linspace(x.min(), x.max(), 50)
result = {
'mod': mod,
'params': modfit.best_values,
'resvar': modfit.residual.var(),
'y': modfit.best_fit,
'finex': finex,
'finey': modfit.eval(x=finex),
'r2': 1 - modfit.residual.var() / np.var(y),
'modfit': modfit}
return result
示例2: test_extra_param_issues_warning
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def test_extra_param_issues_warning(self):
# The function accepts extra params, Model will warn but not raise.
def flexible_func(x, amplitude, center, sigma, **kwargs):
return gaussian(x, amplitude, center, sigma)
flexible_model = Model(flexible_func)
pars = flexible_model.make_params(**self.guess())
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
flexible_model.fit(self.data, pars, x=self.x, extra=5)
self.assertTrue(len(w) == 1)
self.assertTrue(issubclass(w[-1].category, UserWarning))
示例3: test_extra_param_issues_warning
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def test_extra_param_issues_warning(self):
# The function accepts extra params, Model will warn but not raise.
guess = self.guess()
guess['extra'] = 5
def flexible_func(x, height, center, sigma, **kwargs):
return gaussian(x, height, center, sigma)
flexible_model = Model(flexible_func, ['x'])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
flexible_model.fit(self.data, x=self.x, **guess)
self.assertTrue(len(w) == 1)
self.assertTrue(issubclass(w[-1].category, UserWarning))
示例4: FitBiExpo_ResTime
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def FitBiExpo_ResTime(xdata,ydata,pixdim,lambda_p,isplot=False):
# flatten the input
xx = xdata.flatten()
yy = ydata.flatten()
# normalize the input
ymax = np.amax(yy)
nydata = yy/ymax
fmod = Model(Func_BiExpo)
initialp = {'a0':[0.0,1.0,0.0],'b0':[0.0,0.0,0.0],'a1':[1.0,-5.0,-10.],'b1':[1.0,1.0,0.0]}
chisqrThresh = 0.15
for ii in range(len(initialp['a0'])):
result = fmod.fit(np.squeeze(nydata),x=np.squeeze(xdata),a0=initialp['a0'][ii],b0=initialp['b0'][ii],a1=initialp['a1'][ii],b1=initialp['b1'][ii])
param = result.params.valuesdict()
auc = param['a0']/(param['b0'] + lambda_p) + param['a1']/(param['b1'] + lambda_p)
if result.chisqr > chisqrThresh or auc < 0.0:
print 'fit with tnc: chisqr = {}, auc = {}'.format(result.chisqr,auc)
else:
print 'leastsq: good fit!'
break
if result.chisqr > chisqrThresh or auc < 0.0:
for ii in range(len(initialp['a0'])):
result = fmod.fit(np.squeeze(nydata),x=np.squeeze(xdata),a0=initialp['a0'][ii],b0=initialp['b0'][ii],a1=initialp['a1'][ii],b1=initialp['b1'][ii],method='tnc')
if result.chisqr > chisqrThresh or auc < 0.0:
print 'fit with tnc: chisqr = {}, auc = {}'.format(result.chisqr,auc)
else:
print 'tnc: good fit!'
break
# set up best-fit result
param = result.params.valuesdict()
p1 = [param['a0'],param['b0'],param['a1'],param['b1']]
fitydata = ymax*result.eval(x=xdata) # regularize the fitted result
r2 = GetR2(ydata,fitydata)
xfit = np.linspace(np.amin(xx),np.amax(xx),500)[:,np.newaxis]
yfit = ymax*result.eval(x=xfit)
if isplot:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(xx,yy,'ro',label='Original data')
ax.plot(xfit,yfit,label='Fitted data')
plt.show()
return p1,r2,ymax,xfit,yfit
示例5: lmDDOPhaseFit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def lmDDOPhaseFit(xdata, ydata, params, f0_range = 1.2, Q_range = 3):
f0= params[0]
Q=1/(2*params[2])
x = xdata
y = ydata
#Define a linear model and a Damped Oscillator Model
# ddophase_mod = ExpressionModel('off + m*x- arctan(1/Q * 1/(f0/x - x/f0))-')
ddophase_mod = Model(phase)
#Initial Pars for Linear Model
pars = ddophase_mod.make_params(off=0, m=0, f0=f0, Q=Q)
#Add fit parameters, Center, Amplitude, and Sigma
pars['f0'].set(min=f0/f0_range, max=f0*f0_range)
pars['Q'].set(min=Q/Q_range, max=Q*Q_range)
#Create full model. Add linear model and all peaks
#Initialize fit
init = ddophase_mod.eval(pars, x=x)
#Do the fit. The weight exponential can weight the points porportional to the
#amplitude of y point. In this way, points on peak can be given more weight.
out=ddophase_mod.fit(y, pars,x=x)
#Get the fit parameters
fittedf0= out.params['f0'].value
fittedQ = out.params['Q'].value
#Returns the output fit as well as an array of the fit parameters
"""Returns output fit as will as list of important fitting parameters"""
return out, [fittedf0, np.nan, np.nan, fittedQ]
示例6: generalfit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def generalfit(vars,Xmin,Xmax,method,data):
mymod=Model(myfitfunction)
x=np.array(range(Xmin+1,Xmax+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
'''newdata=[]
for i in xrange(Xmin,Xmax):
newdata.append(data[i])'''
out=mymod.fit(data,x=x,method=method,jac=True)
#result=getresult(out.params)
print(out.fit_report())
#x1=np.linspace(1,length,10000)
plt.plot(x,data,'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_general_itera.txt','r+')
file_result.read()
file_result.write(out.fit_report())
file_result.write('\n\n')
file_result.close()
示例7: rescale_reframe
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def rescale_reframe(scisub, refsub, verbose=False):
"""Example function with types documented in the docstring.
`PEP 484`_ type annotations are supported. If attribute, parameter, and
return types are annotated according to `PEP 484`_, they do not need to be
included in the docstring:
Args:
param1 (int): The first parameter.
param2 (str): The second parameter.
Returns:
bool: The return value. True for success, False otherwise.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
params = Parameters()
params.add('sigma', 1.0, True, 0.0, inf)
image_sub = Model(res_sigma_image_flat, independent_vars=['scisub', 'refsub'])
image_sub_results = image_sub.fit(data=scisub.ravel(), params=params, scisub=scisub, refsub=refsub)
if verbose: print('Sigma of Rescale: {}'.format(image_sub_results.params['sigma'].value))
return partial_res_sigma_image(image_sub_results.params['sigma'].value)
开发者ID:exowanderer,项目名称:Reference-Frame-Calibration,代码行数:30,代码来源:Reference_Image_Subtraction_-_Comet_Pipeline.py
示例8: minimizefunction
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [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()
示例9: center_on_cos
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [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)
示例10: fitGauss
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def fitGauss(self, xdata=None, ydata=None, withBG=False, inits=None):
'''
Usage: fitGauss(xdata,ydata,withBG=False,inits=None)
xdata and ydata must have the same length, and a well defined peak
withBG: fit gaussian with linear background
inits: withBG == False -> [A,mu,sigma]
withBG == True -> [A,mu,sigma,m,b]
'''
def gauss(x, A, mu, sigma):
return A*np.exp(-(x-mu)**2/(2.*sigma**2))
def gaussBG(x, A, mu, sigma, m, b):
return b+m*x+A*np.exp(-(x-mu)**2/(2.*sigma**2))
if withBG:
gBGmod = Model(gaussBG)
else:
gmod = Model(gauss)
if inits is None:
mu_i = xdata[np.argmax(ydata)]
A_i = np.max(ydata)
sigma_i = 0.5
if withBG:
m_i = -0.1
b_i = ydata[np.argmax(ydata)-50]
else:
A_i = inits[0]
mu_i = inits[1]
sigma_i = inits[2]
if withBG:
m_i = inits[3]
b_i = inits[4]
if withBG:
results = gBGmod.fit(ydata,x=xdata,A=A_i,mu=mu_i,sigma=sigma_i,b=b_i,m=m_i)
else:
results = gmod.fit(ydata,x=xdata,A=A_i,mu=mu_i,sigma=sigma_i)
return results
示例11: multi_disk_fit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def multi_disk_fit(arcmin_sma, intens, intens_err, bounds, psf):
h_mat_0 = numpy.ones(len(bounds - 1))
mod = Model(multi_disk_func)
pars = mod.make_params(I0 = 1.0, h_mat = h_mat_0, bounds = bounds, PSF = PSF)
pars['bounds'].vary = False
pars['PSF'].vary = False
results = mod.fit(intens, params = pars, x = arcmin_sma, weights = 1.0/intens_err)
pdb.set_trace()
示例12: lmfit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [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
示例13: fit_D_phi_powerlaw
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def fit_D_phi_powerlaw(phi_, D):
"""fit stuff"""
Dmod = Model(Dhop_powerlaw)
params = Dmod.make_params()
params['p'].set(0.3)
result = Dmod.fit(D, params, phi=phi_)
print result.fit_report(min_correl=0.5)
p = result.params['p'].value
return p
示例14: fit_model
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [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)
示例15: Gaussian_Fit
# 需要导入模块: from lmfit import Model [as 别名]
# 或者: from lmfit.Model import fit [as 别名]
def Gaussian_Fit(xData,yData, cen, ifPlot=False):
gmod = Model(gaussian)
result = gmod.fit(yData, x=xData, amp=5, cen=cen, wid=1)
if ifPlot == True :
plt.plot(xData, yData, 'bo')
plt.plot(xData, result.best_fit, 'r-')
plt.ylim(min(min(result.best_fit),min(xData)),max(max(result.best_fit),max(yData)))
plt.show()
return result.best_values, result.best_fit