高斯多指数衰减曲线拟合的python代码

2024-06-07 14:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个代码来拟合一个数据模型,这个模型是两个函数的卷积(gausian with multi-exp decause exp(Ax)+exp(Bx)+…)。基本上,只有高斯和/或高斯修正的https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution拟合在Lmfit中工作得非常好,但是使用了内置卷积(即如果np.卷积使用了两个函数的Lmfit不起作用。在

我在网上试过很多例子,到目前为止,我发现我的函数返回inf或nan值,而且数据在卷积中的间距也不相等。通过使用卷积的数学表达式和scipy.optimize.curve U拟合。但这是一个非常笨拙和耗时的方法,我想通过使用两个函数的卷积和使用lmfit使其更加复杂和通用,因为我可以更容易地控制参数。 数据集也包含在coments中作为参考。在

w=0.1 # is constant
def CONVSum(x,w,*p):
    n=np.int(len(p)/3)
    A=p[:n]
    B=p[n:2*n]
    C=p[2*n:3*n]
# =======================================================================
#     below formula is drived as mathematical expresion of convoluted multi exponential components with a gausian distribution based on the instruction given in http://www.np.ph.bham.ac.uk/research_resources/programs/halflife/gauss_exp_conv.pdf
# ======================================================================
    fnct=sum(np.float64([A[i]*np.exp(-B[i]*((x-C[i])-(0.5*np.square(w)*B[i])))*(1+scipy.special.erf(((x-C[i])-(np.square(w)*B[i]))/(np.sqrt(2)*w))) for i in range(n)]))
    fnct[np.isnan(fnct)]=0
    fnct[fnct<1e-12]=0
    return fnct
N=4 #number of exponential functions to be fitted
params = np.linspace(1, 0.0001, N*3); #parameters for a multiple exponential                                                                                                                        
popt,pcov = curve_fit(CONVSum,x,y,p0=params,
    bounds=((0,0,0,0,-np.inf,-np.inf,-np.inf,-np.inf,-3,-3,-3,-3),
           (1,1,1,1, np.inf, np.inf, np.inf, np.inf, 3, 3, 3, 3)),
           maxfev = 1000000)

fitted data with curve fitt

关于高斯和多重指数衰减的卷积拟合的任何帮助或提示 高度赞赏,我更喜欢使用lmfit,因为我可以很好地识别参数,也可以将它们与每个oter关联起来。在

理想情况下,我想用一些参数来拟合我的数据,其中一些参数在数据集中共享,有些则延迟(+偏移设置)。在


Tags: 数据函数参数withnpscipymulti卷积
2条回答

好吧,你的剧本有点难读,而且有很多东西跟你的问题无关。您的exgauss函数并没有防范无穷大。np.exp(x)对于x>;~710将提供Inf,并且fit将无法继续。在

以下是所讨论的固化配件代码的等价物。我通过在here和{a2}中使用非常好的指令和信息来创建这个。但它仍然需要发展。在

    # =============================================================================
    #     below formula is drived as mathematical expresion of convoluted multi exponential components with a gausian distribution based on the instruction given in http://www.np.ph.bham.ac.uk/research_resources/programs/halflife/gauss_exp_conv.pdf
    # =============================================================================

def CONVSum(x,params):
    fnct=sum(
            np.float64([
                    (params['amp%s_%s'%(n,i)].value)*np.exp(-(params['dec%s_%s'%(n,i)].value)*((x-(params['cen%s_%s'%(n,i)].value))-
                     (0.5*np.square((params['sig%s_%s'%(n,i)].value))*(params['dec%s_%s'%(n,i)].value))))*
                    (1+scipy.special.erf(((x-(params['cen%s_%s'%(n,i)].value))-(np.square((params['sig%s_%s'%(n,i)].value))*
                    (params['dec%s_%s'%(n,i)].value)))/(np.sqrt(2)*(params['sig%s_%s'%(n,i)].value)))) for n in range(N) for i in wav 
                    ])
            )
    fnct=fnct/fnct.max()
    return fnct
    # =============================================================================
    #  this global fit were adapted from  https://stackoverflow.com/questions/20339234/python-and-lmfit-how-to-fit-multiple-datasets-with-shared-parameters/20341726#20341726

    # it is of very important thet we can identify the shared parameteres for datasets
    # =============================================================================


def objective(params, x, data):
    """ calculate total residual for fits to several data sets"""
    ndata = data.shape[0]
    resid = 0.0*data[:]
    # make residual per data set
    resid = data- CONVSum(x,params)
    # now flatten this to a 1D array, as minimize() needs
    return resid.flatten()


# selec datasets
x  = df[949].index
data =df[949].values


# create required sets of parameters, one per data set
N=4 #number of exponential decays
wav=[949]  #the desired data to be fitted
fit_params = Parameters()
for i in wav:
        for n in range(N):
            fit_params.add( 'amp%s_%s'%(n,i), value=1, min=0.0,  max=1)
            fit_params.add( 'dec%s_%s'%(n,i), value=0.5, min=-1e10,  max=1e10)
            fit_params.add( 'cen%s_%s'%(n,i), value=0.1, min=-3.0,  max=1000)
            fit_params.add( 'sig%s_%s'%(n,i), value=0.1, min=0.05, max=0.5)

# now we constrain some values to have the same value
# for example assigning sig_2, sig_3, .. sig_5 to be equal to sig_1
for i in wav:
        for n in (1,2,3):
            print(n,i)
            fit_params['sig%s_%s'%(n,i)].expr='sig0_949'
            fit_params['cen%s_%s'%(n,i)].expr='cen0_949'

# it will run the global fit to all the data sets
result = minimize(objective, fit_params, args=(x,data)) 
report_fit(result.params)

# plot the data sets and fits
plt.close('all')
plt.figure()
for i in wav:
    y_fit = CONVSum(x,result.params)
    plt.plot(x, data, 'o-', x, y_fit, '-')
    plt.xscale('symlog') 
plt.show()

fitted data with convolution of multi exponential and gausian

不幸的是,拟合结果不是很令人满意,我仍在寻找一些建议,以改善这一点。在

相关问题 更多 >

    热门问题