Search code examples
mathscipycurve-fittingmodel-fitting

multivariable non-linear curve_fit with scipy


I have been trying to use scipy.optimize curve_fit using multiple variables. It works fine with the test code I created but when I try to implement this on my actual data I keep getting the following error

TypeError: only arrays length -1 can be converted to python scalars

The shape of the arrays and the data types of their elements in my test code and actual code are exactly the same so I am confused as to why I get this error.

Test code:

    import numpy as np 
    import scipy 
    from scipy.optimize import curve_fit

    def func(x,a,b,c):
          return a+b*x[0]**2+c*x[1]
    x_0=np.array([1,2,3,4])
    x_1=np.array([5,6,7,8])
    X=scipy.array([x_0,x_1])
    Y=func(X,3.1,2.2,2.1)
    popt, pcov=curve_fit(func,X,Y)

Actual code:

    f=open("Exp_Fresnal.csv", 'rb')
    reader=csv.reader(f)
    for row in reader:
         Qz.append(row[0])
         Ref.append(row[1])
         Ref_F.append(row[2])
    Qz_arr,Ref_Farr=scipy.array((Qz)),scipy.array((Ref_F))
    x=scipy.array([Qz_arr,Ref_Farr]

    def func(x,d,sig_int,sig_cp):
         return x[1]*(x[0]*d*(math.exp((-sig_int**2)*(x[0]**2)/2)/(1-cmath.exp(complex(0,1)*x[0]*d)*math.exp((-sig_cp**2)*(x[0]**2)/2))))**2

    Y=scipy.array((Ref))
    popt, pcov=curve_fit(func,x,Y)

EDIT Here is the full error message

Traceback (most recent call last): File "DCM_03.py", line 46, in <module> popt, pcov=curve_fit(func,x,Y) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 651, in curve_fit res = leastsq(func, p0, args=args, full_output=1, **kwargs) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 377, in leastsq shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 26, in _check_func res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) File "//anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 453, in _general_function return function(xdata, *params) - ydata File "DCM_03.py", line 40, in func return (0.062/(2*x))**4*(x*d*(math.exp((-sig_int**2)*(x**2)/2)/(1-cmath.exp(complex(0,1)*x*d)*math.exp((-sig_cp**2)*(x**2)/2))))**2 TypeError: only length-1 arrays can be converted to Python scalars


Solution

  • I figured out the issue. The problem for some reason was the use of math.exp and cmath.exp in the fitting function func. In place of these functions I used np.exp(). I am not completely sure the reason why though.