Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

python - Passing additional arguments using scipy.optimize.curve_fit?

I am writing a program in Python that will fit Gaussian and Lorentzian shapes to some given resonance data. I originally began using scipy.optimize.leastsq but changed to using optimize.curve_fit after having difficulties in retrieving the errors in the optimized parameters from the covariance matrix.

I have defined a function to fit a sum of Gaussian and 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

where p is an array of the initial guesses at the fit parameters. Here is the instance where it is called using curve_fit:

leastsq,covar = opt.curve_fit(mix,energy,intensity,inputtot)

At the moment numg (the number of Gaussian shapes) is a global variable. Is there's any way that it can be incorporated into curve_fit as an extra argument instead, as can be done with leastsq?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The great thing about python is that you can define functions that return other functions, try 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

and then

leastsq, covar = opt.curve_fit(make_mix(numg),energy,intensity,inputtot)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...