Randomness can be used to model particles diffusing in a fluid, a noisy physical system, an epidemic spreading through a small population. We simulate many random trajectories, called sample paths, and study their statistics.
Throughout, we draw random numbers from a seeded Generator, so that every run of the
notebook gives the same results (see Generating Random Numbers).
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.integrate import quad, solve_ivp
from scipy.optimize import brentq
rng = np.random.default_rng(37830)Random walks and diffusion¶
A simple random walk starts at 0 and moves one step left or right with equal probability at each time.
NumPy simulates many independent walkers at once: draw a matrix of steps, one row per walker, and take cumulative sums along the rows.
walkers, steps = 10_000, 1000
X = np.cumsum(rng.choice([-1, 1], size=(walkers, steps)), axis=1)
n = np.arange(1, steps + 1)
plt.figure(figsize=(8, 4))
plt.plot(n, X[:20].T, lw=0.7)
plt.plot(n, 2 * np.sqrt(n), 'k--', n, -2 * np.sqrt(n), 'k--')
plt.xlabel('step $n$')
plt.ylabel('position')
plt.title(r'20 random walks and $\pm 2\sqrt{n}$')
plt.show()
for k in [10, 100, 1000]:
print(f"after {k:4d} steps: mean {X[:, k - 1].mean():+6.2f}, variance {X[:, k - 1].var():7.1f}")The steps are independent with mean 0 and variance 1, so after steps the position has mean 0 and variance . A typical walker is about from the start.
Now shrink the steps. Move by every , with for a constant . At time the position has variance , and by the central limit theorem it is approximately normal. Its density is therefore
the heat kernel, the solution of the diffusion equation that starts from a point source. The diffusion equation describes the density of a cloud of random walkers.
D, dt = 0.5, 1e-3
dx = np.sqrt(2 * D * dt)
positions = dx * X # the same walks, with steps of size dx every dt
x = np.linspace(-3, 3, 300)
plt.figure(figsize=(7, 4))
for k in [50, 200, 1000]:
t = k * dt
plt.hist(positions[:, k - 1], bins=50, density=True, alpha=0.4, label=f'walkers, $t = {t:g}$')
plt.plot(x, np.exp(-x**2 / (4 * D * t)) / np.sqrt(4 * np.pi * D * t), 'k')
plt.xlim(-2, 2)
plt.xlabel('$x$')
plt.legend()
plt.title('random walkers and the heat kernel (black)')
plt.show()Brownian motion and stochastic differential equations¶
The limit of the scaled random walk (with ) is Brownian motion : it starts at , and its increments over disjoint time intervals are independent with
To simulate on a grid, add up independent increments. Below we draw one path on a fine grid of 214 steps and add up its increments in blocks to see the same path on coarser grids.
T, nfine = 1.0, 2**14
dW_fine = np.sqrt(T / nfine) * rng.standard_normal(nfine)
plt.figure(figsize=(8, 4))
styles = {2**14: dict(color='0.6', lw=0.5), 2**8: dict(color='C0', lw=1), 2**4: dict(color='C3', marker='o', ms=3)}
for m, style in styles.items():
dW = dW_fine.reshape(m, nfine // m).sum(axis=1) # increments over the coarse steps
W = np.concatenate([[0], np.cumsum(dW)])
plt.plot(np.linspace(0, T, m + 1), W, label=f'{m} steps', **style)
print(f"{m:6d} steps: sum |dW| = {np.sum(np.abs(dW)):6.2f}, sum dW^2 = {np.sum(dW**2):.4f}")
plt.xlabel('$t$')
plt.ylabel('$W(t)$')
plt.legend()
plt.title('one Brownian path, seen on three grids')
plt.show()Refining the grid reveals more and more wiggles. The total distance travelled, , grows like without bound, because each increment has size about , which is much larger than when the step is small. Brownian paths are continuous but nowhere differentiable.
The sum of the squared increments, converges to : each has mean and variance , so the sum has mean and a variance that vanishes as .
Since has no derivative, a noisy ODE can’t be written with . Instead we write a stochastic differential equation (SDE)
with a deterministic drift and a diffusion coefficient that scales the noise. The simplest numerical method is Euler-Maruyama, forward Euler with a random increment added at each step:
def euler_maruyama(a, b, x0, T, nsteps, npaths, rng):
"""
Euler-Maruyama for dX = a(X, t) dt + b(X, t) dW, simulating npaths paths at once
returns times t (nsteps + 1,) and paths X (npaths, nsteps + 1)
"""
dt = T / nsteps
t = dt * np.arange(nsteps + 1)
X = np.empty((npaths, nsteps + 1))
X[:, 0] = x0
for n in range(nsteps):
dW = np.sqrt(dt) * rng.standard_normal(npaths)
X[:, n + 1] = X[:, n] + a(X[:, n], t[n]) * dt + b(X[:, n], t[n]) * dW
return t, XExample:¶
a simple SDE with interesting behavior: the drift pulls back toward 0 while the noise kicks it around. It models the velocity of a particle in a fluid, slowed down by friction and pushed by molecular collisions. The mean decays like , and in the long run settles into a stationary distribution, the normal distribution with variance .
theta, sigma, x0 = 1.0, 0.5, 2.0
t, X = euler_maruyama(lambda x, t: -theta * x, lambda x, t: sigma,
x0, T=5.0, nsteps=500, npaths=5000, rng=rng)
fig, ax = plt.subplots(1, 2, figsize=(13, 4))
ax[0].plot(t, X[:10].T, lw=0.7)
ax[0].plot(t, X.mean(axis=0), 'k', lw=2, label='sample mean')
ax[0].plot(t, x0 * np.exp(-theta * t), 'r--', lw=2, label=r'$x_0 e^{-\theta t}$')
ax[0].set_xlabel('$t$')
ax[0].legend()
ax[0].set_title('Ornstein-Uhlenbeck paths')
stationary = stats.norm(0, sigma / np.sqrt(2 * theta))
xs = np.linspace(-1.5, 1.5, 200)
ax[1].hist(X[:, -1], bins=50, density=True, alpha=0.5, label='$X(5)$, 5000 paths')
ax[1].plot(xs, stationary.pdf(xs), 'k', label='stationary density')
ax[1].legend()
ax[1].set_title('distribution at $t = 5$')
plt.show()
print(f"sample variance at t = 5: {X[:, -1].var():.4f}, "
f"stationary variance sigma^2 / (2 theta) = {sigma**2 / (2 * theta):.4f}")The Fokker-Planck equation¶
Where does the stationary distribution come from? The density of the solution of satisfies the Fokker-Planck equation
a drift-diffusion PDE. With and it is the diffusion equation of the random walkers above. A stationary density has . In one dimension, integrating once (with no probability flowing in from infinity) gives , whose solution is
provided the right side is integrable.
How accurate is Euler-Maruyama?¶
For SDEs there are two different questions, and they have different answers.
Strong error, , asks how close the computed path is to the exact path driven by the same Brownian motion. Euler-Maruyama has strong order 1/2.
Weak error, , only asks about statistics of the solution, such as its mean or variance. Euler-Maruyama has weak order 1.
Most applications need only weak accuracy. To measure either we need an exact solution. Geometric Brownian motion, the standard model for a stock price,
has the exact solution
To measure the strong error, the coarse and the exact solution must see the same Brownian path. We generate the increments on a fine grid and add them up in blocks to get the increments for each coarser step.
mu, sigma, S0, T = 0.05, 0.4, 1.0, 1.0
npaths, nfine = 10_000, 2**9
dW_fine = np.sqrt(T / nfine) * rng.standard_normal((npaths, nfine))
S_exact = S0 * np.exp((mu - sigma**2 / 2) * T + sigma * dW_fine.sum(axis=1))
nsteps_list = 2 ** np.arange(1, 9)
strong = []
for m in nsteps_list:
dW = dW_fine.reshape(npaths, m, nfine // m).sum(axis=2) # same path, coarser steps
S = np.full(npaths, S0)
for j in range(m):
S = S + mu * S * (T / m) + sigma * S * dW[:, j]
strong.append(np.mean(np.abs(S - S_exact)))
dts = T / nsteps_list
order = np.polyfit(np.log(dts), np.log(strong), 1)[0]
plt.figure(figsize=(6, 4))
plt.loglog(dts, strong, 'o-', label=f'strong error (slope {order:.2f})')
plt.loglog(dts, strong[-1] * np.sqrt(dts / dts[-1]), 'k--', label=r'$\Delta t^{1/2}$')
plt.xlabel(r'$\Delta t$')
plt.legend()
plt.title('strong convergence of Euler-Maruyama')
plt.show()For the weak error we don’t need matching paths, only an exact expectation. For geometric Brownian motion . We estimate from a million independent paths and show the Monte Carlo uncertainty (two standard errors) with error bars.
exact_second_moment = S0**2 * np.exp((2 * mu + sigma**2) * T)
npaths = 10**6
nsteps_list = 2 ** np.arange(0, 7)
bias, half_width = [], []
for m in nsteps_list:
S = np.full(npaths, S0)
for _ in range(m):
S += mu * S * (T / m) + sigma * S * np.sqrt(T / m) * rng.standard_normal(npaths)
bias.append(abs(np.mean(S**2) - exact_second_moment))
half_width.append(2 * np.std(S**2) / np.sqrt(npaths))
dts = T / nsteps_list
plt.figure(figsize=(6, 4))
plt.errorbar(dts, bias, yerr=half_width, fmt='o-', capsize=3, label=r'$|E[S_N^2] - E[S(T)^2]|$')
plt.loglog(dts, bias[0] * dts / dts[0], 'k--', label=r'$\Delta t$')
plt.xscale('log')
plt.yscale('log')
plt.xlabel(r'$\Delta t$')
plt.legend()
plt.title('weak error, with 2 standard errors of Monte Carlo noise')
plt.show()The weak error decreases like until it meets the Monte Carlo noise, after which the estimate is just noise.
Langevin dynamics as a sampler¶
The overdamped Langevin equation
describes a particle sliding downhill on a potential while being kicked by thermal noise at inverse temperature . The Fokker-Planck formula with and shows that its stationary distribution is the Boltzmann distribution, with density proportional to .
Take the double well , with minima at and a barrier of height 1 between them, and run ten thousand particles to .
V = lambda x: (x**2 - 1)**2
dV = lambda x: 4 * x * (x**2 - 1)
beta, dt = 1.0, 0.01
Xw = rng.choice([-1.0, 1.0], size=10_000)
for _ in range(3000):
Xw = Xw - dV(Xw) * dt + np.sqrt(2 * dt / beta) * rng.standard_normal(Xw.size)
Z = quad(lambda x: np.exp(-beta * V(x)), -np.inf, np.inf)[0]
xs = np.linspace(-2, 2, 300)
plt.figure(figsize=(7, 4))
plt.hist(Xw, bins=60, density=True, alpha=0.5, label='Langevin, $t = 30$')
plt.plot(xs, np.exp(-beta * V(xs)) / Z, 'k', label=r'$e^{-\beta V(x)} / Z$')
plt.xlabel('$x$')
plt.legend()
plt.title(r'sampling the double well, $\beta = 1$')
plt.show()
exact_x2 = quad(lambda x: x**2 * np.exp(-beta * V(x)), -np.inf, np.inf)[0] / Z
print(f"E[X^2]: Langevin {np.mean(Xw**2):.4f}, exact {exact_x2:.4f}")At low temperature (large ) a particle spends long stretches in one well before a rare large kick carries it over the barrier. The rate of these transitions falls off like , where is the barrier height.
def langevin_path(beta, x0, dt, nsteps, rng):
"""
one Euler-Maruyama path of the overdamped Langevin equation in the double well
"""
x = np.empty(nsteps + 1)
x[0] = x0
noise = np.sqrt(2 * dt / beta) * rng.standard_normal(nsteps)
for n in range(nsteps):
x[n + 1] = x[n] - dV(x[n]) * dt + noise[n]
return x
dt, nsteps = 0.01, 50_000
t = dt * np.arange(nsteps + 1)
fig, ax = plt.subplots(2, 1, figsize=(10, 5), sharex=True)
for a, b in zip(ax, [1.0, 4.0]):
a.plot(t, langevin_path(b, -1.0, dt, nsteps, rng), lw=0.4)
a.set_ylabel('$x$')
a.set_title(f'$\\beta = {b}$')
ax[1].set_xlabel('$t$')
plt.tight_layout()
plt.show()At the particle hops between the wells only occasionally, and stays in one well for tens of time units at a time. An average computed from this path converges slowly, because the path needs many hops to learn the relative weights of the two wells. The same problem afflicts MCMC, and much of the work on sampling algorithms is about getting across barriers faster.
Discrete stochastic models: the Gillespie algorithm¶
When the number of individuals is small, randomness in when individual events happen matters. Consider an epidemic in a population of people, divided into susceptible (), infected (), and recovered (). Two kinds of events happen:
infection, , at rate ;
recovery, , at rate .
Treating the counts as continuous gives the SIR model of ODEs,
Gillespie’s algorithm simulates the random events exactly. If the events have rates (“propensities”) with total , then the waiting time until the next event is exponentially distributed with rate , and the event is of type with probability . Draw both, update the state, and repeat. There is no time step, so there is no discretization error.
def gillespie_sir(N, I0, beta, gamma, rng):
"""
exact stochastic simulation of the SIR model until the epidemic dies out
returns event times, the number infected after each event, and the final number recovered
"""
S, I, R = N - I0, I0, 0
t = 0.0
times, infected = [0.0], [I0]
while I > 0:
a_infect = beta * S * I / N
a_recover = gamma * I
a_total = a_infect + a_recover
t += rng.exponential(1 / a_total) # waiting time to the next event
if rng.random() * a_total < a_infect: # which event happened
S, I = S - 1, I + 1
else:
I, R = I - 1, R + 1
times.append(t)
infected.append(I)
return np.array(times), np.array(infected), R
N, beta, gamma = 1000, 2.0, 1.0
ode = solve_ivp(lambda t, y: [-beta * y[0] * y[1] / N, beta * y[0] * y[1] / N - gamma * y[1]],
(0, 15), [N - 10, 10], t_eval=np.linspace(0, 15, 300), rtol=1e-8)
plt.figure(figsize=(8, 4))
for _ in range(20):
times, infected, _ = gillespie_sir(N, 10, beta, gamma, rng)
plt.step(times, infected, where='post', lw=0.7, alpha=0.8)
plt.plot(ode.t, ode.y[1], 'k', lw=2.5, label='ODE model')
plt.xlim(0, 15)
plt.xlabel('time (in units of the infectious period)')
plt.ylabel('number infected')
plt.legend()
plt.title('20 stochastic epidemics, N = 1000, 10 initially infected')
plt.show()The stochastic epidemics have the same shape as the ODE solution but peak at random times, because the early phase, when only a few people are infected, is dominated by chance.
Starting from a single infected person, chance can end the epidemic right away. Early on, the epidemic is a branching process in which each infected person infects others at rate and recovers at rate . The theory of branching processes says that the probability that it dies out before becoming a major outbreak is , where is the basic reproduction number. If it does take off, the fraction of the population eventually infected solves the final size equation . We check both.
N, runs = 500, 1000
start = time.perf_counter()
final_sizes = np.array([gillespie_sir(N, 1, beta, gamma, rng)[2] for _ in range(runs)])
elapsed = time.perf_counter() - start
R0 = beta / gamma
minor = final_sizes < 0.1 * N
z = brentq(lambda z: z - 1 + np.exp(-R0 * z), 1e-6, 1)
print(f"{runs} epidemics simulated in {elapsed:.2f} s")
print(f"fraction that died out early: {minor.mean():.3f} (theory 1/R0 = {1 / R0:.3f})")
print(f"mean final size of major outbreaks: {final_sizes[~minor].mean() / N:.3f} "
f"(final size equation: {z:.3f})")
plt.figure(figsize=(6, 3.5))
plt.hist(final_sizes / N, bins=50)
plt.xlabel('fraction of the population ever infected')
plt.ylabel('number of runs')
plt.title('final sizes of 1000 epidemics starting from one case')
plt.show()Both predictions hold up. The distribution of final sizes is bimodal: an epidemic either fizzles out after a few cases or infects about 80% of the population. The ODE model, which predicts a major outbreak every time, misses the first possibility entirely.
Tau-leaping¶
Gillespie’s algorithm simulates every single event, so its cost grows with the population. An epidemic in a city of a million people takes millions of passes through a Python loop. It also simulates one run at a time, because every run has its own random event times.
Tau-leaping takes fixed time steps and assumes that the rates barely change during a step, so that the number of events of type in the step is Poisson distributed with mean . With fixed time steps, NumPy can advance many runs at once.
def tau_leap_sir(N, I0, beta, gamma, tau, nruns, rng, t_max=200.0):
"""
tau-leaping simulation of nruns SIR epidemics at once, until all of them die out or t_max
returns the number of people ever infected in each run
"""
S = np.full(nruns, N - I0)
I = np.full(nruns, I0)
t = 0.0
while I.any() and t < t_max:
infections = np.minimum(rng.poisson(beta * S * I / N * tau), S) # can't infect more than S
recoveries = np.minimum(rng.poisson(gamma * I * tau), I)
S, I = S - infections, I + infections - recoveries
t += tau
return N - S
start = time.perf_counter()
final_tau = tau_leap_sir(N, 1, beta, gamma, tau=0.05, nruns=runs, rng=rng)
elapsed_tau = time.perf_counter() - start
print(f"{runs} epidemics in {elapsed_tau:.3f} s with tau-leaping, {elapsed:.2f} s with Gillespie")
print(f"fraction that died out early: {np.mean(final_tau < 0.1 * N):.3f} with tau-leaping, "
f"{minor.mean():.3f} with Gillespie")
bins = np.linspace(0, 1, 51)
plt.figure(figsize=(6, 3.5))
plt.hist(final_sizes / N, bins=bins, alpha=0.5, label='Gillespie')
plt.hist(final_tau / N, bins=bins, alpha=0.5, label=r'tau-leaping, $\tau = 0.05$')
plt.xlabel('fraction of the population ever infected')
plt.ylabel('number of runs')
plt.legend()
plt.show()The two methods give nearly the same distribution of outcomes, and tau-leaping is much faster. The price is an error that grows with , since the rates are frozen during each step.
The Gillespie algorithm assumes a well-mixed population, in which everybody is equally likely to meet everybody else. Agent-Based Models drop that assumption and track individuals with their own positions, contacts, or behaviors.
Exercises¶
Exercise 1¶
Simulate 5000 random walks in two dimensions, with independent normal steps of variance in each coordinate. Plot the mean squared distance from the origin against time and compare with . Then estimate the distribution of the first time a walker reaches distance 1 from the origin.
# Your code here