5 Introduction to dynamic modelling
A dynamic model describes how the levels of molecules, such as metabolites, mRNAs or proteins, change over time. Most such models are systems of ordinary differential equations (ODEs),
\[ \frac{dx_i}{dt} = f_i(x_1, x_2, \ldots, x_n;\ \Theta), \qquad i = 1, 2, \ldots, n, \]
where \(x_i\) is the concentration of species \(i\), \(f_i\) is its rate law, and \(\Theta\) is the set of parameters, such as rate constants. In this chapter, we cover the two halves of working with such models: writing the equations down, and solving them numerically, including what can go wrong. Along the way, we shall see how power laws can stand in for rate laws (biochemical systems theory), and how an ensemble of models helps us judge which predictions to trust. At the end of the chapter, in §5.A, we go beyond the book, to stochastic simulation.
5.1 Constructing dynamic models
5.1.1 Modelling a generic biochemical system
There is no code for this section; see the book.
5.2 Mass-action kinetic models
There is no code for this section; see the book.
5.3 Modelling enzyme kinetics
5.3.1 The Michaelis–Menten model
For an enzyme \(E\) converting a substrate \(S\) into a product \(P\) through a complex \(ES\),
\[ E + S \underset{k_{-1}}{\overset{k_1}{\rightleftharpoons}} ES \xrightarrow{k_2} E + P , \]
mass-action kinetics gives one ODE per species, with \([E] = E_0 - [ES]\) because the total amount of enzyme is fixed (book, Eqs. 5.4 and 5.6). Assuming in addition that \([ES]\) changes slowly compared to \([S]\) (the quasi-steady-state approximation of Briggs and Haldane) collapses all of this into the familiar Michaelis–Menten rate law (book, Eqs. 5.12 and 5.13)
\[ v = \frac{v_\text{max}[S]}{K_M + [S]}, \qquad v_\text{max} = k_2 E_0, \qquad K_M = \frac{k_{-1} + k_2}{k_1}. \]
The rate law is so widely used that it is easy to forget it is an approximation. Let us solve both models, for a small and a large amount of enzyme, with \(K_M = 2\) mM and \(S_0 = 10\) mM.
Core MATLAB only.
%% Full mass-action enzyme model vs the Michaelis-Menten rate law
% E + S <-> ES -> E + P (rate constants k1, k_1, k2)
% The full model tracks S, ES and P; the enzyme is E = E0 - ES. The
% Michaelis-Menten (Briggs-Haldane) approximation replaces all of this
% with a single rate law, v = vmax*S/(KM + S). How good is it?
% Requires: core MATLAB only.
k1 = 1.0; k_1 = 1.0; k2 = 1.0; % 1/(mM s), 1/s, 1/s
KM = (k_1 + k2) / k1; % Michaelis constant: 2 mM
S0 = 10.0; % initial substrate (mM)
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10); % tight tolerances
% Two cases: little enzyme (E0 << S0) and a lot of enzyme (E0 ~ S0)
names = {'low_enzyme', 'high_enzyme'};
E0s = [0.1 5.0];
t_ends = [150 6];
fig = figure('Position', [100 100 1000 400]);
for k = 1:2
E0 = E0s(k);
t = linspace(0, t_ends(k), 51);
% Full model: y = [S; ES; P]
full_model = @(t, y) [-k1*(E0 - y(2))*y(1) + k_1*y(2)
k1*(E0 - y(2))*y(1) - (k_1 + k2)*y(2)
k2*y(2)];
[~, y] = ode45(full_model, t, [S0; 0; 0], opts);
P_full = y(:, 3)';
% Michaelis-Menten model: a single ODE for S
vmax = k2 * E0;
mm_model = @(t, S) -vmax * S / (KM + S);
[~, S] = ode45(mm_model, t, S0, opts);
P_mm = S0 - S'; % in the MM model, P = S0 - S
err = max(abs(P_full - P_mm)) / S0;
fprintf('E0 = %g mM: max |P_full - P_MM| = %.1f%% of S0\n', E0, 100*err);
results.(names{k}) = struct('E0', E0, 't', t, 'P_full', P_full, ...
'P_mm', P_mm, 'max_rel_difference', err);
subplot(1, 2, k)
plot(t, P_full, '-', 'Color', [0.000 0.447 0.698], 'LineWidth', 2);
hold on
plot(t, P_mm, '--', 'Color', [0.902 0.624 0.000], 'LineWidth', 2);
xlabel('Time (s)'); ylabel('Product P (mM)');
title(sprintf('E_0 = %g mM, S_0 = %g mM', E0, S0));
legend({'full mass action', 'Michaelis–Menten'}, ...
'Location', 'southeast', 'Box', 'off');
box off
end
sbp.save_figure(fig, mfilename('fullpath'), 'fig-michaelis-menten');
sbp.save_results(mfilename('fullpath'), results);
Needs SciPy.
"""Full mass-action enzyme model vs the Michaelis-Menten rate law.
E + S <-> ES -> E + P (rate constants k1, k_1, k2)
The full model tracks S, ES and P; the enzyme is E = E0 - ES. The
Michaelis-Menten (Briggs-Haldane) approximation replaces all of this
with a single rate law, v = vmax*S/(KM + S). How good is it?
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
k1, k_1, k2 = 1.0, 1.0, 1.0 # 1/(mM s), 1/s, 1/s
KM = (k_1 + k2) / k1 # Michaelis constant: 2 mM
S0 = 10.0 # initial substrate (mM)
tol = dict(rtol=1e-8, atol=1e-10) # tight tolerances for both solvers
def full_model(t, y, E0):
"""Mass-action ODEs for S, ES and P (book Eqs. 5.4a–d)."""
S, ES, P = y
E = E0 - ES # enzyme conservation (Eq. 5.6)
return [-k1 * E * S + k_1 * ES,
k1 * E * S - (k_1 + k2) * ES,
k2 * ES]
def mm_model(t, y, E0):
"""A single ODE for S, with the Michaelis-Menten rate law."""
S = y[0]
vmax = k2 * E0
return [-vmax * S / (KM + S)]
def simulate(E0, t_end):
t = np.linspace(0, t_end, 51)
full = solve_ivp(full_model, [0, t_end], [S0, 0, 0], t_eval=t,
args=(E0,), **tol)
mm = solve_ivp(mm_model, [0, t_end], [S0], t_eval=t, args=(E0,), **tol)
P_full = full.y[2]
P_mm = S0 - mm.y[0] # in the MM model, P = S0 - S
return t, P_full, P_mm
# Two cases: little enzyme (E0 << S0) and a lot of enzyme (E0 ~ S0)
cases = {"low_enzyme": (0.1, 150), "high_enzyme": (5.0, 6)} # E0, t_end
results = {}
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, (name, (E0, t_end)) in zip(axes, cases.items()):
t, P_full, P_mm = simulate(E0, t_end)
err = np.abs(P_full - P_mm).max() / S0
print(f"E0 = {E0} mM: max |P_full - P_MM| = {100 * err:.1f}% of S0")
results[name] = {"E0": E0, "t": t, "P_full": P_full, "P_mm": P_mm,
"max_rel_difference": err}
ax.plot(t, P_full, "-", color="#0072B2", lw=2, label="full mass action")
ax.plot(t, P_mm, "--", color="#E69F00", lw=2, label="Michaelis–Menten")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Product P (mM)")
ax.set_title(f"$E_0$ = {E0:g} mM, $S_0$ = {S0:g} mM")
ax.legend(frameon=False, loc="lower right")
sbp.save_figure(fig, __file__, "fig-michaelis-menten")
sbp.save_results(__file__, results)
sbp.show()
With little enzyme, the two models are indistinguishable: they never differ by more than 0.3% of \(S_0\). With a lot of enzyme, the Michaelis–Menten model runs ahead of the full model by up to 14% of \(S_0\). The reason is that a substantial share of the substrate is held in the complex \(ES\), which the rate law ignores. A useful rule of thumb is that the approximation is good when \(E_0 / (S_0 + K_M) \ll 1\) (Segel and Slemrod 1989); here that ratio is 0.008 in the first case and 0.42 in the second. Know thy assumptions!
5.3.2 Co-operativity: Hill kinetics
There is no separate example for this section; in Exercise 5, we replace the Michaelis–Menten rate law of the example above with a Hill rate law and compare the time courses.
5.3.3 An illustrative example: a three-node oscillator
There is no separate example for this section; Exercise 7 invites you to simulate this oscillator yourself.
5.4 Generalised rate equations
5.4.1 Biochemical systems theory
Where do the kinetic orders of an S-system come from? One answer is that they are elasticities: around a steady state, any rate law \(v(X)\) can be approximated by a power law \(\gamma X^f\), with \(f = \partial \ln v / \partial \ln X\), a first-order Taylor expansion in logarithms. Let us build the S-system for a small pathway with end-product inhibition, \(X_1 \rightarrow X_2 \rightarrow\), in which \(X_2\) inhibits the supply of \(X_1\), and compare it with the original model when the supply increases.
Core MATLAB only.
%% Biochemical systems theory: an S-system approximation of a pathway
% A two-step pathway with feedback inhibition, written with familiar rate
% laws (book §5.3):
% v1 = V1 / (1 + (X2/Ki)^h) (supply, inhibited by the end product)
% v2 = V2 X1 / (K2 + X1) (conversion of X1 to X2)
% v3 = V3 X2 / (K3 + X2) (demand for X2)
% dX1/dt = v1 - v2, dX2/dt = v2 - v3.
% In the S-system form of BST (book Eq. 5.21), each rate is replaced by a
% power law, v ~ gamma X^f, whose kinetic order f is the elasticity
% d ln v / d ln X at the steady state, and gamma matches the rate there:
% dX1/dt = a1 X2^g12 - b1 X1^h11, dX2/dt = a2 X1^g21 - b2 X2^h22.
% We compare the two models when the supply V1 is raised by 10%, 50% and
% 200%. Note that the steady state of an S-system can be found with linear
% algebra, since in logarithms its steady-state equations are linear.
p.V1 = 2.0; p.Ki = 1.0; p.h = 2.0;
p.V2 = 3.0; p.K2 = 1.0;
p.V3 = 2.5; p.K3 = 1.0;
xs = steady_state(p, p.V1);
x1s = xs(1); x2s = xs(2);
v = rates(p, x1s, x2s, p.V1);
flux = v(3);
% Kinetic orders: elasticities at the steady state
g12 = -p.h * (x2s / p.Ki) ^ p.h / (1 + (x2s / p.Ki) ^ p.h);
h11 = p.K2 / (p.K2 + x1s); g21 = h11;
h22 = p.K3 / (p.K3 + x2s);
% Rate constants: each power law equals the flux at the steady state
a1 = flux / x2s ^ g12;
b1 = flux / x1s ^ h11; a2 = b1;
b2 = flux / x2s ^ h22;
fprintf('Steady state: X1 = %.4f, X2 = %.4f, flux = %.4f\n', x1s, x2s, flux);
fprintf('Kinetic orders: g12 = %.3f, h11 = g21 = %.3f, h22 = %.3f\n', ...
g12, h11, h22);
bst_model = @(t, x, f) [f * a1 * x(2) ^ g12 - b1 * x(1) ^ h11;
a2 * x(1) ^ g21 - b2 * x(2) ^ h22];
factors = [1.1, 1.5, 3.0];
t = linspace(0, 10, 201);
results.steady_state = [x1s, x2s];
results.kinetic_orders = [g12, h11, h22];
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-12);
fig = figure('Position', [100 100 1200 360]);
tiledlayout(1, 3, 'TileSpacing', 'compact');
colours = {[0.000 0.447 0.698], [0.835 0.369 0.000]};
for k = 1:numel(factors)
f = factors(k);
[~, full] = ode45(@(t, x) full_model(p, x, f * p.V1), t, ...
[x1s; x2s], opts);
[~, approx] = ode45(@(t, x) bst_model(t, x, f), t, [x1s; x2s], ...
opts);
exact_ss = steady_state(p, f * p.V1);
% S-system steady state, in logs: g12 y2 - h11 y1 = ln(b1 / (f a1)),
% and g21 y1 - h22 y2 = ln(b2 / a2), with y = ln X
bst_ss = exp([-h11, g12; g21, -h22] ...
\ [log(b1 / (f * a1)); log(b2 / a2)])';
key = sprintf('supply_up_%d', round(100 * (f - 1)));
results.(key) = struct('full', exact_ss, 's_system', bst_ss, ...
'error_percent', 100 * (bst_ss ./ exact_ss - 1));
fprintf(['Supply x%g: new steady state, full model ' ...
'X1 = %.4f, X2 = %.4f; S-system X1 = %.4f, X2 = %.4f\n'], ...
f, exact_ss, bst_ss);
ax(k) = nexttile; hold on
for i = 1:2
plot(t, full(:, i), 'Color', colours{i}, ...
'DisplayName', sprintf('X%d, full model', i));
plot(t, approx(:, i), '--', 'Color', colours{i}, ...
'DisplayName', sprintf('X%d, S-system', i));
end
title(sprintf('Supply raised %d%%', round(100 * (f - 1))));
xlabel('Time'); box off
if k == 1
ylabel('Concentration');
legend('Box', 'off', 'FontSize', 8, 'Location', 'northeast');
else
yticklabels({});
end
end
linkaxes(ax, 'y');
sbp.save_figure(fig, mfilename('fullpath'), 'fig-s-system');
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function v = rates(p, x1, x2, v1max)
v = [v1max / (1 + (x2 / p.Ki) ^ p.h), p.V2 * x1 / (p.K2 + x1), ...
p.V3 * x2 / (p.K3 + x2)];
end
function dx = full_model(p, x, v1max)
v = rates(p, x(1), x(2), v1max);
dx = [v(1) - v(2); v(2) - v(3)];
end
function xs = steady_state(p, v1max)
% v1 = v3 fixes X2; then v2 = v3 fixes X1.
g = @(x) v1max / (1 + (x / p.Ki) ^ p.h) - p.V3 * x / (p.K3 + x);
x2 = fzero(g, [1e-9, 100], optimset('TolX', 1e-14));
flux = p.V3 * x2 / (p.K3 + x2);
xs = [flux * p.K2 / (p.V2 - flux), x2];
end
Needs SciPy.
"""Biochemical systems theory: an S-system approximation of a pathway.
A two-step pathway with feedback inhibition, written with familiar rate
laws (book §5.3):
v1 = V1 / (1 + (X2/Ki)^h) (supply, inhibited by the end product)
v2 = V2 X1 / (K2 + X1) (conversion of X1 to X2)
v3 = V3 X2 / (K3 + X2) (demand for X2)
dX1/dt = v1 - v2, dX2/dt = v2 - v3.
In the S-system form of BST (book Eq. 5.21), each rate is replaced by a
power law, v ~ gamma X^f, whose kinetic order f is the elasticity
d ln v / d ln X at the steady state, and gamma matches the rate there:
dX1/dt = a1 X2^g12 - b1 X1^h11, dX2/dt = a2 X1^g21 - b2 X2^h22.
We compare the two models when the supply V1 is raised by 10%, 50% and
200%. Note that the steady state of an S-system can be found with linear
algebra, since in logarithms its steady-state equations are linear.
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import matplotlib.pyplot as plt
import sbp
V1, Ki, h = 2.0, 1.0, 2.0
V2, K2 = 3.0, 1.0
V3, K3 = 2.5, 1.0
def rates(x1, x2, v1max=V1):
return (v1max / (1 + (x2 / Ki) ** h), V2 * x1 / (K2 + x1),
V3 * x2 / (K3 + x2))
def steady_state(v1max=V1):
"""v1 = v3 fixes X2; then v2 = v3 fixes X1."""
x2 = brentq(lambda x: rates(1, x, v1max)[0] - rates(1, x)[2], 1e-9, 100,
xtol=1e-14)
flux = rates(1, x2)[2]
x1 = flux * K2 / (V2 - flux) # v2(x1) = flux
return np.array([x1, x2])
x1s, x2s = steady_state()
flux = rates(x1s, x2s)[2]
# Kinetic orders: elasticities at the steady state
g12 = -h * (x2s / Ki) ** h / (1 + (x2s / Ki) ** h)
h11 = g21 = K2 / (K2 + x1s)
h22 = K3 / (K3 + x2s)
# Rate constants: each power law equals the flux at the steady state
a1 = flux / x2s ** g12
b1 = a2 = flux / x1s ** h11
b2 = flux / x2s ** h22
print(f"Steady state: X1 = {x1s:.4f}, X2 = {x2s:.4f}, flux = {flux:.4f}")
print(f"Kinetic orders: g12 = {g12:.3f}, h11 = g21 = {h11:.3f}, "
f"h22 = {h22:.3f}")
def full_model(t, x, v1max):
v1, v2, v3 = rates(x[0], x[1], v1max)
return [v1 - v2, v2 - v3]
def bst_model(t, x, factor):
return [factor * a1 * x[1] ** g12 - b1 * x[0] ** h11,
a2 * x[0] ** g21 - b2 * x[1] ** h22]
def s_steady_state(factor):
"""In logs: g12 y2 - h11 y1 = ln(b1 / (factor a1)), and
g21 y1 - h22 y2 = ln(b2 / a2), with y = ln X."""
M = np.array([[-h11, g12], [g21, -h22]])
rhs = np.array([np.log(b1 / (factor * a1)), np.log(b2 / a2)])
return np.exp(np.linalg.solve(M, rhs))
factors = [1.1, 1.5, 3.0]
t = np.linspace(0, 10, 201)
results = {"steady_state": [x1s, x2s], "kinetic_orders": [g12, h11, h22]}
sbp.style()
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6), sharey=True)
for ax, f in zip(axes, factors):
full = solve_ivp(full_model, [0, 10], [x1s, x2s], t_eval=t,
args=(f * V1,), rtol=1e-10, atol=1e-12).y
approx = solve_ivp(bst_model, [0, 10], [x1s, x2s], t_eval=t,
args=(f,), rtol=1e-10, atol=1e-12).y
exact_ss, bst_ss = steady_state(f * V1), s_steady_state(f)
results[f"supply_up_{round(100 * (f - 1))}"] = {
"full": exact_ss, "s_system": bst_ss,
"error_percent": 100 * (bst_ss / exact_ss - 1)}
print(f"Supply x{f}: new steady state, full model "
f"X1 = {exact_ss[0]:.4f},"
f" X2 = {exact_ss[1]:.4f}; S-system X1 = {bst_ss[0]:.4f}, "
f"X2 = {bst_ss[1]:.4f}")
for i, (name, colour) in enumerate((("X1", "#0072B2"),
("X2", "#D55E00"))):
ax.plot(t, full[i], color=colour, label=f"{name}, full model")
ax.plot(t, approx[i], "--", color=colour,
label=f"{name}, S-system")
ax.set_title(f"Supply raised {round(100 * (f - 1))}%")
ax.set_xlabel("Time")
axes[0].set_ylabel("Concentration")
axes[0].legend(frameon=False, fontsize=8, loc="upper right")
sbp.save_figure(fig, __file__, "fig-s-system")
sbp.save_results(__file__, results)
sbp.show()
Note that the kinetic order of the supply with respect to \(X_2\) is negative (\(g_{12} = -0.85\)), as it must be for an inhibitor. For a 10% increase in supply, the S-system and the original model are practically indistinguishable (they differ by 0.1%); for a 50% increase, by 2%; and when the supply triples, by 14%. The power-law approximation is excellent close to the operating point, and degrades gracefully away from it. A great advantage of the S-system form is that its steady states can be found by linear algebra, since the steady-state equations are linear in \(\ln X\); this makes S-systems especially convenient for analysis and design (Savageau 1976; Voit 2000).
5.5 Solving ODEs
Few ODE models can be solved on paper, so we solve them numerically. The simplest method, due to Euler, replaces the derivative by a finite difference over a small time step \(\Delta t\):
\[ x(t + \Delta t) \approx x(t) + f\big(x(t)\big)\,\Delta t . \]
Starting from the initial value \(x_0\), we step forward in time, one \(\Delta t\) at a time. This is the forward (or explicit) Euler method (book, Eqs. 5.23 and 5.24). The backward (or implicit) Euler method evaluates \(f\) at the end of the step instead, \(x(t + \Delta t) = x(t) + f\big(x(t + \Delta t)\big)\,\Delta t\), which must be solved for \(x(t + \Delta t)\) at every step (book, Eqs. 5.25 and 5.26).
We try both on an ODE with a known answer,
\[ \frac{dx}{dt} = a - bx, \qquad x(0) = c, \qquad x(t) = \frac{a}{b} - \left(\frac{a}{b} - c\right) e^{-bt}, \]
with \(a = 20\), \(b = 2\) and \(c = 5\), so \(x\) rises from 5 towards its steady state \(a/b = 10\).
Core MATLAB only.
%% Solving dx/dt = a - b*x with the forward and backward Euler methods
% This simple ODE has an exact solution, so we can see how the step size
% dt affects accuracy and, for forward Euler, stability.
% Requires: core MATLAB only.
a = 20; b = 2; c = 5; % dx/dt = a - b*x, x(0) = c
t_end = 4;
exact = @(t) a/b - (a/b - c) * exp(-b*t);
%% Forward Euler with different step sizes
steps = [0.05 0.25 0.9 1.1];
max_error = zeros(size(steps));
for k = 1:numel(steps)
[t, x] = forward_euler(a, b, c, t_end, steps(k));
max_error(k) = max(abs(x - exact(t)));
fprintf('forward Euler, dt = %4g: max error = %.4g\n', ...
steps(k), max_error(k));
end
fprintf('Forward Euler is stable only for dt < 2/b = %g\n', 2/b);
%% Forward vs backward Euler at a step size beyond the stability limit
[t_f, x_f] = forward_euler(a, b, c, t_end, 1.1);
[t_b, x_b] = backward_euler(a, b, c, t_end, 1.1);
%% Plot
colors = [0.000 0.447 0.698; 0.000 0.620 0.451;
0.902 0.624 0.000; 0.835 0.369 0.000];
t_fine = linspace(0, 4.4, 441);
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
plot(t_fine, exact(t_fine), 'k-', 'LineWidth', 2);
hold on
for k = 1:3 % dt = 1.1 is in the right panel
[t, x] = forward_euler(a, b, c, t_end, steps(k));
plot(t, x, 'o-', 'Color', colors(k, :), 'MarkerSize', 4, ...
'MarkerFaceColor', colors(k, :));
end
ylim([0 20]);
xlabel('t'); ylabel('x(t)'); title('Forward Euler');
legend(['exact', compose('\\Deltat = %g', steps(1:3))], ...
'Location', 'northeast', 'Box', 'off');
box off
subplot(1, 2, 2)
plot(t_fine, exact(t_fine), 'k-', 'LineWidth', 2);
hold on
plot(t_f, x_f, 'o-', 'Color', colors(4, :), 'MarkerSize', 4, ...
'MarkerFaceColor', colors(4, :));
plot(t_b, x_b, 's-', 'Color', colors(1, :), 'MarkerSize', 4, ...
'MarkerFaceColor', colors(1, :));
ylim([-2 25]);
xlabel('t'); title('Forward vs backward Euler');
legend({'exact', 'forward, \Deltat = 1.1', 'backward, \Deltat = 1.1'}, ...
'Location', 'northwest', 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-euler');
results.steps = steps;
results.max_error_forward = max_error;
results.forward_dt_1_1 = x_f;
results.backward_dt_1_1 = x_b;
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function [t, x] = forward_euler(a, b, c, t_end, dt)
% x(t + dt) = x(t) + f(x(t)) * dt
n = round(t_end / dt);
t = dt * (0:n);
x = zeros(1, n + 1);
x(1) = c;
for i = 1:n
x(i + 1) = x(i) + (a - b * x(i)) * dt;
end
end
function [t, x] = backward_euler(a, b, c, t_end, dt)
% x(t + dt) = x(t) + f(x(t + dt)) * dt, solved for x(t + dt).
% For a linear f this can be done by hand:
% x(t + dt) = (x(t) + a*dt) / (1 + b*dt).
n = round(t_end / dt);
t = dt * (0:n);
x = zeros(1, n + 1);
x(1) = c;
for i = 1:n
x(i + 1) = (x(i) + a * dt) / (1 + b * dt);
end
end
Needs NumPy and Matplotlib.
"""Solving dx/dt = a - b*x with the forward and backward Euler methods.
This simple ODE has an exact solution, so we can see how the step size
dt affects accuracy and, for forward Euler, stability.
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp
a, b, c = 20, 2, 5 # dx/dt = a - b*x, x(0) = c
t_end = 4
def exact(t):
return a / b - (a / b - c) * np.exp(-b * t)
def forward_euler(dt):
"""x(t + dt) = x(t) + f(x(t)) * dt"""
n = round(t_end / dt)
t = dt * np.arange(n + 1)
x = np.zeros(n + 1)
x[0] = c
for i in range(n):
x[i + 1] = x[i] + (a - b * x[i]) * dt
return t, x
def backward_euler(dt):
"""x(t + dt) = x(t) + f(x(t + dt)) * dt, solved for x(t + dt).
For a linear f this can be done by hand:
x(t + dt) = (x(t) + a*dt) / (1 + b*dt).
"""
n = round(t_end / dt)
t = dt * np.arange(n + 1)
x = np.zeros(n + 1)
x[0] = c
for i in range(n):
x[i + 1] = (x[i] + a * dt) / (1 + b * dt)
return t, x
# --- Forward Euler with different step sizes
steps = [0.05, 0.25, 0.9, 1.1]
max_error = []
for dt in steps:
t, x = forward_euler(dt)
max_error.append(np.abs(x - exact(t)).max())
print(f"forward Euler, dt = {dt:4}: max error = {max_error[-1]:.4g}")
print(f"Forward Euler is stable only for dt < 2/b = {2 / b}")
# --- Forward vs backward Euler at a step size beyond the stability limit
t_f, x_f = forward_euler(1.1)
t_b, x_b = backward_euler(1.1)
# --- Plot
sbp.style()
colors = ["#0072B2", "#009E73", "#E69F00"]
t_fine = np.linspace(0, 4.4, 441)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(t_fine, exact(t_fine), "k-", lw=2, label="exact")
for dt, col in zip(steps[:3], colors): # dt = 1.1 is in the right panel
t, x = forward_euler(dt)
ax1.plot(t, x, "o-", color=col, ms=4, label=f"Δt = {dt}")
ax1.set_ylim(0, 20)
ax1.set_xlabel("t")
ax1.set_ylabel("x(t)")
ax1.set_title("Forward Euler")
ax1.legend(frameon=False, loc="upper right")
ax2.plot(t_fine, exact(t_fine), "k-", lw=2, label="exact")
ax2.plot(t_f, x_f, "o-", color="#D55E00", ms=4, label="forward, Δt = 1.1")
ax2.plot(t_b, x_b, "s-", color="#0072B2", ms=4, label="backward, Δt = 1.1")
ax2.set_ylim(-2, 25)
ax2.set_xlabel("t")
ax2.set_title("Forward vs backward Euler")
ax2.legend(frameon=False, loc="upper left")
sbp.save_figure(fig, __file__, "fig-euler")
sbp.save_results(__file__, {
"steps": steps,
"max_error_forward": max_error,
"forward_dt_1_1": x_f,
"backward_dt_1_1": x_b,
})
sbp.show()
Small steps track the exact solution well, and the error shrinks roughly in proportion to \(\Delta t\). Large steps are a different matter. For this ODE, each forward Euler step multiplies the distance from the steady state by \((1 - b\,\Delta t)\). If \(\Delta t\) is between \(1/b\) and \(2/b\), this factor is negative but smaller than 1 in size, so the solution overshoots and oscillates, but still settles (\(\Delta t = 0.9\)). Beyond \(2/b = 1\) it is larger than 1 in size, and the solution oscillates with growing amplitude (\(\Delta t = 1.1\)): the method is unstable. Backward Euler multiplies the distance by \(1/(1 + b\,\Delta t)\) instead, which is less than 1 for any step size, so it stays stable even at \(\Delta t = 1.1\); it is merely inaccurate.
In practice: use a library solver
You will rarely write your own solver. MATLAB and SciPy provide well-tested solvers that choose the step size automatically to keep the estimated error within a tolerance you set. The main ones correspond closely:
| MATLAB | Python (SciPy) | |
|---|---|---|
| Call | [t, y] = ode45(f, tspan, y0, opts) |
sol = solve_ivp(f, t_span, y0, ...) |
| Right-hand side | f(t, y), returns a column vector |
f(t, y), returns a list or array |
| General-purpose (non-stiff) | ode45 |
method="RK45" (the default) |
| Lower accuracy, cheaper | ode23 |
method="RK23" |
| Stiff problems | ode15s, ode23s |
method="BDF", "Radau", or "LSODA" (switches automatically) |
| Tolerances | odeset('RelTol', 1e-6, 'AbsTol', 1e-9) |
rtol=1e-6, atol=1e-9 |
| Output at chosen times | pass a vector as tspan |
pass t_eval=... |
| Shape of the solution | y is time × species |
sol.y is species × time |
5.6 Troubleshooting
5.6.1 Handling stiff equations
The quasi-steady-state approximation works because binding is fast and catalysis is slow. That same separation of time scales causes trouble for numerical solvers. Let us solve the enzyme model again, with \(E_0 \ll S_0\), making binding and unbinding (\(k_1 = k_{-1}\)) faster and faster.
Core MATLAB only.
%% Stiffness: when fast binding makes a simple model expensive to solve
% The same enzyme model as before, but now binding and unbinding (k1, k_1)
% are much faster than catalysis (k2). The fast and slow time scales make
% the ODEs 'stiff'. We compare a non-stiff solver (ode45) with a stiff
% one (ode15s) by counting how often each one evaluates the right-hand
% side of the ODEs.
% Requires: core MATLAB only.
k2 = 1.0; E0 = 0.1; S0 = 10.0; t_end = 50.0;
opts = odeset('RelTol', 1e-6, 'AbsTol', 1e-9);
% y = [S; ES; P]
enzyme = @(t, y, k1, k_1) [-k1*(E0 - y(2))*y(1) + k_1*y(2)
k1*(E0 - y(2))*y(1) - (k_1 + k2)*y(2)
k2*y(2)];
%% How the cost grows as binding gets faster (k1 = k_1 = k)
speeds = [1 10 100 1000];
cost_nonstiff = zeros(size(speeds));
cost_stiff = zeros(size(speeds));
final_P = zeros(size(speeds));
for i = 1:numel(speeds)
k = speeds(i);
f = @(t, y) enzyme(t, y, k, k);
nonstiff = ode45(f, [0 t_end], [S0; 0; 0], opts);
stiff = ode15s(f, [0 t_end], [S0; 0; 0], opts);
cost_nonstiff(i) = nonstiff.stats.nfevals;
cost_stiff(i) = stiff.stats.nfevals;
final_P(i) = stiff.y(3, end);
fprintf(['k = %5g: ode45 used %7d evaluations, ode15s %5d; ' ...
'P(%g) = %.4f mM\n'], k, cost_nonstiff(i), cost_stiff(i), ...
t_end, final_P(i));
end
%% The fast transient, for k = 100, on a logarithmic time axis
t = logspace(-4, log10(t_end), 41);
[~, y] = ode15s(@(t, y) enzyme(t, y, 100, 100), [0 t], [S0; 0; 0], opts);
y = y(2:end, :); % drop t = 0, which we added as the start
%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
semilogx(t, y(:, 2) / E0, '-', 'Color', [0.000 0.620 0.451], ...
'LineWidth', 2);
hold on
semilogx(t, y(:, 3) / S0, '-', 'Color', [0.000 0.447 0.698], ...
'LineWidth', 2);
% Label the curves directly: no room for a legend that misses them
text(1e-1, 0.93, 'ES / E_0 (fast)', 'Color', [0.000 0.620 0.451], ...
'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
text(1e-2, 0.03, 'P / S_0 (slow)', 'Color', [0.000 0.447 0.698], ...
'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
ylim([0 1]);
xlabel('Time (s)'); ylabel('Fraction');
title('Two time scales (k_1 = k_{-1} = 100)');
box off
subplot(1, 2, 2)
loglog(speeds, cost_nonstiff, 'o-', 'Color', [0.902 0.624 0.000], ...
'MarkerFaceColor', [0.902 0.624 0.000]);
hold on
loglog(speeds, cost_stiff, 's-', 'Color', [0.000 0.447 0.698], ...
'MarkerFaceColor', [0.000 0.447 0.698]);
xlabel('Binding rate constants k_1 = k_{-1}');
ylabel('Function evaluations');
title('Cost of solving to t = 50 s');
legend({'non-stiff solver', 'stiff solver'}, 'Location', 'northwest', ...
'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-stiff');
results.speeds = speeds;
results.final_P = final_P;
results.t = t;
results.ES_k100 = y(:, 2)';
results.P_k100 = y(:, 3)';
results.evaluations_nonstiff = cost_nonstiff;
results.evaluations_stiff = cost_stiff;
sbp.save_results(mfilename('fullpath'), results);
Needs SciPy.
"""Stiffness: when fast binding makes a simple model expensive to solve.
The same enzyme model as before, but now binding and unbinding (k1, k_1)
are much faster than catalysis (k2). The fast and slow time scales make
the ODEs 'stiff'. We compare a non-stiff solver (RK45, like ode45) with a
stiff one (BDF, like ode15s) by counting how often each one evaluates the
right-hand side of the ODEs.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
k2, E0, S0, t_end = 1.0, 0.1, 10.0, 50.0
tol = dict(rtol=1e-6, atol=1e-9)
def enzyme(t, y, k1, k_1):
S, ES, P = y
E = E0 - ES
return [-k1 * E * S + k_1 * ES,
k1 * E * S - (k_1 + k2) * ES,
k2 * ES]
# --- How the cost grows as binding gets faster (k1 = k_1 = k)
speeds = [1, 10, 100, 1000]
cost = {"nonstiff": [], "stiff": []}
final_P = []
for k in speeds:
nonstiff = solve_ivp(enzyme, [0, t_end], [S0, 0, 0], method="RK45",
args=(k, k), **tol)
stiff = solve_ivp(enzyme, [0, t_end], [S0, 0, 0], method="BDF",
args=(k, k), **tol)
cost["nonstiff"].append(nonstiff.nfev)
cost["stiff"].append(stiff.nfev)
final_P.append(stiff.y[2, -1])
print(f"k = {k:5}: RK45 used {nonstiff.nfev:7} evaluations, "
f"BDF {stiff.nfev:5}; P({t_end:g}) = {stiff.y[2, -1]:.4f} mM")
# --- The fast transient, for k = 100, on a logarithmic time axis
t = np.logspace(-4, np.log10(t_end), 41)
sol = solve_ivp(enzyme, [0, t_end], [S0, 0, 0], method="BDF", t_eval=t,
args=(100, 100), **tol)
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.semilogx(t, sol.y[1] / E0, "-", color="#009E73", lw=2)
ax1.semilogx(t, sol.y[2] / S0, "-", color="#0072B2", lw=2)
# Label the curves directly: no room for a legend that misses them
ax1.text(1e-1, 0.93, "ES / $E_0$ (fast)", color="#009E73", ha="center",
va="bottom")
ax1.text(1e-2, 0.03, "P / $S_0$ (slow)", color="#0072B2", ha="center",
va="bottom")
ax1.set_ylim(0, 1)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Fraction")
ax1.set_title("Two time scales ($k_1 = k_{-1} = 100$)")
ax2.loglog(speeds, cost["nonstiff"], "o-", color="#E69F00",
label="non-stiff solver")
ax2.loglog(speeds, cost["stiff"], "s-", color="#0072B2",
label="stiff solver")
ax2.set_xlabel("Binding rate constants $k_1 = k_{-1}$")
ax2.set_ylabel("Function evaluations")
ax2.set_title("Cost of solving to t = 50 s")
ax2.legend(frameon=False)
sbp.save_figure(fig, __file__, "fig-stiff")
sbp.save_results(__file__, {
"speeds": speeds,
"final_P": final_P,
"t": t,
"ES_k100": sol.y[1],
"P_k100": sol.y[2],
"evaluations_nonstiff": cost["nonstiff"],
"evaluations_stiff": cost["stiff"],
})
sbp.show()
The left panel shows the two time scales: the complex \(ES\) forms within a few milliseconds, while the product takes tens of seconds to accumulate. After the first few milliseconds, nothing fast is happening, yet a non-stiff solver such as ode45 or RK45 must keep its steps small enough to remain stable with respect to the fast process, just as forward Euler had to keep \(\Delta t < 2/b\). Its cost therefore grows in proportion to the binding rate constants (right panel), reaching close to a million function evaluations. A stiff solver such as ode15s or BDF is implicit, like backward Euler, and can take large steps once the fast transient is over; its cost hardly changes. Both reach the same answer.
Such ODEs are called stiff: the step size is limited by the stability of the method, long before accuracy becomes a concern. Stiffness is common in biology, where binding, phosphorylation and transport often run much faster than gene expression or growth. A practical rule: start with ode45 or RK45, and if it is unexpectedly slow, switch to ode15s or BDF (or LSODA).
The exact counts differ between MATLAB and Python, because the solvers differ in their internals, but the pattern is the same; our automated checks compare only the solutions.
5.6.2 Handling uncertainty
Data never pin down a model completely. One practical way to see what the data do and do not determine is to build an ensemble of parameter sets, all consistent with the data, and to compare their predictions. We take the gene expression model fitted to mRNA and protein data in §6.2.2. Near the best fit, the uncertainty in the (logarithms of the) parameters is approximately Gaussian, with covariance \((J^TJ)^{-1}\), as in the sloppiness analysis of §6.5.2. We draw 200 parameter sets from this distribution, using sbp.uniform so that both languages draw the same sets.
Core MATLAB only.
%% Handling uncertainty with an ensemble of models
% Parameters estimated from data are uncertain, and so are the predictions
% made with them. One way to see how uncertain is to build an ensemble:
% many parameter sets that are all consistent with the data, each making
% its own prediction (book §5.6.2). Predictions on which the members agree
% can be trusted; those on which they disagree cannot, however good the fit.
%
% The model and data are those of fit_timecourse (gene expression, mRNA and
% protein measured for 12 h). Near the best fit, the parameters (in logs)
% are approximately Gaussian, with covariance (J'J)^-1, where J is the
% Jacobian of the weighted residuals (see sloppiness, §6.5.2). We draw 200
% parameter sets from this distribution, and compare their predictions:
% * the protein level at 12 h (within the data) and at 48 h (beyond it);
% * the protein level at 48 h if translation is halved;
% * the half-lives of the mRNA and of the protein.
% The Gaussian numbers come from sbp.uniform (Box-Muller), so that the
% ensemble is the same in MATLAB and Python.
theta = [9.4984, 0.96342, 5.2262, 0.20479]; % fit_timecourse
data = readmatrix(fullfile(sbp.data_dir(), 'gene_expression_timecourse.csv'));
t_obs = data(:, 1)'; m_obs = data(:, 2)'; p_obs = data(:, 3)';
delta = 0.1;
resid = @(log_p) residuals(exp(log_p), t_obs, m_obs, p_obs, delta);
% Covariance of log(theta): (J'J)^-1, J by central differences
log_theta = log(theta);
J = zeros(2 * numel(t_obs), 4);
for j = 1:4
up = log_theta; up(j) = up(j) + 1e-5;
down = log_theta; down(j) = down(j) - 1e-5;
J(:, j) = (resid(up) - resid(down)) / 2e-5;
end
L = chol(inv(J' * J), 'lower');
% 200 parameter sets: log(theta) + L z, z standard Gaussian
members = 200;
u = sbp.uniform(31, 2 * 4 * members);
z = sqrt(-2 * log(u(1:2:end))) .* cos(2 * pi * u(2:2:end));
z = reshape(z, 4, members)'; % members x parameters
members_theta = exp(log_theta + z * L');
t = [12, 48];
names = {'protein_12h', 'protein_48h', 'protein_48h_half_translation', ...
'mrna_half_life', 'protein_half_life'};
pred = zeros(members, numel(names));
for k = 1:members
p = members_theta(k, :);
x = simulate(p, t);
halved = simulate(p .* [1, 1, 0.5, 1], t);
pred(k, :) = [x(2, 1), x(2, 2), halved(2, 2), log(2) / p(2), ...
log(2) / p(4)];
end
fprintf(['Prediction (200 members) median 5%% to 95%%' ...
' spread\n']);
for c = 1:numel(names)
s = sort(pred(:, c));
% median, and the 10th and 190th of the 200 sorted values (the 5th
% and 95th percentiles)
r = struct('median', median(s), 'low', s(10), 'high', s(190), ...
'spread_percent', 100 * (s(190) - s(10)) / median(s));
results.(names{c}) = r;
fprintf(' %-30s %7.2f %6.2f to %6.2f %5.1f%%\n', names{c}, ...
r.median, r.low, r.high, r.spread_percent);
end
%% Plot: the ensemble of protein time courses
fig = figure('Position', [100 100 650 450]); hold on
tt = linspace(0, 48, 97);
for k = 1:50
x = simulate(members_theta(k, :), tt(2:end));
plot(tt, [0, x(2, :)], 'Color', [0.000 0.447 0.698 0.15]);
end
h = plot(t_obs, p_obs, 'ko', 'MarkerSize', 4, 'MarkerFaceColor', 'k');
xline(12, ':k', 'LineWidth', 1.5);
xlabel('Time (h)'); ylabel('Protein (molecules per cell)');
title('50 members of the ensemble');
legend(h, 'data (12 h)', 'Box', 'off', 'Location', 'southeast');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-ensemble');
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function x = simulate(p, t)
% Rows: mRNA, protein, at the times t (all > 0).
rhs = @(~, y) [p(1) - p(2) * y(1); p(3) * y(1) - p(4) * y(2)];
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-10);
[~, y] = ode45(rhs, [0, t], [0; 0], opts);
x = y(2:end, :)';
end
function r = residuals(p, t, m_obs, p_obs, delta)
x = simulate(p, t);
r = [(x(1, :) - m_obs) ./ (delta * m_obs), ...
(x(2, :) - p_obs) ./ (delta * p_obs)]';
end
Needs SciPy.
"""Handling uncertainty with an ensemble of models.
Parameters estimated from data are uncertain, and so are the predictions
made with them. One way to see how uncertain is to build an ensemble:
many parameter sets that are all consistent with the data, each making
its own prediction (book §5.6.2). Predictions on which the members agree
can be trusted; those on which they disagree cannot, however good the fit.
The model and data are those of fit_timecourse (gene expression, mRNA and
protein measured for 12 h). Near the best fit, the parameters (in logs)
are approximately Gaussian, with covariance (J'J)^-1, where J is the
Jacobian of the weighted residuals (see sloppiness, §6.5.2). We draw 200
parameter sets from this distribution, and compare their predictions:
* the protein level at 12 h (within the data) and at 48 h (beyond it);
* the protein level at 48 h if translation is halved;
* the half-lives of the mRNA and of the protein.
The Gaussian numbers come from sbp.uniform (Box-Muller), so that the
ensemble is the same in MATLAB and Python.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
theta = np.array([9.4984, 0.96342, 5.2262, 0.20479]) # fit_timecourse
data = np.loadtxt(sbp.DATA / "gene_expression_timecourse.csv",
delimiter=",", skiprows=1)
t_obs, m_obs, p_obs = data.T
delta = 0.1
def simulate(p, t):
k_m, g_m, k_p, g_p = p
rhs = lambda _, y: [k_m - g_m * y[0], k_p * y[0] - g_p * y[1]]
return solve_ivp(rhs, [0, t[-1]], [0, 0], t_eval=t, method="LSODA",
rtol=1e-10, atol=1e-10).y
def residuals(log_p):
m, prot = simulate(np.exp(log_p), t_obs)
return np.r_[(m - m_obs) / (delta * m_obs),
(prot - p_obs) / (delta * p_obs)]
# Covariance of log(theta): (J'J)^-1, J by central differences
log_theta = np.log(theta)
J = np.zeros((2 * len(t_obs), 4))
for j in range(4):
up, down = log_theta.copy(), log_theta.copy()
up[j] += 1e-5
down[j] -= 1e-5
J[:, j] = (residuals(up) - residuals(down)) / 2e-5
L = np.linalg.cholesky(np.linalg.inv(J.T @ J))
# 200 parameter sets: log(theta) + L z, z standard Gaussian
members = 200
u = sbp.uniform(31, 2 * 4 * members)
z = (np.sqrt(-2 * np.log(u[0::2])) * np.cos(2 * np.pi * u[1::2]))
z = z.reshape(members, 4)
members_theta = np.exp(log_theta + z @ L.T)
t = np.array([12.0, 48.0])
predictions = {"protein_12h": [], "protein_48h": [],
"protein_48h_half_translation": [],
"mrna_half_life": [], "protein_half_life": []}
for p in members_theta:
prot = simulate(p, t)[1]
halved = simulate(p * [1, 1, 0.5, 1], t)[1]
predictions["protein_12h"].append(prot[0])
predictions["protein_48h"].append(prot[1])
predictions["protein_48h_half_translation"].append(halved[1])
predictions["mrna_half_life"].append(np.log(2) / p[1])
predictions["protein_half_life"].append(np.log(2) / p[3])
def summary(x):
"""Median, and the 10th and 190th of the 200 sorted values (the 5th
and 95th percentiles)."""
s = np.sort(x)
return {"median": np.median(s), "low": s[9], "high": s[189],
"spread_percent": 100 * (s[189] - s[9]) / np.median(s)}
results = {k: summary(v) for k, v in predictions.items()}
print("Prediction (200 members) median 5% to 95% spread")
for k, r in results.items():
print(f" {k:30s} {r['median']:7.2f} {r['low']:6.2f} to {r['high']:6.2f}"
f" {r['spread_percent']:5.1f}%")
# --- Plot: the ensemble of protein time courses
sbp.style()
fig, ax = plt.subplots(figsize=(6.5, 4.5))
tt = np.linspace(0, 48, 97)
for p in members_theta[:50]:
ax.plot(tt, simulate(p, tt)[1], color="#0072B2", alpha=0.15)
ax.plot(t_obs, p_obs, "o", color="black", ms=4, label="data (12 h)")
ax.axvline(12, ls=":", color="black")
ax.set_xlabel("Time (h)")
ax.set_ylabel("Protein (molecules per cell)")
ax.set_title("50 members of the ensemble")
ax.legend(frameon=False, loc="lower right")
sbp.save_figure(fig, __file__, "fig-ensemble")
sbp.save_results(__file__, results)
sbp.show()
The members of the ensemble agree closely on the protein level at 12 h, within the range of the data: the middle 90% of their predictions span 13%. Asked to extrapolate to 48 h, well beyond the data, they agree much less (23%), and they are even less certain about the half-lives of the mRNA (31%) and, especially, of the protein (47%). Predictions can thus be more precise than the parameters behind them: a lesson from sloppy models (Gutenkunst et al. 2007). Note, too, that halving translation simply halves the predicted protein level at 48 h, with the same relative uncertainty; a relative prediction of this kind is often much more robust than an absolute one. When even the topology of a model is uncertain, the same idea extends to ensembles of different models (§6.4.1).
5.7 Software tools
There is no code for this section; see the book.
5.A Stochastic simulation
The ODE models of this chapter treat concentrations as smooth, continuous quantities. Inside a single cell, however, many molecules are present in tiny numbers: a gene has one or two copies, and a given mRNA may be present as a handful of molecules. Each reaction is then a discrete, random event, and two genetically identical cells in the same environment can hold quite different numbers of a protein. This section simulates such systems with Gillespie’s algorithm, and shows how the random fluctuations, or noise, depend on the reactions that produce them. For a fuller treatment, see the reviews by Gillespie (2007) and Raj and Oudenaarden (2008).
5.A.1 Gillespie’s algorithm
Consider a set of reactions, each with a propensity \(a_j(\mathbf{x})\): the probability per unit time that reaction \(j\) occurs, given the current numbers of molecules \(\mathbf{x}\). For a reaction \(\text{M} \to \emptyset\) with rate constant \(\gamma\), for instance, the propensity is \(\gamma M\), since each of the \(M\) molecules can be degraded. Gillespie’s stochastic simulation algorithm (SSA) generates exact sample paths of such a system (Gillespie 1977):
- Compute all propensities and their sum, \(a_0 = \sum_j a_j(\mathbf{x})\).
- Draw the time to the next reaction from an exponential distribution with mean \(1/a_0\): \(\tau = -\ln(r_1)/a_0\), with \(r_1\) uniform on \((0, 1)\).
- Choose which reaction occurs: reaction \(j\) with probability \(a_j/a_0\).
- Advance time by \(\tau\), update \(\mathbf{x}\) for that reaction, and repeat.
Both languages have a short implementation of these four steps in the companion’s helper package (sbp.gillespie), which returns the state at a chosen set of times. Here is the Python version; the MATLAB one, in matlab/+sbp/gillespie.m, follows it line by line.
"""Gillespie's stochastic simulation algorithm (SSA), shared by examples."""
import numpy as np
def gillespie(x0, changes, propensities, t_grid, rng):
"""Simulate one trajectory and return the state at the times t_grid.
x0 initial numbers of molecules (one per species)
changes one row per reaction: how each species changes when the
reaction fires
propensities function of the state x, returning one rate per reaction
t_grid increasing times at which to record the state
rng a numpy random generator
"""
changes = np.asarray(changes)
x = np.array(x0, dtype=float)
t = 0.0
out = np.zeros((len(t_grid), len(x)))
k = 0
while k < len(t_grid):
a = propensities(x)
a0 = a.sum()
# Time to the next reaction: exponential with mean 1/a0
tau = rng.exponential(1 / a0) if a0 > 0 else np.inf
# Record the current state at every grid time before the event
while k < len(t_grid) and t_grid[k] < t + tau:
out[k] = x
k += 1
t += tau
if k < len(t_grid):
# Which reaction: reaction j with probability a_j / a0
j = np.searchsorted(np.cumsum(a), rng.random() * a0, side="right")
x += changes[j]
return out5.A.2 Production and degradation of an mRNA
The simplest example is an mRNA made at a constant rate \(k\) and degraded at rate \(\gamma\) per molecule:
\[ \emptyset \xrightarrow{k} \text{M}, \qquad \text{M} \xrightarrow{\gamma M} \emptyset . \]
The ODE model, \(dM/dt = k - \gamma M\), rises smoothly to \(M = k/\gamma\). The stochastic model has a steady state too, but it is a steady distribution: the number of molecules keeps fluctuating, and for this model it follows a Poisson distribution with mean \(k/\gamma\), whose variance is equal to its mean. We take \(k = 10\) per minute and \(\gamma = 1\) per minute, and run the SSA 2000 times.
Core MATLAB only.
%% Stochastic production and degradation of an mRNA
% 0 -> M at rate k (transcription)
% M -> 0 at rate gamma * M (degradation)
% The deterministic (ODE) model, dM/dt = k - gamma*M, predicts a smooth
% rise to M = k/gamma. With few molecules, each reaction is a random
% event, simulated here with Gillespie's algorithm. At steady state the
% number of molecules follows a Poisson distribution with mean k/gamma.
% Requires: core MATLAB only.
k = 10; gamma = 1; % per minute
t_grid = linspace(0, 10, 201); % minutes
n_runs = 2000;
rng(1);
changes = [+1; -1];
propensities = @(x) [k, gamma * x(1)];
runs = zeros(n_runs, numel(t_grid));
for r = 1:n_runs
runs(r, :) = sbp.gillespie(0, changes, propensities, t_grid)';
end
final = runs(:, end);
ode = k / gamma * (1 - exp(-gamma * t_grid));
fprintf(['At t = %g min, over %d runs: mean %.3f, variance %.3f ' ...
'(Poisson: both %g)\n'], t_grid(end), n_runs, mean(final), ...
var(final, 1), k / gamma);
%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
colors = [0.000 0.447 0.698; 0.000 0.620 0.451; 0.800 0.475 0.655];
for r = 1:3
stairs(t_grid, runs(r, :), 'Color', colors(r, :), 'LineWidth', 1);
hold on
end
plot(t_grid, mean(runs, 1), '-', 'Color', [0.902 0.624 0.000], ...
'LineWidth', 2);
plot(t_grid, ode, 'k--', 'LineWidth', 1.5);
ylim([0 25]);
xlabel('Time (min)'); ylabel('Number of mRNA molecules');
legend({'one simulation', '', '', ...
sprintf('mean of %d simulations', n_runs), 'ODE'}, ...
'Location', 'northwest', 'Box', 'off');
title('Trajectories');
box off
subplot(1, 2, 2)
m = 0:25;
counts = histcounts(final, -0.5:25.5) / n_runs;
bar(m, counts, 'FaceColor', [0.000 0.447 0.698], 'FaceAlpha', 0.7, ...
'EdgeColor', 'none');
hold on
lambda = k / gamma;
plot(m, exp(-lambda) * lambda.^m ./ factorial(m), 'o-', ...
'Color', [0.902 0.624 0.000], 'MarkerSize', 4, ...
'MarkerFaceColor', [0.902 0.624 0.000]);
ylim([0 0.17]);
xlabel('Number of mRNA molecules'); ylabel('Probability');
legend({sprintf('simulated, t = %g min', t_grid(end)), ...
sprintf('Poisson, mean %g', lambda)}, 'Box', 'off');
title('Distribution at steady state');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-birth-death');
results.steady_state = struct('mean', mean(final), ...
'variance', var(final, 1));
mean_traj = mean(runs, 1);
results.mean_trajectory = mean_traj(1:20:end);
sbp.save_results(mfilename('fullpath'), results);
Needs SciPy (for the Poisson distribution).
"""Stochastic production and degradation of an mRNA.
0 -> M at rate k (transcription)
M -> 0 at rate gamma * M (degradation)
The deterministic (ODE) model, dM/dt = k - gamma*M, predicts a smooth
rise to M = k/gamma. With few molecules, each reaction is a random
event, simulated here with Gillespie's algorithm. At steady state the
number of molecules follows a Poisson distribution with mean k/gamma.
"""
import numpy as np
from scipy.stats import poisson
import matplotlib.pyplot as plt
import sbp
from sbp.ssa import gillespie
k, gamma = 10.0, 1.0 # per minute
t_grid = np.linspace(0, 10, 201) # minutes
n_runs = 2000
rng = np.random.default_rng(1)
changes = [[+1], [-1]]
def propensities(x):
return np.array([k, gamma * x[0]])
runs = np.array([gillespie([0], changes, propensities, t_grid, rng)[:, 0]
for _ in range(n_runs)])
final = runs[:, -1]
ode = k / gamma * (1 - np.exp(-gamma * t_grid))
print(f"At t = {t_grid[-1]:g} min, over {n_runs} runs: mean {final.mean():.3f}"
f", variance {final.var():.3f} (Poisson: both {k / gamma:g})")
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
colors = ["#0072B2", "#009E73", "#CC79A7"]
for r, col in zip(range(3), colors):
ax1.step(t_grid, runs[r], where="post", color=col, lw=1,
label="one simulation" if r == 0 else None)
ax1.plot(t_grid, runs.mean(axis=0), "-", color="#E69F00", lw=2,
label=f"mean of {n_runs} simulations")
ax1.plot(t_grid, ode, "k--", lw=1.5, label="ODE")
ax1.set_xlabel("Time (min)")
ax1.set_ylabel("Number of mRNA molecules")
ax1.set_ylim(0, 25)
ax1.legend(frameon=False, loc="upper left")
ax1.set_title("Trajectories")
m = np.arange(0, 26)
counts = np.bincount(final.astype(int), minlength=26)[:26] / n_runs
ax2.bar(m, counts, color="#0072B2", alpha=0.7,
label=f"simulated, t = {t_grid[-1]:g} min")
ax2.plot(m, poisson.pmf(m, k / gamma), "o-", color="#E69F00", ms=4,
label=f"Poisson, mean {k / gamma:g}")
ax2.set_xlabel("Number of mRNA molecules")
ax2.set_ylabel("Probability")
ax2.set_ylim(0, 0.17)
ax2.legend(frameon=False, loc="upper right", reverse=True) # bars first
ax2.set_title("Distribution at steady state")
sbp.save_figure(fig, __file__, "fig-birth-death")
sbp.save_results(__file__, {
"steady_state": {"mean": final.mean(), "variance": final.var()},
"mean_trajectory": runs.mean(axis=0)[::20],
})
sbp.show()
Individual runs (left) are jagged and differ from one another; at steady state, any one of them may hold anywhere from about 3 to 18 molecules. Their average, on the other hand, follows the ODE closely. For reactions such as these, where every propensity is at most linear in the numbers of molecules, the ODE gives the mean behaviour exactly; for nonlinear reactions, such as dimerisation, it is only an approximation. The distribution across runs (right) matches the Poisson distribution.
A useful way to describe the size of fluctuations is the Fano factor, the variance divided by the mean. It is 1 for a Poisson distribution, whatever the mean. Relative fluctuations, measured by the coefficient of variation \(\sigma/\mu = 1/\sqrt{\mu}\), shrink as numbers grow: with 10 molecules they are about 32%, with 10,000 about 1%. That is why ODEs work well for abundant molecules and stochastic models matter for scarce ones.
5.A.3 Noise in gene expression
Proteins are made from mRNAs, and each mRNA is translated many times before it is degraded. Adding these two steps,
\[ \emptyset \xrightarrow{k_m} \text{M}, \qquad \text{M} \xrightarrow{\gamma_m M} \emptyset, \qquad \text{M} \xrightarrow{k_p M} \text{M} + \text{P}, \qquad \text{P} \xrightarrow{\gamma_p P} \emptyset , \]
the mean number of proteins at steady state is \(k_m k_p / \gamma_m \gamma_p\), and the Fano factor of the protein is approximately \(1 + k_p/(\gamma_m + \gamma_p)\) (Thattai and Oudenaarden 2001). The ratio \(k_p/\gamma_m\) is the mean number of proteins made from one mRNA, the burst size. So two genes can make the same average amount of protein with very different noise: gene A is transcribed often, with small bursts of 2.5 proteins per mRNA, while gene B is transcribed ten times less often, with bursts of 25. Here we simulate each gene for 40,000 minutes and sample the protein number once a minute.
Core MATLAB only.
%% Noise in gene expression: transcription and translation
% 0 -> M at rate km (transcription)
% M -> 0 at rate gm * M (mRNA degradation)
% M -> M + P at rate kp * M (translation)
% P -> 0 at rate gp * P (protein degradation)
% Two genes make the same mean number of proteins, 50. Gene A is
% transcribed often and each mRNA is translated a few times; gene B is
% transcribed rarely and each mRNA is translated many times, so its
% proteins are made in bursts. Theory (for example, Thattai and van
% Oudenaarden, 2001) gives, at steady state,
% mean P = km*kp/(gm*gp), Fano factor = var/mean = 1 + kp/(gm + gp).
% Requires: core MATLAB only.
gm = 1.0; gp = 0.1; % per minute
names = {'A', 'B'};
km = [2.0 0.2]; % B: rare transcription,
kp = [2.5 25.0]; % big bursts
t_grid = 0:40000; % one long run, sampled each minute
burn_in = 200; % discard the approach to steady state
rng(1);
% Changes in (M, P) for each of the four reactions
changes = [1 0; -1 0; 0 1; 0 -1];
traces = zeros(numel(t_grid), 2);
for g = 1:2
propensities = @(x) [km(g), gm * x(1), kp(g) * x(1), gp * x(2)];
X = sbp.gillespie([0 0], changes, propensities, t_grid);
traces(:, g) = X(:, 2);
P = X(burn_in + 1:end, 2);
results.(names{g}) = struct('mean', mean(P), ...
'fano', var(P, 1) / mean(P));
fprintf(['Gene %s: mean %.1f (theory %g), Fano factor %.2f ' ...
'(theory %.2f)\n'], names{g}, mean(P), km(g) * kp(g) / (gm * gp), ...
var(P, 1) / mean(P), 1 + kp(g) / (gm + gp));
end
%% Plot
colors = [0.000 0.447 0.698; 0.902 0.624 0.000];
fig = figure('Position', [100 100 1000 400]);
subplot(1, 3, [1 2])
window = 1001:1301;
for g = 1:2
plot(t_grid(window) - t_grid(window(1)), traces(window, g), ...
'Color', colors(g, :), 'LineWidth', 1.2);
hold on
end
xlabel('Time (min)'); ylabel('Number of protein molecules');
title('Same mean, different noise');
legend({'gene A', 'gene B'}, 'Location', 'northwest', 'Box', 'off');
box off
subplot(1, 3, 3)
edges = 0:5:250;
for g = 1:2
h = histcounts(traces(burn_in + 1:end, g), edges, ...
'Normalization', 'pdf');
stairs(edges, [h h(end)], 'Color', colors(g, :), 'LineWidth', 1.5);
hold on
end
xlabel('Number of protein molecules'); ylabel('Probability density');
title('Distribution');
legend({'gene A', 'gene B'}, 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-gene-expression');
sbp.save_results(mfilename('fullpath'), results);
Needs NumPy and Matplotlib.
"""Noise in gene expression: transcription and translation.
0 -> M at rate km (transcription)
M -> 0 at rate gm * M (mRNA degradation)
M -> M + P at rate kp * M (translation)
P -> 0 at rate gp * P (protein degradation)
Two genes make the same mean number of proteins, 50. Gene A is
transcribed often and each mRNA is translated a few times; gene B is
transcribed rarely and each mRNA is translated many times, so its
proteins are made in bursts. Theory (for example, Thattai and van
Oudenaarden, 2001) gives, at steady state,
mean P = km*kp/(gm*gp), Fano factor = var/mean = 1 + kp/(gm + gp).
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp
from sbp.ssa import gillespie
gm, gp = 1.0, 0.1 # per minute
genes = {"A": {"km": 2.0, "kp": 2.5}, # frequent transcription
"B": {"km": 0.2, "kp": 25.0}} # rare transcription, big bursts
t_grid = np.arange(0, 40001.0) # one long run, sampled each minute
burn_in = 200 # discard the approach to steady state
rng = np.random.default_rng(1)
# Changes in (M, P) for each of the four reactions
changes = [[1, 0], [-1, 0], [0, 1], [0, -1]]
results = {}
traces = {}
for name, g in genes.items():
def propensities(x, km=g["km"], kp=g["kp"]):
M, P = x
return np.array([km, gm * M, kp * M, gp * P])
X = gillespie([0, 0], changes, propensities, t_grid, rng)
P = X[burn_in:, 1]
theory_mean = g["km"] * g["kp"] / (gm * gp)
theory_fano = 1 + g["kp"] / (gm + gp)
results[name] = {"mean": P.mean(), "fano": P.var() / P.mean()}
traces[name] = X[:, 1]
print(f"Gene {name}: mean {P.mean():.1f} (theory {theory_mean:g}), "
f"Fano factor {P.var() / P.mean():.2f} (theory {theory_fano:.2f})")
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
gridspec_kw={"width_ratios": [2, 1]})
window = slice(1000, 1301)
colors = {"A": "#0072B2", "B": "#E69F00"}
for name in genes:
ax1.plot(t_grid[window] - t_grid[window][0], traces[name][window],
color=colors[name], lw=1.2, label=f"gene {name}")
ax2.hist(traces[name][burn_in:], bins=np.arange(0, 251, 5),
density=True, histtype="step", lw=1.5, color=colors[name],
label=f"gene {name}")
ax1.set_xlabel("Time (min)")
ax1.set_ylabel("Number of protein molecules")
ax1.set_title("Same mean, different noise")
ax1.legend(frameon=False, loc="upper left")
ax2.set_xlabel("Number of protein molecules")
ax2.set_ylabel("Probability density")
ax2.set_title("Distribution")
ax2.legend(frameon=False)
sbp.save_figure(fig, __file__, "fig-gene-expression")
sbp.save_results(__file__, results)
sbp.show()
Both genes average about 50 proteins, but gene B jumps up in bursts, each time one of its rare mRNAs is translated many times over, and then decays; its Fano factor is about 23, against about 3 for gene A (the theory gives 23.7 and 3.3), and its distribution is wide and skewed. Ozbudak and colleagues found exactly this in Bacillus subtilis: increasing translation increased noise far more than increasing transcription did (Ozbudak et al. 2002). Cells can therefore tune their noise, as well as their mean expression, through the balance of transcription and translation.
Since MATLAB and Python draw different random numbers, the two versions give slightly different estimates. The automated checks require both to be within 10% of theory for the mRNA example, and within 15% for the noisier protein estimates.
Noise is not always a nuisance. In circuits with two stable states, such as the toggle switch, noise can flip cells between states, letting a population hedge its bets. Exploring such circuits needs both the ODE tools of this chapter and the stochastic tools of this section.
Exercises
- Run forward Euler with \(\Delta t = 1/b = 0.5\) and \(\Delta t = 2/b = 1\). Explain both results using the factor \((1 - b\,\Delta t)\).
- For the Michaelis–Menten example, vary \(E_0\) from 0.01 to 10 mM and plot the largest difference between the two models against \(E_0 / (S_0 + K_M)\).
- Make the product step reversible (\(E + P \to ES\) with rate constant \(k_{-2}\); book Eq. 5.3). Does the Michaelis–Menten rate law still describe the time course? What happens at long times?
- Solve the stiff example with \(k_1 = k_{-1} = 1000\) using
ode45andode15s(orRK45andBDF), timing each withtic/toc(ortime.perf_counter). - Replace the Michaelis–Menten rate law with a Hill rate law, \(v = v_\text{max}[S]^n / (K^n + [S]^n)\), and compare the time courses for \(n = 1, 2, 4\). (Book Eq. 5.14 writes the denominator as \(k' + [S]^n\), with \(k' = K^n\); Eq. 5.15.)
- Book Exercises 5.3–5.5: solve \(dx/dt = -x^3\), \(x(0) = 1\), with forward Euler for several step sizes and plot the error in \(x(2)\) against the step size; then solve \(dx/dt = -30x\) up to \(t = 1.5\) with \(\Delta t = 0.001\), 0.01 and 0.05. Which step sizes are stable, and why?
- Simulate the three-node phosphorylation oscillator of book §5.3.3 (Eqs. 5.17–5.19). Choose parameter values and explore: can the three proteins oscillate, and what does it take? (Compare the repressilator in Chapter 12.)
- In the mRNA example, start each run with 50 molecules in place of none. How does the mean approach the steady state? Compare with the solution of the ODE.
- Add a dimerisation reaction, \(2\text{P} \to \text{D}\), with propensity \(k_d P(P-1)/2\), to the birth–death model for a protein P. Compare the mean of many SSA runs with the solution of the corresponding ODE for small and large numbers of molecules. When do they differ?
- For the gene-expression model, vary \(k_p\) from 1 to 50 while adjusting \(k_m\) to keep the mean at 50 proteins. Plot the Fano factor against the burst size \(k_p/\gamma_m\) and compare with the theory.
- Simulating every reaction becomes slow when molecules are abundant. Look up the tau-leaping method, which fires many reactions in each time step, and implement it for the mRNA example. How large can the time step be before the distribution is visibly wrong?
Exercises 8–11 refer to the section on stochastic simulation (§5.A).
Going further
The parameters here were simply chosen. In practice, they must be estimated from data, which is the subject of Chapter 6.