Search code examples
pythonscipysyntax-errorleast-squaresambiguous

Python: optimize.leastsq. ValueError: The truth value of an array with more than one element is ambiguous


Everything work except for the last line. My goal is to calculate the best fit through the chi-squared test. There is something wrong with the application of leastsq function. z,d and d_err are arrays of the same length, given (the experimental data).

def df(z,omega_m,omega_l):
    return 1/(np.sqrt(omega_m*(1+z)**3+(1-omega_m-omega_l)*(1+z)**2+omega_l))

def DL(z,omega_m,omega_l,H_0):      #   checked with Hubble's law with low z, it is consistent
    f,err_f=scipy.integrate.quad(df,0,z,args=(omega_m,omega_l))     #   it's evident err_f it's irrelevant

    if omega_m+omega_l==1:
        return 299792./H_0*(1+z)*f

    elif omega_m+omega_l<1:
        fk=np.sin(np.sqrt(np.absolute(1-omega_l-omega_m))*f)
        return 299792./H_0*(1+z)/np.sqrt(np.absolute(1-omega_m-omega_l))*fk

    elif omega_m+omega_l>1:
        fk=np.sinh(np.sqrt(np.absolute(1-omega_l-omega_m))*f)
        return 299792./H_0*(1+z)/np.sqrt(np.absolute(1-omega_m-omega_l))*fk


params=(0.3,0.7,73) #   starting values for minimization   omega_m, omega_l, H_0

def chi(params,z,d,d_err):   #   checked, this function works
    return (d-DL(z,params[0],params[1],params[2]))**2/d_err

minimization,minimization_cov=optimize.leastsq(chi,params,args=(z,d,d_err))

This is the complete message of error:

File "C:\Python34\lib\site-packages\scipy\integrate\quadpack.py", line 360, 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()

Solution

  • The third argument to scipy.integrate.quad() is the upper limit and must be a float. You use z as the third argument which is a NumPy array.

    Signature: scipy.integrate.quad(func, a, b, ...)

    Integrate func from a to b (possibly infinite interval) using a technique from the Fortran library QUADPACK.

    ...

    a : float

    Lower limit of integration (use -numpy.inf for -infinity).

    b : float

    Upper limit of integration (use numpy.inf for +infinity).