An initial value problem is an ordinary differential equation of the form with , where can be a scalar or a vector.
The idea is that you specify the starting point of a system and the rules that govern the system, and let the simulation go from there.
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sympy as sym
from sympy.solvers import odeYour Zebra Sanctuary¶
Let’s say you are really enthusiastic about zebras.
By Rainbirder - Grevy's Zebra Stallion, CC BY-SA 2.0, Link
You decide to start a zebra sanctuary in your backyard. Soon you have a bunch of zebras having a great time eating your grass and shrubbery.
A Growing Problem¶
Your zebras keep having babies. This is manageable for now, and the baby zebras are cute. However, you’re a bit worried about the number of zebras you’re going to need to feed, and you want to figure out what will happen if you let things go unchecked. Naturally, you decide to write a program to simulate your zebra problem.
Let’s say you have zebras this month. The number of zebra babies that will appear next month is proportional to the current population, so
where . You estimate is about 0.02.
Zebras are not all born on the first day of the month, so it is more natural to let the population change continuously. Over a short time (measured in months), about zebras are born, so . Dividing by and letting gives a differential equation
whose solution is .
Now it is time to fire up your Python interpreter. We’ll use solve_ivp in scipy.integrate - this is a high-level wrapper with lots of options for solving initial value problems. The important arguments to provide are:
f(t, y)- a Python function that returns the right-hand side of the ODE - this can be a vector-valued function. Note thattcomes first; the olderscipy.integrate.odeintexpectsf(y, t), so check the order when you read older code.t_span- a tuple(t0, t1)which gives the start and end times of the simulationy0- the state of the system att0
solve_ivp will do a lot of work for you - deciding on a backend algorithm, choosing time steps, etc. You might find it useful to specify t_eval, which gives an array of points to evaluate the function on.
The result sol has the fields sol.t, the times, and sol.y, the solution, with one row for each component of and one column for each time. That is why we plot sol.y[0] below.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
z0 = np.array([50])
alpha = 0.02
f = lambda t, z : alpha * z
t_span = (0, 100)
t_eval = np.linspace(0,100, 200)
sol = solve_ivp(f, t_span, z0, t_eval=t_eval)
plt.plot(sol.t, sol.y[0], c='k')
plt.title("The Zebra Problem")
plt.ylabel("zebras")
plt.xlabel("months")
plt.show()Things do not look good. There is no way you can afford to feed even 100 zebras while paying tuition at the University of Chicago. Hard choices will need to be made.
A Natural Solution¶
When posting a “Zebras for sale” ad on craigslist, you see an ad for a family of lions that need a home. You feel bad for the lions, and realize you can use them to solve your zebra problem. However, before committing, you want to make sure the lions won’t eat all the zebras (you just want to keep the population controlled, not exterminated). You read a bit about how lions and zebras might interact and decide to use a Predator-Prey model.
Zebras will continue to have babies at rate .
A lion will catch and eat every 100-th zebra it sees. The number of zebras a lion sees depends on the zebra population, we’ll denote the rate at which a lion encounters a single zebra in a month as .
For every 5 zebras the lions eat, a lion baby is born.
Lions die of old age at a rate of
We’ll use to denote the number of lions, and for the number of zebras. Now, the amount the zebra population changes every month is . The amount the lion population changes every month is .
In order to solve this problem, we can use a vector , and the following ODE system:
You estimate to be 0.02, and to be 1.0.
You plan to start with 5 lions and 50 zebras.
z0 = 50
x0 = 5
alpha = 0.02
beta = 1.0
gamma = 0.02
y0 = np.array([x0, z0])
f = lambda t, y : np.array([
-gamma*y[0] + beta/500 * y[0]*y[1],
alpha*y[1] - beta/100 * y[0]*y[1]
] )
t_eval = np.linspace(0, 100, 200)
sol = solve_ivp(f, t_span, y0, t_eval=t_eval)
plt.plot(sol.t, sol.y[1], label="zebras", c='k')
plt.plot(sol.t, sol.y[0], label="lions", c='r')
plt.title("Lions v.s. Zebras")
plt.ylabel("population")
plt.xlabel("months")
plt.legend()
plt.show()Oh no! Soon the zebras will be eaten, and you’ll be left with a pack of hungry lions. You wonder what would happen if you do some landscaping to make it easier for the zebras to hide. Then you might have .
z0 = 50
x0 = 5
alpha = 0.02
beta = 0.3
gamma = 0.02
y0 = np.array([x0, z0])
f = lambda t, y : np.array([
-gamma*y[0] + beta/500 * y[0]*y[1],
alpha*y[1] - beta/100 * y[0]*y[1]
] )
t_eval = np.linspace(0, 100, 200)
sol = solve_ivp(f, t_span, y0, t_eval=t_eval)
plt.plot(sol.t, sol.y[1], label="zebras", c='k')
plt.plot(sol.t, sol.y[0], label="lions", c='r')
plt.title("Lions v.s. Zebras")
plt.ylabel("population")
plt.xlabel("months")
plt.legend()
plt.show()That looks a bit better - what if we run the simulation for longer?
t_eval = np.linspace(0, 1000, 2000)
t_span = (0, 1000)
sol = solve_ivp(f, t_span, y0, t_eval=t_eval)
plt.plot(sol.t, sol.y[1], label="zebras", c='k')
plt.plot(sol.t, sol.y[0], label="lions", c='r')
plt.title("Lions v.s. Zebras")
plt.ylabel("population")
plt.xlabel("months")
plt.legend()
plt.show()This seems like a good solution - you install some hiding places for zebras, and give the lions a home. You start charging interested visitors for tours, and open a gift shop. Soon you are able to cover the expenses for the zebra hay. You quit your day job and become a safari guide in your own backyard.
Symbolic Solutions of ODEs¶
You can use SymPy for symbolic solutions of ODEs. For instance, in our zebra growth problem, we had an ODE of the form
We can use SymPy to classify the ODEs and find a symbolic solution (if one exists)
import sympy as sym
from sympy.solvers import odea, t = sym.symbols('a t') # symbol
y = sym.Function('y') # symbolic function
eqn = y(t).diff(t) - a * y(t) # eqn = 0
eqnode.classify_ode(eqn)You might recognize some of the above from an ODE class. We see that this ODE is fairly simple, and a variety of methods might be used to solve the equation symbolically.
ode.dsolve(eqn, hint='separable') # we solve the differential equation using the hinted methodIf you have taken a class on ODEs, hopefully this looks correct. If you don’t remember your ODEs, or haven’t seen them before, try verifying that the solution satisfies y'(t) = a * y(t). SymPy can also do the check: checkodesol substitutes a solution into the equation, and returns True and the simplified residual 0 if the equation is satisfied.
ode.checkodesol(eqn, ode.dsolve(eqn, hint='separable'))The Logistic Equation¶
Another ODE is the Logistic equation
This models growth of a population with resource limits.
First, let’s use SymPy to find a symbolic solution
t = sym.symbols('t') # symbol
y = sym.Function('y') # symbolic function
eqn = y(t).diff(t) - y(t) * (1 - y(t))
eqnode.classify_ode(eqn)f = ode.dsolve(eqn, hint='separable')
fLet’s just set the constant to be 1
logistic = 1 / (sym.exp(-t) + 1)
sym.plot(logistic)Let’s look at solving the ODE with . We can pass this into SymPy’s ode.dsolve using the ics keyword. Writing 0.1 as the fraction sym.Rational(1, 10) keeps the answer exact:
f = ode.dsolve(eqn, hint='separable', ics={y(0): sym.Rational(1, 10)})
fnow, because we actually solved the IVP, there are no constants to fill in, and we can plot the right hand side of the equation:
sym.plot(f.rhs)Now, let’s solve the IVP numerically using scipy
y0 = np.array([0.1])
f = lambda t, y : y * (1 - y)
t_span = (0, 10)
t_eval = np.linspace(0,10, 200)
sol = solve_ivp(f, t_span, y0, t_eval=t_eval)
plt.plot(sol.t, sol.y[0], c='k')
plt.title("Logistic Function")
plt.ylabel("y")
plt.xlabel("t")
plt.show()Exercises¶
Get an exact expression for the zebra growth IVP using SymPy. What is the worst-case error over the 100-month simulation we conducted?
## Your code here
Euler Method¶
The (forward) Euler Method is a numerical method for solving Initial Value Problems. The basic idea is to choose a step size h, and iteratively compute approximations at the times , starting from the initial value , using
Each step follows the tangent line to the solution through for a time . Equivalently, it replaces in the ODE by the forward difference from Differentiation. For the zebra equation with a step of month, forward Euler is exactly the month-by-month model that we started from.
Here’s an example implementation
def forward_euler(f, y0, t0=0, h=1e-2, n=100):
"""
compute n forward euler steps
returns arrays y and t with n + 1 entries each
"""
y = [y0]
t = [t0]
for k in range(n):
fk = f(t[-1], y[-1])
y.append(y[-1] + h*fk)
t.append(t[-1]+h)
return np.array(y), np.array(t)Let’s use this function to compute the solution to the Logistic equation:
f = lambda t, y : y * (1 - y)
y, t = forward_euler(f, 0.1, h=1e-1, n=100)plt.plot(t, y, c='k')
plt.title("Logistic Function")
plt.ylabel("y")
plt.xlabel("t")
plt.show()How accurate is this? We found the exact solution with SymPy above. Let’s compare it with forward Euler for a few step sizes.
exact = lambda t: 1 / (1 + 9 * np.exp(-t))
for h in [0.5, 0.25, 0.125]:
y, t = forward_euler(f, 0.1, h=h, n=int(5 / h))
plt.plot(t, y, '.-', label=f'h = {h}')
print(f"h = {h}: largest error {np.max(np.abs(y - exact(t))):.4f}")
t = np.linspace(0, 5, 200)
plt.plot(t, exact(t), 'k--', label='exact')
plt.xlabel("t")
plt.ylabel("y")
plt.legend()
plt.show()Halving the step size halves the error, so the error of forward Euler is proportional to , so it is a first order method.
Events¶
You can ask solve_ivp to find the location of events. An event is defined as a function event(t, y), and solve_ivp will find values of t where event(t,y) = 0. For instance, in the zebra growth problem, we might want to find the value of t where the number of zebras reaches 100. We can pass in an event or list of events using the events keyword.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
z0 = np.array([50])
alpha = 0.02
f = lambda t, z : alpha * z
t_span = (0, 100)
t_eval = np.linspace(0,100, 200)
def zebra100(t, y):
return y[0] - 100
sol = solve_ivp(f, t_span, z0, t_eval=t_eval, events=zebra100)
plt.plot(sol.t, sol.y[0], c='k')
plt.title("The Zebra Problem")
plt.ylabel("zebras")
plt.xlabel("months")
plt.show()we can access the time at which events occur using the t_events field of the solution
sol.t_eventsThe population reaches 100 when it has doubled, at months. solve_ivp finds events by checking the sign of zebra100 after every step. When the sign changes, it locates the root inside the step with a root finder (see Root Finding), applied to an interpolating polynomial of the numerical solution.
print("exact :", np.log(2) / alpha)
print("rtol = 1e-3 :", sol.t_events[0][0])
sol_tight = solve_ivp(f, t_span, z0, events=zebra100, rtol=1e-10, atol=1e-10)
print("rtol = 1e-10:", sol_tight.t_events[0][0])If you want to end the simulation when an event occurs, you can set a flag terminal=True. You can also specify a direction flag to only trigger an event when the root of the function goes from negative to positive (direction=1), or positive to negative (direction=-1)
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
z0 = np.array([50])
alpha = 0.02
f = lambda t, z : alpha * z
t_span = (0, 100)
t_eval = np.linspace(0,100, 200)
def zebra100(t, y):
return y[0] - 100
zebra100.terminal=True # we can set this a flag on the function object
zebra100.direction=1
sol = solve_ivp(f, t_span, z0, t_eval=t_eval, events=zebra100)
plt.plot(sol.t, sol.y[0], c='k')
plt.title("The Zebra Problem")
plt.ylabel("zebras")
plt.xlabel("months")
plt.show()sol.t_eventsHigher-Order Equations¶
solve_ivp solves first-order systems . An equation with higher derivatives can always be rewritten as a first-order system, by making the lower derivatives into new unknowns. For example, the angle of a pendulum of length satisfies
With the angular velocity as a second unknown, this becomes the system
for . The initial condition has to give both the starting angle and the starting angular velocity . In general, an equation of order becomes a system of first-order equations for .
Let’s release the pendulum from rest at a few different angles.
g, L = 9.81, 1.0 # gravitational acceleration (m/s^2) and length (m)
def pendulum(t, y):
theta, omega = y
return [omega, -g / L * np.sin(theta)]
t_eval = np.linspace(0, 10, 1000)
fig, axs = plt.subplots(2, 2 , figsize=(8, 8))
axs = axs.flatten()
for i, theta0 in enumerate([0.1, 1.0, 2.0, 3.0]):
sol = solve_ivp(pendulum, (0, 10), [theta0, 0.0], t_eval=t_eval, rtol=1e-8, atol=1e-8)
axs[i].plot(sol.t, sol.y[0], label=rf'$\theta(0) = {theta0}$')
axs[i].set_title(rf'$\theta(0) = {theta0}$')
#axs[i].legend(loc='center left', bbox_to_anchor=(1, 0.5))
#plt.show()For small angles , and the equation becomes the harmonic oscillator , whose period seconds does not depend on the amplitude. Larger swings take longer. We can measure the period with an event: the pendulum passes through in the same direction once per period.
The exact period is an integral,
(a complete elliptic integral of the first kind), which we can compute numerically with quad from Integration & Quadrature.
from scipy.integrate import quad
def lowest_point(t, y):
return y[0] # theta = 0
lowest_point.direction = -1 # only count crossings where theta is decreasing
for theta0 in [0.1, 1.0, 2.0, 3.0]:
sol = solve_ivp(pendulum, (0, 20), [theta0, 0.0], events=lowest_point, rtol=1e-10, atol=1e-10)
period = np.mean(np.diff(sol.t_events[0]))
k = np.sin(theta0 / 2)
K = quad(lambda phi: 1 / np.sqrt(1 - k**2 * np.sin(phi)**2), 0, np.pi / 2)[0]
print(f"theta(0) = {theta0}: period {period:.6f} s from the events, "
f"{4 * np.sqrt(L / g) * K:.6f} s from the integral")
print(f"small-angle period: {2 * np.pi * np.sqrt(L / g):.6f} s")Exercises¶
Write the damped oscillator as a first-order system, and solve it with , for , 1 and 2. Compare with the exact solutions from SymPy’s
dsolve.The energy of the pendulum is constant in time. Solve the pendulum equation with and for 100 seconds with the default tolerances, and plot . What happens when you decrease
rtol?
# Your code hereLorenz attractor and chaos¶
In 1963 Edward Lorenz derived a simplified model of convection in the atmosphere, a system of three ODEs, and found that its solutions oscillate without ever settling into a repeating pattern.
We use the parameter values from Lorenz’s paper, , and , which are also the defaults in the function below. The args keyword of solve_ivp passes extra arguments to the right-hand side after t and y, which is how we pass the parameters below.
def lorenz(t, xyz, p=10., r=28., b=8./3):
"""Lorenz equation"""
x, y, z = xyz
dxdt = p*(y - x)
dydt = -x*z + r*x - y
dzdt = x*y - b*z
return np.array([dxdt, dydt, dzdt])y0 = np.array([1, 0, 0])
t_span = (0, 50)
t_eval = np.linspace(0, 50, 5000)
sol = solve_ivp(lorenz, t_span, y0, t_eval=t_eval, args=(10., 28., 8./3))
plt.plot(sol.t, sol.y[0], lw=1);
plt.plot(sol.t, sol.y[1], lw=1);
plt.plot(sol.t, sol.y[2], lw=1);
plt.xlabel('t'); plt.ylabel('x,y,z'); plt.legend(('x','y','z'));# Plot in 3D
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(projection='3d')
ax.plot(sol.y[0], sol.y[1], sol.y[2], lw=1)
plt.xlabel('x')
plt.ylabel('y')
ax.set_zlabel('z')Now let’s compute a second solution whose initial is shifted by 10-8. We compute both solutions with a high-order method and tight tolerances, so that the difference between them is caused by the shift and not by numerical error (more on this below).
tight = dict(method='DOP853', rtol=1e-12, atol=1e-12) # a high-order method with tight tolerances
sol = solve_ivp(lorenz, t_span, y0, t_eval=t_eval, args=(10., 28., 8./3), **tight)
sol_2 = solve_ivp(lorenz, t_span, y0 + np.array([1e-8, 0, 0]), t_eval=t_eval, args=(10., 28., 8./3), **tight)
dist = np.linalg.norm(sol_2.y - sol.y, axis=0)
plt.semilogy(t_eval, dist, lw=1, label='$x(0)$ shifted by $10^{-8}$')
plt.xlabel('t')
plt.ylabel('distance between solutions')
plt.show()
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(projection='3d')
ax.plot(sol.y[0], sol.y[1], sol.y[2], lw=0.5)
ax.plot(sol_2.y[0], sol_2.y[1], sol_2.y[2], lw=0.5)
plt.xlabel('x')
plt.ylabel('y')
ax.set_zlabel('z')
ax.set_title('Two solutions, 1e-8 apart')How long can we trust the computed solution?¶
The first solution above was computed with the default tolerances rtol=1e-3 and
atol=1e-6. The numerical error made in each step is also a small perturbation, and in a
chaotic system it grows just like the 10-8 shift. To see how far the computed solution
can be trusted, we compare it with a reference solution computed with much tighter tolerances.
# reference solution: a high-order method with tight tolerances
ref = solve_ivp(lorenz, t_span, y0, t_eval=t_eval, args=(10., 28., 8./3),
method='DOP853', rtol=1e-12, atol=1e-12)
for rtol in [1e-3, 1e-6, 1e-9]:
s = solve_ivp(lorenz, t_span, y0, t_eval=t_eval, args=(10., 28., 8./3),
rtol=rtol, atol=1e-3 * rtol)
err = np.linalg.norm(s.y - ref.y, axis=0)
plt.semilogy(t_eval, err, lw=1, label=f'rtol = {rtol:.0e}')
print(f"rtol = {rtol:.0e}: error first exceeds 1 at t = {t_eval[np.argmax(err > 1)]:.1f}")
plt.xlabel('t')
plt.ylabel('distance from the reference solution')
plt.legend()
plt.show()Conclusion¶
The Lorenz solution never settles into a steady state or a periodic orbit. It loops around one lobe, then the other, switching at irregular times, but it stays on a bounded, butterfly-shaped set called the Lorenz attractor. The plots of the two nearby solutions show the defining feature of chaos, or sensitive dependence on initial conditions: two solutions that start 10-8 apart separate roughly exponentially. Numerical errors grow the same way, which is why tightening the tolerance extends the reliable part of a computed solution only slowly.
The same holds for the weather, which is what Lorenz was modeling. Small errors in the measurements of today’s weather grow exponentially, so beyond a horizon of a couple of weeks the weather cannot be forecast in detail, however good the model.