How to use integrate.quad with an array

Question:

I would like to use integrate.quad with an array but it returns me : "TypeError: only size-1 arrays can be converted to Python scalars"

I understand that the first argument which is required must be a scalar. But the argument I want to use comes from a function that depends on one parameter and that return an array and I can’t get the problem fixed:

Here is my script in Python:

from scipy import integrate as intg

DfH_ref_jp = np.array([0,-393.52,-110.53,-74.87,-241.83,0]) *1000
n_jp = np.array([1.2,0.2,0.15,0.001,0.49,0.30])
Tref = 1298
Ta = 1310

def c_jp(T):
    t = T/1000
    XC = np.array([1,t,t**2,t**3,t**(-2)])
    Mah = M_ah(T)                            # a matrix defined before
    c = np.dot(Mah[:,:5],XC)

    return c

H1_jp = n_jp * (DfH_ref_jp + intg.quad(c_jp,Tref,Ta)[0])   # this where it doesn't work / [0] because intg.quad returns an array and I want the first value

So I have tried with a function which returns a scalar:

def c_jp0(T):
    t = T/1000
    XC = np.array([1,t,t**2,t**3,t**(-2)])
    Mah = M_ah(T)
    c = np.dot(Mah[0,:5],XC)

    return c

H1_jp = np.zeros(6, dtype=float)
H1_jp[0] = n_jp[0] * (DfH_ref_jp[0] + intg.quad(c_jp0,Tref,Ta)[0]) 

It works but I don’t want to specify 6 functions : c_jp0 … c_jp6.
Does anyone has an idea how to do it ?
Thanks

Asked By: booo

||

Answers:

The quad method, is designed to integrate a scalar function only over one scalar variable.

If your integral has only one integration variable, but depends on other parameters you can pass them via params in quad(func, a, b, params).

If you want to integrate over multiple variables you can use nquad, in that case you have to give a limit for each of your variables.

If the limits are constant you can pass them directly, if the limits depend on other integration variable you must pass the limits as a function of variables
that are not integrated yet.

e.g.
For instance, to calculate the volume of a cube having one corner at the origin and other corner at the point (1,1,1).

from scipy import integrate as intg
nquad(lambda x,y,z: 1.0, [(0,1), (0,1), (0,1)])

Or the volume of square base pyramid with vertices at (0,0,1), (-1,-1,0) and (1,1,0). Where the limits of x and y depends on z

from scipy import integrate as intg
intg.nquad(lambda x,y,z: 1.0, [lambda y,z: (z-1,1-z), lambda z: (z-1,1-z), (0,1)])
Answered By: Bob