我试图用python
和lmfit
将指数衰减函数与测量仪器响应进行卷积拟合
我是python新手,我正在尝试遵循https://groups.google.com/group/lmfit-py/attach/90f51c25ebb39a52/deconvol_exp2.py?part=0.1&authuser=0中的代码
import numpy as np
from lmfit import Model
import matplotlib.pyplot as plt
import requests
# Load data
url = requests.get('https://groups.google.com/group/lmfit-py/attach/73a983d40ad945b1/tcspcdatashifted.csv?part=0.1&authuser=0')
x,decay1,irf=np.loadtxt(url.iter_lines(),delimiter=',',unpack=True,dtype='float')
plt.figure(1)
plt.semilogy(x,decay1,x,irf)
plt.show()
# Define weights
wWeights=1/np.sqrt(decay1+1)
# define the double exponential model
def jumpexpmodel(x,tau1,ampl1,tau2,ampl2,y0,x0,args=(irf)):
ymodel=np.zeros(x.size)
t=x
c=x0
n=len(irf)
irf_s1=np.remainder(np.remainder(t-np.floor(c)-1, n)+n,n)
irf_s11=(1-c+np.floor(c))*irf[irf_s1.astype(int)]
irf_s2=np.remainder(np.remainder(t-np.ceil(c)-1,n)+n,n)
irf_s22=(c-np.floor(c))*irf[irf_s2.astype(int)]
irf_shift=irf_s11+irf_s22
irf_reshaped_norm=irf_shift/sum(irf_shift)
ymodel = ampl1*np.exp(-(x)/tau1)
ymodel+= ampl2*np.exp(-(x)/tau2)
z=Convol(ymodel,irf_reshaped_norm)
z+=y0
return z
# convolution using fft (x and h of equal length)
def Convol(x,h):
X=np.fft.fft(x)
H=np.fft.fft(h)
xch=np.real(np.fft.ifft(X*H))
return xch
# assign the model for fitting
mod=Model(jumpexpmodel)
定义拟合的初始参数时,我会得到错误
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
#initialize the parameters - showing error
pars = mod.make_params(tau1=10,ampl1=1000,tau2=10,ampl2=1000,y0=0,x0=10,args=irf)
pars['x0'].vary =True
pars['y0'].vary =True
print(pars)
# fit this model with weights, initial parameters
result = mod.fit(decay1,params=pars,weights=wWeights,method='leastsq',x=x)
# print results
print(result.fit_report())
# plot results
plt.figure(5)
plt.subplot(2,1,1)
plt.semilogy(x,decay1,'r-',x,result.best_fit,'b')
plt.subplot(2,1,2)
plt.plot(x,result.residual)
plt.show()
根据lmfit.model
的文档,我怀疑这是因为参数irf
在模型中是如何定义为args=(irf)
。我试图将irf
传递给model
,而不是params
。我还尝试使用**kwargs
将irf
合并到model
进行卷积并拟合数据的正确方法是什么?
我相信你想把^ {CD1>}作为模型函数的附加独立变量——一个值,你传递给函数,但在拟合中不被当作变量。
为此,只需修改模型函数
jumpexpmodel()
的签名,使其更简单函数的主体很好(实际上
args=(irf)
不起作用,因为您需要解包args
这里的签名确实是您想要的)然后告诉
lmfit.Model()
irf
是一个自变量-默认情况下第一个参数是唯一的自变量:然后,在制作参数时,不要包括
irf
或args
:而是现在将{}与{}一起传递给{}:
程序的其余部分看起来很好,由此产生的拟合效果会相当好,并给出一份
像这样的情节:
相关问题 更多 >
编程相关推荐