Skip to main content

1  Introduction to modelling

Before turning to cells and molecules, two classic models show what a dynamic model is and what it can tell us. Both are systems of two or three ODEs, simple enough to understand completely, and yet each makes a prediction that is far from obvious from its equations: predator and prey populations rise and fall in endless cycles, and an epidemic either fizzles out or sweeps through most of a population, depending on a single number.

1.1 What is modelling?

1.1.1 What are models?

There is no code for this section; see the book.

1.2 Why build models?

1.2.1 Why model biological systems?

There is no code for this section; see the book.

1.2.2 Why systems biology?

There is no code for this section; see the book.

1.3 Challenges in modelling biological systems

There is no code for this section; see the book.

1.4 The practice of modelling

1.4.1 Scope of the model

There is no code for this section; see the book.

1.4.2 Making assumptions

There is no code for this section; see the book.

1.4.3 Modelling paradigms

The book deals with deterministic models, and notes that stochastic models, simulated with Gillespie’s algorithm, matter when molecule numbers are small. This companion adds a section on stochastic simulation at the end of Chapter 5.

1.4.4 Building the model

There is no code for this section; see the book.

1.4.5 Model analysis, debugging and (in)validation

There is no code for this section; see the book.

1.4.6 Simulating the model

Every example in this companion is a simulation, in both MATLAB and Python; Getting started explains how to run them.

1.5 Examples of models

Let us now look at the two classic models in turn. We solve both with the standard ODE solvers, ode45 in MATLAB and solve_ivp in Python; Chapter 5 looks at how such solvers work.

1.5.1 Lotka–Volterra predator–prey model

The Lotka–Volterra model follows two populations, deer \(D\) (the prey) and lions \(L\) (the predators):

\[ \frac{dD}{dt} = bD - pLD, \qquad \frac{dL}{dt} = rDL - dL . \]

Deer are born at rate \(b\) and are eaten at a rate proportional to how often deer and lions meet, \(pLD\). Lions grow by eating deer, \(rDL\), and die at rate \(d\). Setting both derivatives to zero gives the steady state, where the populations would stay forever if left there: \(D^* = d/r\) and \(L^* = b/p\). Away from it, something more interesting happens.

Core MATLAB only.

%% The Lotka-Volterra predator-prey model (book Eqs. 1.4 and 1.5)
%     dD/dt = b*D - p*L*D      deer (prey): born at rate b, eaten by lions
%     dL/dt = r*D*L - d*L      lions (predators): grow by eating, die at rate d
% The populations oscillate. Each starting point gives its own closed orbit
% around the steady state (D*, L*) = (d/r, b/p), because the quantity
%     V = r*D - d*ln(D) + p*L - b*ln(L)
% stays constant along every solution.
% Requires: core MATLAB only.

b = 1.0; p = 0.1; r = 0.02; d = 0.5;  % per year (p, r per animal per year)
D_star = d / r; L_star = b / p;       % steady state: 25 deer, 10 lions
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-10);

rhs = @(t, y) [b * y(1) - p * y(2) * y(1);
                          r * y(1) * y(2) - d * y(2)];
V = @(D, L) r * D - d * log(D) + p * L - b * log(L);

t = linspace(0, 30, 301);
starts = [40 9; 60 9; 80 9];
Y = cell(1, 3);
for k = 1:3
    [~, Y{k}] = ode45(rhs, t, starts(k, :), opts);
end

% Period of the first orbit: times at which the deer population passes
% upwards through D*, found by the solver as 'events'
crossing = @(t, y) upward(y(1) - D_star);
[~, ~, te] = ode45(rhs, [0 30], starts(1, :), ...
    odeset(opts, 'Events', crossing));
period = mean(diff(te));

D = Y{1}(:, 1); L = Y{1}(:, 2);
drift = max(abs(V(D, L) - V(D(1), L(1))));
fprintf('Steady state: D* = %g deer, L* = %g lions\n', D_star, L_star);
fprintf(['Period of the orbit from (40, 9): %.4f years (small ' ...
    'oscillations: 2*pi/sqrt(b*d) = %.4f)\n'], period, 2 * pi / sqrt(b * d));
fprintf('Largest change in V along the solution: %.1e\n', drift);

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
plot(t, D, '-', 'Color', [0.000 0.447 0.698]);
hold on
plot(t, L, '-', 'Color', [0.835 0.369 0.000]);
ylim([0 50]);
xlabel('Time (years)'); ylabel('Population');
title('Starting from 40 deer and 9 lions');
legend({'deer, D', 'lions, L'}, 'Location', 'north', 'Orientation', ...
    'horizontal', 'Box', 'off');
box off

subplot(1, 2, 2)
colors = [0.000 0.447 0.698; 0.000 0.620 0.451; 0.902 0.624 0.000];
for k = 1:3
    plot(Y{k}(:, 1), Y{k}(:, 2), '-', 'Color', colors(k, :));
    hold on
end
plot(D_star, L_star, 'k+', 'MarkerSize', 10, 'LineWidth', 2);
ylim([0 32]);
xlabel('Deer, D'); ylabel('Lions, L'); title('Phase plane');
legend({'start (40, 9)', 'start (60, 9)', 'start (80, 9)', ...
    'steady state'}, 'Location', 'northeast', 'NumColumns', 2, ...
    'Box', 'off', 'FontSize', 9);
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-lotka-volterra');

results.steady_state = [D_star L_star];
results.period = period;
results.V_drift = drift;
results.D_every_5_years = D(1:50:end)';
results.L_every_5_years = L(1:50:end)';
sbp.save_results(mfilename('fullpath'), results);

%% Local function
function [value, isterminal, direction] = upward(value)
% Event function for ode45: report (do not stop at) upward zero crossings.
isterminal = 0;
direction = 1;
end

Needs SciPy.

"""The Lotka-Volterra predator-prey model (book Eqs. 1.4 and 1.5).

    dD/dt = b*D - p*L*D      deer (prey): born at rate b, eaten by lions
    dL/dt = r*D*L - d*L      lions (predators): grow by eating, die at rate d

The populations oscillate. Each starting point gives its own closed orbit
around the steady state (D*, L*) = (d/r, b/p), because the quantity
    V = r*D - d*ln(D) + p*L - b*ln(L)
stays constant along every solution.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp

b, p, r, d = 1.0, 0.1, 0.02, 0.5      # per year (p, r per animal per year)
D_star, L_star = d / r, b / p         # steady state: 25 deer, 10 lions
tol = dict(rtol=1e-10, atol=1e-10)


def lotka_volterra(t, y):
    D, L = y
    return [b * D - p * L * D, r * D * L - d * L]


def V(D, L):
    return r * D - d * np.log(D) + p * L - b * np.log(L)


t = np.linspace(0, 30, 301)
starts = [(40, 9), (60, 9), (80, 9)]
sols = [solve_ivp(lotka_volterra, [0, 30], y0, t_eval=t, **tol)
        for y0 in starts]

# Period of the first orbit: times at which the deer population passes
# upwards through D*, found by the solver as 'events'
def crossing(t, y):
    return y[0] - D_star
crossing.direction = 1
ev = solve_ivp(lotka_volterra, [0, 30], starts[0], events=crossing, **tol)
period = np.diff(ev.t_events[0]).mean()

D, L = sols[0].y
drift = np.abs(V(D, L) - V(D[0], L[0])).max()
print(f"Steady state: D* = {D_star:g} deer, L* = {L_star:g} lions")
small = 2 * np.pi / np.sqrt(b * d)
print(f"Period of the orbit from (40, 9): {period:.4f} years "
      f"(small oscillations: 2*pi/sqrt(b*d) = {small:.4f})")
print(f"Largest change in V along the solution: {drift:.1e}")

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(t, D, "-", color="#0072B2", label="deer, D")
ax1.plot(t, L, "-", color="#D55E00", label="lions, L")
ax1.set_xlabel("Time (years)")
ax1.set_ylabel("Population")
ax1.set_title("Starting from 40 deer and 9 lions")
ax1.set_ylim(0, 50)
ax1.legend(frameon=False, loc="upper center", ncol=2)
colors = ["#0072B2", "#009E73", "#E69F00"]
for sol, y0, col in zip(sols, starts, colors):
    ax2.plot(sol.y[0], sol.y[1], "-", color=col,
             label=f"start ({y0[0]}, {y0[1]})")
ax2.plot(D_star, L_star, "k+", ms=10, mew=2, label="steady state")
ax2.set_xlabel("Deer, D")
ax2.set_ylabel("Lions, L")
ax2.set_title("Phase plane")
ax2.set_ylim(0, 32)
ax2.legend(frameon=False, loc="upper right", ncol=2, fontsize=9)
sbp.save_figure(fig, __file__, "fig-lotka-volterra")

sbp.save_results(__file__, {
    "steady_state": [D_star, L_star],
    "period": period,
    "V_drift": drift,
    "D_every_5_years": D[::50], "L_every_5_years": L[::50],
})
sbp.show()

The populations oscillate, with the lions lagging behind the deer: plenty of deer lets the lions multiply, more lions eat more deer, the deer decline, the lions starve, and the cycle begins again, about every nine years. In the phase plane (right), where time is left out and the two populations are plotted against each other, each starting point traces its own closed loop around the steady state. The loops never grow or shrink, because the quantity \(V = rD - d\ln D + pL - b\ln L\) stays exactly constant along every solution; our code checks this, and the tiny change it finds measures the error of the numerical solver.

The code also shows a useful feature of both solvers: events. Asked to watch for the moments at which \(D - D^*\) crosses zero upwards, the solver reports them precisely, which gives the period of the cycle. For small oscillations around the steady state, the period is \(2\pi/\sqrt{bd} \approx 8.9\) years; our larger cycle is a little slower.

Closed loops that depend on the starting point are a sign that this model is fragile: almost any change to its equations, such as a limit on the number of deer the land can support, turns the loops into spirals. We return to such questions in Chapter 12.

1.5.2 SIR model: a classic example

The SIR model divides a population into those susceptible to an infection (\(S\)), those infected (\(I\)) and those recovered and immune (\(R\)), as fractions of the whole:

\[ \frac{dS}{dt} = -\beta SI, \qquad \frac{dI}{dt} = \beta SI - \gamma I, \qquad \frac{dR}{dt} = \gamma I . \]

Susceptible people are infected at a rate proportional to their contacts with infected people, \(\beta SI\), and infected people recover at rate \(\gamma\), after \(1/\gamma\) days on average. The infected fraction grows only while \(\beta S > \gamma\). At the start of an outbreak, nearly everyone is susceptible, \(S \approx 1\), and so an outbreak can grow only if the basic reproduction number

\[ R_0 = \frac{\beta}{\gamma}, \]

the number of people each infected person infects in a fully susceptible population, is greater than one. (Book Eq. 1.9 writes \(\beta S/\gamma\), which is the reproduction number at a time when a fraction \(S\) is still susceptible; at the start, the two are the same.)

How many people are eventually infected? Dividing the equations for \(dS/dt\) and \(dR/dt\) and integrating gives an equation for the final size of the epidemic, \(R_\infty\):

\[ R_\infty = 1 - S_0\, e^{-R_0 R_\infty}, \]

which has exactly one solution between 0 and 1, easily found with fzero in MATLAB or brentq in Python. Our code simulates an epidemic with \(R_0 = 3\), starting from one infected person in 10,000, and then compares simulated and predicted final sizes for \(R_0\) from 0.5 to 4.

Core MATLAB only.

%% The SIR model of an epidemic (book Eqs. 1.6 to 1.8)
%     dS/dt = -beta*S*I
%     dI/dt =  beta*S*I - gamma*I
%     dR/dt =  gamma*I
% S, I and R are fractions of the population. With almost everyone
% susceptible at the start, an outbreak grows only if the basic
% reproduction number R0 = beta/gamma exceeds 1. The fraction finally
% infected, R_inf, then satisfies  R_inf = 1 - S0*exp(-R0*R_inf).
% Requires: core MATLAB only.

gamma = 0.1;                       % recovery rate: 10 days to recover
I0 = 1e-4;                         % one person in 10,000 infected at first
S0 = 1 - I0;
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10);
sir_rhs = @(t, y, beta) [-beta * y(1) * y(2);
                     beta * y(1) * y(2) - gamma * y(2);
                     gamma * y(2)];
% Final size: the one root between 0 and 1 of R_inf = 1 - S0*exp(-R0*R_inf)
final_size = @(R0) fzero(@(x) x - (1 - S0 * exp(-R0 * x)), [0 1]);

%% One epidemic, R0 = 3
beta = 0.3;
t = linspace(0, 200, 201);         % days
[~, Y] = ode45(@(t, y) sir_rhs(t, y, beta), t, [S0 I0 0], opts);
S = Y(:, 1); I = Y(:, 2); R = Y(:, 3);
[~, peak] = max(I);
fprintf(['R0 = %g: peak of %.4f infected on day %g; after 200 days ' ...
    'R = %.4f (final-size equation: %.4f)\n'], beta / gamma, I(peak), ...
    t(peak), R(end), final_size(beta / gamma));

%% Final size for a range of R0
R0s = linspace(0.5, 4, 36);
simulated = zeros(size(R0s));
theory = zeros(size(R0s));
for k = 1:numel(R0s)
    [~, Yk] = ode45(@(t, y) sir_rhs(t, y, R0s(k) * gamma), [0 5000], ...
        [S0 I0 0], opts);
    simulated(k) = Yk(end, 3);
    theory(k) = final_size(R0s(k));
end

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
plot(t, S, '-', 'Color', [0.000 0.447 0.698]);
hold on
plot(t, I, '-', 'Color', [0.835 0.369 0.000]);
plot(t, R, '--', 'Color', [0.000 0.620 0.451]);
xlabel('Time (days)'); ylabel('Fraction of the population');
title('An epidemic with R_0 = 3');
legend({'S, susceptible', 'I, infected', 'R, recovered'}, ...
    'Location', 'east', 'Box', 'off');
box off

subplot(1, 2, 2)
plot(R0s, theory, '-', 'Color', [0.6 0.6 0.6]);
hold on
plot(R0s, simulated, 'o', 'Color', [0.000 0.620 0.451], ...
    'MarkerFaceColor', [0.000 0.620 0.451], 'MarkerSize', 4);
xline(1, 'LineStyle', ':', 'Color', [0.6 0.6 0.6], 'LineWidth', 1.5);
xlabel('Basic reproduction number R_0'); ylabel('Fraction ever infected');
title('Final size of the epidemic');
legend({'final-size equation', 'simulation'}, 'Location', 'southeast', ...
    'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-sir');

results.peak_infected = I(peak);
results.peak_day = t(peak);
results.final_R = R(end);
results.final_size_R0_3 = final_size(3.0);
results.R0 = R0s;
results.final_size_simulated = simulated;
sbp.save_results(mfilename('fullpath'), results);

Needs SciPy.

"""The SIR model of an epidemic (book Eqs. 1.6 to 1.8).

    dS/dt = -beta*S*I
    dI/dt =  beta*S*I - gamma*I
    dR/dt =  gamma*I

S, I and R are fractions of the population. With almost everyone
susceptible at the start, an outbreak grows only if the basic
reproduction number R0 = beta/gamma exceeds 1. The fraction finally
infected, R_inf, then satisfies  R_inf = 1 - S0*exp(-R0*R_inf).
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import matplotlib.pyplot as plt
import sbp

gamma = 0.1                        # recovery rate: 10 days to recover
I0 = 1e-4                          # one person in 10,000 infected at first
S0 = 1 - I0
tol = dict(rtol=1e-8, atol=1e-10)


def sir(t, y, beta):
    S, I, R = y
    return [-beta * S * I, beta * S * I - gamma * I, gamma * I]


def final_size(R0):
    """Solve R_inf = 1 - S0*exp(-R0*R_inf) for the epidemic's final size.
    The equation has exactly one root between 0 and 1."""
    return brentq(lambda x: x - (1 - S0 * np.exp(-R0 * x)), 0, 1)


# --- One epidemic, R0 = 3
beta = 0.3
t = np.linspace(0, 200, 201)       # days
sol = solve_ivp(sir, [0, 200], [S0, I0, 0], t_eval=t, args=(beta,), **tol)
S, I, R = sol.y
peak = np.argmax(I)
print(f"R0 = {beta / gamma:g}: peak of {I[peak]:.4f} infected on day "
      f"{t[peak]:g}; after 200 days R = {R[-1]:.4f} "
      f"(final-size equation: {final_size(beta / gamma):.4f})")

# --- Final size for a range of R0
R0s = np.linspace(0.5, 4, 36)
simulated = [solve_ivp(sir, [0, 5000], [S0, I0, 0], args=(R0 * gamma,),
                       **tol).y[2, -1] for R0 in R0s]
theory = [final_size(R0) for R0 in R0s]

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
for y, lab, style, col in [(S, "S, susceptible", "-", "#0072B2"),
                           (I, "I, infected", "-", "#D55E00"),
                           (R, "R, recovered", "--", "#009E73")]:
    ax1.plot(t, y, style, color=col, label=lab)
ax1.set_xlabel("Time (days)")
ax1.set_ylabel("Fraction of the population")
ax1.set_title(r"An epidemic with $R_0$ = 3")
ax1.legend(frameon=False, loc="center right")
ax2.plot(R0s, theory, "-", color="#999999", label="final-size equation")
ax2.plot(R0s, simulated, "o", color="#009E73", ms=4, label="simulation")
ax2.axvline(1, color="#999999", ls=":")
ax2.set_xlabel("Basic reproduction number $R_0$")
ax2.set_ylabel("Fraction ever infected")
ax2.set_title("Final size of the epidemic")
ax2.legend(frameon=False, loc="lower right")
sbp.save_figure(fig, __file__, "fig-sir")

sbp.save_results(__file__, {
    "peak_infected": I[peak], "peak_day": t[peak], "final_R": R[-1],
    "final_size_R0_3": final_size(3.0),
    "R0": R0s, "final_size_simulated": simulated,
})
sbp.show()

With \(R_0 = 3\), the epidemic peaks after about 50 days, with 30% of the population infected at once, and by the end 94% of the population has been infected. The epidemic stops before everyone is infected because the susceptible pool runs low: once \(S < 1/R_0\), each infected person infects fewer than one other, and the outbreak dies away, even though about 6% of people never catch the infection. This is the idea behind herd immunity: vaccinating a fraction \(1 - 1/R_0\) of the population prevents an epidemic altogether.

The final-size curve (right) shows the threshold at \(R_0 = 1\). Below it, the outbreak stays tiny. Above it, the final size rises steeply, and for \(R_0\) around 2 to 3, typical of many respiratory infections, most of the population is eventually infected. The simulations agree with the final-size equation throughout.

1.6 Troubleshooting

1.6.1 Clarity of scope and objectives

There is no code for this section; see the book.

1.6.2 The breakdown of assumptions

There is no code for this section; see the book.

1.6.3 Is my model fit for purpose?

There is no code for this section; see the book.

1.6.4 Handling uncertainties

There is no code for this section; see the book.

Exercises

  1. Add a carrying capacity for the deer (book Exercise 1.4), replacing \(bD\) by \(bD(1 - D/K)\) with \(K = 100\). What happens to the oscillations, and where do the trajectories end up?
  2. Vary the initial number of lions in the Lotka–Volterra model, keeping 40 deer. Plot the period of the cycle against the amplitude of the deer oscillation.
  3. In the SIR model with \(R_0 = 3\), vaccinate a fraction \(v\) of the population at the start (move it from \(S\) to \(R\)). Plot the peak and the final size of the epidemic against \(v\). At what value of \(v\) does the epidemic no longer grow?
  4. Add a loss of immunity, \(R \to S\) at rate \(\omega\) (the SIRS model). Simulate for 1000 days with \(\omega = 0.01\) per day. What happens in the long run?
  5. Simulate the zombie outbreak model of Munz and colleagues (book Exercise 1.8), and reproduce their main results.

Going further

Both models assume well-mixed populations, in which everyone meets everyone else equally often. Real contacts follow networks, which changes how epidemics spread (book, §4.4); Chapter 3 introduces the tools for studying such networks, and Chapter 4 simulates epidemics on them. A generalised Lotka–Volterra model of interacting microbial species appears in book §11.1.2.