使用scipy.optimize.curve_fit传递其他参数?

Mat*_*kin 15 python scipy

我正在用Python编写一个程序,它将高斯和洛伦兹的形状与某些给定的共振数据相匹配.我最初开始使用scipy.optimize.leastsq但是optimize.curve_fit在从协方差矩阵中检索优化参数中的错误之后变得难以使用.

我已经定义了一个函数来拟合Gaussian和Lorentzian的和:

def mix(x,*p):
    ng = numg
    p1 = p[:3*ng]
    p2 = p[3*ng:]
    a = sumarray(gaussian(x,p1),lorentzian(x,p2))
    return a
Run Code Online (Sandbox Code Playgroud)

其中p是拟合参数的初始猜测数组.以下是使用curve_fit以下方法调用它的实例:

leastsq,covar = opt.curve_fit(mix,energy,intensity,inputtot)
Run Code Online (Sandbox Code Playgroud)

目前numg(高斯形状的数量)是一个全局变量.有没有什么方法可以将它curve_fit作为一个额外的参数纳入,就像可以做到的那样leastsq

She*_*hep 20

关于python的好处是你可以定义返回其他函数的函数,尝试currying:

def make_mix(numg): 
    def mix(x, *p): 
        ng = numg
        p1 = p[:3*ng]
        p2 = p[3*ng:]
        a = sumarray(gaussian(x,p1),lorentzian(x,p2))
        return a
    return mix
Run Code Online (Sandbox Code Playgroud)

然后

leastsq, covar = opt.curve_fit(make_mix(numg),energy,intensity,inputtot)
Run Code Online (Sandbox Code Playgroud)