非线性最小二乘拟合,变量作为积分极限

时间:2015-03-02 15:49:29

标签: python physics numeric curve-fitting

我试图用python制作一些涉及积分的非线性配件,积分的极限取决于自变量。代码如下:

import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.integrate import quad


T,M=np.genfromtxt("zfc.txt", unpack=True, skiprows = 0) #here I load the data to fit
plt.plot(T,M,'o')

def arg_int1(x,sigma,Ebm):
    return (1/(np.sqrt(2*np.pi)*sigma*Ebm))*np.exp(-(np.log(x/float(Ebm))**2)/(2*sigma**2))
def arg_int2(x,sigma,Ebm):
    return (1/(np.sqrt(2*np.pi)*sigma*x))*np.exp(-(np.log(x/float(Ebm))**2)/(2*sigma**2))



def zfc(x,k1,k2,k3):   
    Temp=x*k2*27/float(k2/1.36e-16) 
    #Temp=k2*27/float(k2/1.36e-16) #apparently x can't be fitted with curve_fit if appears as well in the integral limits
    A=sc.integrate.quad(arg_int1,0,Temp,args=(k3,k2))[0]
    B=sc.integrate.quad(arg_int2,Temp,10*k2,args=(k3,k2))[0]
    M=k1*(k2/1.36e-16*A/x+B)
    return M
T_fit=np.linspace(1,301,301)


popt, pcov = curve_fit(zfc,T,M,p0=(0.5,2.802e-13,0.46))

M_fit=np.zeros(301)
M_fit[0]=zfc(100,0.5,2.8e-13,0.46)
for i in range (1,301):    
    M_fit[i-1]=zfc(i,popt[0],popt[1],popt[2])
plt.plot(T_fit,M_fit,'g')

我得到的错误是:

  File "C:\Users\usuario\Anaconda\lib\site-packages\scipy\integrate\quadpack.py", line 329, in _quad
    if (b != Inf and a != -Inf):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我不明白,因为功能定义明确。我知道我的问题的解决方案是参数(我已经使用mathematica)。我试图寻找Bloch-Gruneisen函数的拟合(其中自变量也定义了积分限制)但我没有发现任何线索。

1 个答案:

答案 0 :(得分:1)

问题是scipy.optimize.curve_fit期望zfc处理数组参数,即给定一个x值的n个数组和3个k1的n个数组,{{1} } {,k2k3应返回包含函数对应值的n数组。但是,可以通过使用zfc(x,k1,k2,k3)

为函数创建包装器来轻松实现
np.vectorize

如果您能提供一些示例输入数据,那么下次会很好。我设法用一些任意函数的测试数据运行它,但情况可能并非总是如此。

干杯。

相关问题