import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivpNumerical calculus quick-start
MCSB Bootcamp — Mathematical and Computational Track
The coffee bean model
A jar holds N scoops of coffee. Each day you drink one scoop’s worth and top the jar back up with decaf, so the fraction of the jar that is still caffeinated shrinks by a factor of every day.
N = 10 # number of scoops in each jar
n_max = 2 * N # max number of days to simulate
x = np.zeros(n_max) # fraction caffeinated
x[0] = 1.0 # initial fraction caffeinated
for n in range(1, n_max):
x[n] = (1 - 1 / N) * x[n - 1]
# finished loop through days
days = np.arange(1, n_max + 1)
fig, ax = plt.subplots()
ax.plot(days, x, "-ok")
ax.set_ylabel("Fraction caffeinated")
ax.set_xlabel("Days")
plt.show()The differential equation
There are two ways to think about a differential equation. One is as a relationship between the derivatives of and the function itself. A population of E. coli in a large petri dish:
A charged biomolecule flying through a mass spectrometer:
Any function either satisfies the differential equation or it does not. Sometimes it is hard to guess the solution.
One differential equation often has many solutions.
A differential equation involving a function of one variable, e.g. time , is called an ordinary differential equation (ODE).
The set of models ,
The second way of thinking about a differential equation is as a rule that tells you, given the state of a system at time , how it is going to change.
In this case, for the model to make a prediction, we need to state an initial condition. The combination of differential equation and initial condition is called an initial value problem or ivp.
A gene produces protein at a constant rate (copies per hour). The proteins are removed at a per-molecule rate (1/hrs).
# dP/dt = a - b*PIf the protein promotes its own expression, then one model of this is:
# dP/dt = (a_0 + a_1*P) - b*PIf the protein promotes its own degradation, then one model of this is:
# dP/dt = a - (b_0 + b_1*P)*PQuestion: why did the modeller choose to put an asymmetry between production (constant) and removal (linear)?
Numerical ODEs
Euler method, and more complicated methods
Thinking about an ODE as a rule that states how a system will change, there is an obvious way to simulate numerical solutions: pick a small and step forward just as you would for a discrete-time system. This is the Forward Euler method.
dt = 0.01 # time step
a_0 = 500 # molecules per hour
a_1 = 1 # molecules per hour, per existing molecule of A
b = 4 # 1/hrs
nt_max = 200
P = np.zeros(nt_max + 1)
t_array = np.linspace(0, nt_max * dt, nt_max + 1)
P[0] = 0 # initial condition
for nt in range(nt_max):
dPdt = (a_0 + a_1 * P[nt]) - b * P[nt] # "dPdt" is a convenient shorthand for "dP/dt"
P[nt + 1] = P[nt] + dPdt * dt
# finished loop through time
# plot it
fig, ax = plt.subplots()
ax.plot(t_array, P)
ax.set_ylabel("Molecules of protein A")
ax.set_xlabel("Time (hours)")
plt.show()Solving an ODE with a library solver
def rhs(t, P):
"""The model, in the form solve_ivp asks for: given the time and the protein level P, how fast is P changing? This model does not depend on t."""
return (a_0 + a_1 * P) - b * P
sol = solve_ivp(rhs, [0, 2.0], [0.0], t_eval=np.linspace(0, 2.0, 1000))
T = sol.t
P = sol.y[0]
fig, ax = plt.subplots()
ax.plot(T, P)
ax.set_ylabel("Molecules of protein A")
ax.set_xlabel("Time (hours)")
plt.show()Let’s explore the solution for different values of .
fig, ax = plt.subplots()
for a_1 in [0, 0.1, 0.5, 1, 3, 5, 7, 10]:
# t_eval asks the solver for the solution on a fine grid rather than only at the steps it chose for itself, so each curve is drawn smooth rather than as a handful of straight segments.
sol = solve_ivp(rhs, [0, 2.0], [0.0], t_eval=np.linspace(0, 2.0, 1000))
ax.plot(sol.t, sol.y[0], label=f"$a_1 = {a_1}$")
ax.set_ylim(0, 1000)
ax.set_ylabel("Molecules of protein A")
ax.set_xlabel("Time (hours)")
ax.legend(fontsize="small")
plt.show()Analytical examples
Linear ODEs that look like
have solutions
where the single constant is fixed by the initial condition — one first-order equation, one arbitrary constant. If , exponential growth; if , exponential decay.
Now take
whose solution is
It reaches infinity at , which is called finite time blow-up. Ask a numerical solver to integrate to and it cannot get there.
def quadratic_rhs(t, x):
return x**2
sol = solve_ivp(quadratic_rhs, [0, 6.0], [0.2])
print(sol.success)
print(sol.message)
print(f"got as far as t = {sol.t[-1]:.4f}, where x = {sol.y[0, -1]:.3e}")False
Required step size is less than spacing between numbers.
got as far as t = 4.9999, where x = 1.023e+14
Multivariate differential equations
If there are multiple quantities to track — multiple molecules, or multiple species — then an ODE model may be a system of coupled ODEs:
Here is gene expression where the protein is an activator: is RNA, is protein.
def dxdt(t, state):
"""du/dt and dw/dt for the RNA-protein system, given the state [u, w]."""
u, w = state
du_dt = -10 * u + 6 * w + 0.1
dw_dt = -2 * w + 1.9 * u
return [du_dt, dw_dt]
sol = solve_ivp(dxdt, [0, 24], [0.0, 0.0], t_eval=np.linspace(0, 24, 1000))
T = sol.t
rna, protein = sol.y
fig, ax = plt.subplots()
ax.plot(T, rna, "-r")
ax.plot(T, protein, "-", color=[0.5, 0, 1])
ax.set_ylabel("Molecular concentration (micromolar)")
ax.set_xlabel("Time (hours)")
plt.show()Notes:
solve_ivphands your function the whole state as one array and expects the whole set of derivatives back as one list. It then gets unpacked withu, w = stateon the first line. This lets the two equations below be easier to read.solve_ivpreturnssol.ywith one row per variable, so unpacking it withrna, protein = sol.ygives one array per variable, the same wayu, w = statedoes inside the function.