Systems of ODEs
Most models have several interacting unknowns: predators and prey, position and velocity, concentrations of several chemicals. Numerically a system is no harder than a single equation: the same methods apply with replaced by a vector. Higher-order equations are first rewritten as first-order systems.
Vector form
Every method of this part works verbatim for vectors. Euler's method, for example, is . In NumPy the state is a 1D array and returns an array of the same shape.
import numpy as np
from scipy.integrate import solve_ivp
def lotka_volterra(t, u, a=1.0, b=0.1, c=1.5, d=0.075):
prey, pred = u
return np.array([a * prey - b * prey * pred, -c * pred + d * prey * pred])
sol = solve_ivp(lotka_volterra, (0, 15), [10.0, 5.0], rtol=1e-9, dense_output=True)
for t in (0, 3, 6, 9, 12, 15):
prey, pred = sol.sol(t)
print(f"t = {t:2d}: prey {prey:7.3f}, predators {pred:7.3f}")t = 0: prey 10.000, predators 5.000
t = 3: prey 31.846, predators 19.704
t = 6: prey 13.512, predators 3.602
t = 9: prey 16.750, predators 22.885
t = 12: prey 19.164, predators 3.098
t = 15: prey 9.780, predators 17.167
Higher order to first order
An -th order equation becomes first-order equations by introducing derivatives as new unknowns. The pendulum with , :
import numpy as np
from scipy.integrate import solve_ivp
g_over_L = 9.81
def pendulum(t, u):
return [u[1], -g_over_L * np.sin(u[0])]
for amp_deg in (5, 45, 90, 170):
u0 = [np.radians(amp_deg), 0.0]
# period: first return to the starting turning point, where theta' crosses 0 from + to -
def turning(t, u): return u[1]
turning.direction = -1
sol = solve_ivp(pendulum, (0, 20), u0, events=turning, rtol=1e-10, atol=1e-12)
T = sol.t_events[0][sol.t_events[0] > 1e-6][0] # skip the event at t = 0
print(f"amplitude {amp_deg:3d} deg: period {T:.5f} s (small-angle {2 * np.pi / np.sqrt(g_over_L):.5f} s)")amplitude 5 deg: period 2.00702 s (small-angle 2.00607 s)
amplitude 45 deg: period 2.08626 s (small-angle 2.00607 s)
amplitude 90 deg: period 2.36784 s (small-angle 2.00607 s)
amplitude 170 deg: period 4.89352 s (small-angle 2.00607 s)
Large swings take longer, which the small-angle formula misses.
Many bodies
Systems of particles have one block of equations per particle. Writing the right-hand side with array operations keeps the code fast. Here are three bodies with gravity in the plane (units with ):
import numpy as np
from scipy.integrate import solve_ivp
m = np.array([1.0, 1.0, 1.0])
def nbody(t, u):
pos = u[:6].reshape(3, 2); vel = u[6:].reshape(3, 2)
d = pos[None, :, :] - pos[:, None, :] # d[i, j] = pos_j - pos_i
r3 = np.sum(d**2, axis=2) ** 1.5 + np.eye(3) # avoid division by zero on the diagonal
acc = np.sum(m[None, :, None] * d / r3[:, :, None], axis=1)
return np.concatenate([vel.ravel(), acc.ravel()])
# the figure-eight choreography (Chenciner-Montgomery initial data)
p = np.array([[-0.97000436, 0.24308753], [0.0, 0.0], [0.97000436, -0.24308753]])
v3 = np.array([-0.93240737, -0.86473146])
v = np.array([-v3 / 2, v3, -v3 / 2])
u0 = np.concatenate([p.ravel(), v.ravel()])
T = 6.32591398
sol = solve_ivp(nbody, (0, T), u0, method="DOP853", rtol=1e-12, atol=1e-12)
print(f"after one period, max change in positions: {np.max(np.abs(sol.y[:6, -1] - u0[:6])):.1e}")
print("total momentum:", np.round((m[:, None] * sol.y[6:, -1].reshape(3, 2)).sum(axis=0), 12) + 0)after one period, max change in positions: 3.0e-08
total momentum: [0. 0.]
In software
solve_ivpexpectsfun(t, y)returning an array of shape(n,);vectorized=Truelets it evaluate several states at once for finite-difference Jacobians.- Physics engines and molecular dynamics codes store positions and velocities in separate arrays and use specialized integrators (Long-Time Integration and Symplectic Methods).
Exercises
Exercise 1: Convert to a system
Write as a first-order system.
Answer
, , .
Solution
With , , , the equation gives .
Exercise 2: Initial conditions
What initial data does the system of exercise 1 need?
Answer
, and .
Solution
One value per first-order equation: .
Exercise 3: A damped oscillator (code)
Solve , , with solve_ivp and compare with the exact solution , .
Answer
They agree to about 9 digits with rtol=1e-10.
Solution
import numpy as np
from scipy.integrate import solve_ivp
sol = solve_ivp(lambda t, u: [u[1], -0.4 * u[1] - 4 * u[0]], (0, 5), [1.0, 0.0], rtol=1e-10, atol=1e-12)
w = np.sqrt(3.96)
exact = np.exp(-1.0) * (np.cos(5 * w) + 0.2 / w * np.sin(5 * w))
print(f"{sol.y[0, -1]:.12f} {exact:.12f}")-0.336851680563 -0.336851680590
Test yourself
A third-order scalar ODE becomes a first-order system of…
- 1 equation
- 2 equations
- 3 equations
- 6 equations
Euler's method for a system is…
- applied to one component at a time with different steps
- not possible
- only for linear systems
In the pendulum, the period for large amplitude is…
- shorter than the small-angle value
- longer than the small-angle value
- the same
- zero