I used odeint to solve a coupled differential equation in terms of v(t) and u(t).
f = odeint(ODEs, f0, t)
v = f[:,0]
u = f[:,1]
I want to get x, which is the integral of v(t), so I have this code that uses scipy.integrate.quad:
x = lambda t: f[t,0]
delta_x=quad(x, 0,1)
print(delta_x)
When I run this, I get
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
and my Jupyter Notebook highlights f[t,0]. Why is there an index error if the function is defined everywhere within the bounds of integration? How can I solve the error or get the integral via another method?
Here is a minimal reproducible example:
import numpy as np
from scipy.integrate import odeint, quad
def ODEs(f,t):
v = f[0]
u = f[1]
dvdt = u-v
dudt = (v-u)/3
return [dvdt, dudt]
f0 = [0.3, 0.2]
t = np.linspace(0,4,10000)
f = odeint(ODEs, f0, t)
v = f[:,0]
u = f[:,1]
x = lambda t: f[t,0]
delta_x=quad(x, 0,1)
print(delta_x)
As mentioned in the comments,
quadwill evaluate a function at various points and compute the integral that way. Since you have discrete values fromodeint, you cannot usequad. Instead, you can usenp.trapzto perform the integration using the trapezoid rule from the discrete results.Alternatively, you can use
scipy.integrate.solve_ivpwithdense_output=True. The ODE integration result will then have asolattribute which is a function that can be evaluated. This can then be used forquad.