Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Stochastic Simulation

Open in Colab

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).

Random walks and diffusion

A simple random walk starts at 0 and moves one step left or right with equal probability 1/21/2 at each time.

NumPy simulates many independent walkers at once: draw a matrix of ±1\pm 1 steps, one row per walker, and take cumulative sums along the rows.

The steps are independent with mean 0 and variance 1, so after nn steps the position has mean 0 and variance nn. A typical walker is about n\sqrt n from the start.

Now shrink the steps. Move by ±Δx\pm\Delta x every Δt\Delta t, with Δx2=2D Δt\Delta x^2 = 2D\,\Delta t for a constant DD. At time tt the position has variance (t/Δt) Δx2=2Dt(t/\Delta t)\,\Delta x^2 = 2Dt, and by the central limit theorem it is approximately normal. Its density is therefore

u(x,t)=14πDt e−x2/(4Dt),u(x, t) = \frac{1}{\sqrt{4\pi D t}}\, e^{-x^2/(4Dt)},

the heat kernel, the solution of the diffusion equation ut=Duxxu_t = D u_{xx} that starts from a point source. The diffusion equation describes the density of a cloud of random walkers.

Brownian motion and stochastic differential equations

The limit of the scaled random walk (with D=1/2D = 1/2) is Brownian motion W(t)W(t): it starts at W(0)=0W(0) = 0, and its increments over disjoint time intervals are independent with

W(t+Δt)−W(t)∼N(0,Δt).W(t + \Delta t) - W(t) \sim \mathcal N(0, \Delta t).

To simulate WW on a grid, add up independent N(0,Δt)\mathcal N(0, \Delta t) 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.

Refining the grid reveals more and more wiggles. The total distance travelled, ∑∣ΔW∣\sum |\Delta W|, grows like n\sqrt{n} without bound, because each increment has size about Δt\sqrt{\Delta t}, which is much larger than Δt\Delta t when the step is small. Brownian paths are continuous but nowhere differentiable.

The sum of the squared increments, converges to TT: each ΔW2\Delta W^2 has mean Δt\Delta t and variance 2Δt22\Delta t^2, so the sum has mean TT and a variance 2TΔt2T\Delta t that vanishes as Δt→0\Delta t \to 0.

Since WW has no derivative, a noisy ODE can’t be written with dW/dtdW/dt. Instead we write a stochastic differential equation (SDE)

dX=a(X,t) dt+b(X,t) dW,dX = a(X, t)\, dt + b(X, t)\, dW,

with a deterministic drift aa and a diffusion coefficient bb that scales the noise. The simplest numerical method is Euler-Maruyama, forward Euler with a random increment added at each step:

Xn+1=Xn+a(Xn,tn) Δt+b(Xn,tn) ΔWn,ΔWn=Δt  ξn,ξn∼N(0,1).X_{n+1} = X_n + a(X_n, t_n)\,\Delta t + b(X_n, t_n)\,\Delta W_n, \qquad \Delta W_n = \sqrt{\Delta t}\;\xi_n, \quad \xi_n \sim \mathcal N(0, 1).

Example:

dX=−θX dt+σ dWdX = -\theta X\, dt + \sigma\, dW

a simple SDE with interesting behavior: the drift pulls XX 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 X0e−θtX_0 e^{-\theta t}, and in the long run XX settles into a stationary distribution, the normal distribution with variance σ2/(2θ)\sigma^2/(2\theta).

The Fokker-Planck equation

Where does the stationary distribution come from? The density p(x,t)p(x, t) of the solution of dX=a(X) dt+b(X) dWdX = a(X)\, dt + b(X)\, dW satisfies the Fokker-Planck equation

∂p∂t=−∂∂x(a p)+12∂2∂x2(b2 p),\frac{\partial p}{\partial t} = -\frac{\partial}{\partial x}\big(a\, p\big) + \frac12 \frac{\partial^2}{\partial x^2}\big(b^2\, p\big),

a drift-diffusion PDE. With a=0a = 0 and b=2Db = \sqrt{2D} it is the diffusion equation of the random walkers above. A stationary density has ∂p/∂t=0\partial p/\partial t = 0. In one dimension, integrating once (with no probability flowing in from infinity) gives a p=12(b2p)′a\,p = \frac12 (b^2 p)', whose solution is

p∞(x)∝1b(x)2exp⁡ ⁣(∫x2 a(y)b(y)2 dy),p_\infty(x) \propto \frac{1}{b(x)^2} \exp\!\left( \int^x \frac{2\, a(y)}{b(y)^2}\, dy \right),

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, E ∣XN−X(T)∣\mathbb E\,|X_N - X(T)|, 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, ∣Ef(XN)−Ef(X(T))∣|\mathbb E f(X_N) - \mathbb E f(X(T))|, 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,

dS=μS dt+σS dW,dS = \mu S\, dt + \sigma S\, dW,

has the exact solution

S(t)=S0exp⁡ ⁣((μ−σ22)t+σW(t)).S(t) = S_0 \exp\!\left( \left(\mu - \frac{\sigma^2}{2}\right) t + \sigma W(t) \right).

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.

For the weak error we don’t need matching paths, only an exact expectation. For geometric Brownian motion E[S(T)2]=S02 e(2μ+σ2)T\mathbb E[S(T)^2] = S_0^2\, e^{(2\mu + \sigma^2)T}. We estimate E[SN2]\mathbb E[S_N^2] from a million independent paths and show the Monte Carlo uncertainty (two standard errors) with error bars.

The weak error decreases like Δt\Delta t until it meets the Monte Carlo noise, after which the estimate is just noise.

Langevin dynamics as a sampler

The overdamped Langevin equation

dX=−V′(X) dt+2/β  dWdX = -V'(X)\, dt + \sqrt{2/\beta}\; dW

describes a particle sliding downhill on a potential VV while being kicked by thermal noise at inverse temperature β\beta. The Fokker-Planck formula with a=−V′a = -V' and b2=2/βb^2 = 2/\beta shows that its stationary distribution is the Boltzmann distribution, with density proportional to e−βV(x)e^{-\beta V(x)}.

Take the double well V(x)=(x2−1)2V(x) = (x^2 - 1)^2, with minima at ±1\pm 1 and a barrier of height 1 between them, and run ten thousand particles to t=30t = 30.

At low temperature (large β\beta) 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 e−β ΔVe^{-\beta\,\Delta V}, where ΔV\Delta V is the barrier height.

At β=4\beta = 4 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 NN people, divided into susceptible (SS), infected (II), and recovered (RR). Two kinds of events happen:

  • infection, S+I→2IS + I \to 2I, at rate βSI/N\beta S I / N;

  • recovery, I→RI \to R, at rate γI\gamma I.

Treating the counts as continuous gives the SIR model of ODEs,

S′=−βSI/N,I′=βSI/N−γI,R′=γI.S' = -\beta S I/N, \qquad I' = \beta S I / N - \gamma I, \qquad R' = \gamma I.

Gillespie’s algorithm simulates the random events exactly. If the events have rates (“propensities”) a1,…,ama_1, \dots, a_m with total a0=∑jaja_0 = \sum_j a_j, then the waiting time until the next event is exponentially distributed with rate a0a_0, and the event is of type jj with probability aj/a0a_j / a_0. Draw both, update the state, and repeat. There is no time step, so there is no discretization error.

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 β\beta and recovers at rate γ\gamma. The theory of branching processes says that the probability that it dies out before becoming a major outbreak is 1/R01/R_0, where R0=β/γR_0 = \beta/\gamma is the basic reproduction number. If it does take off, the fraction zz of the population eventually infected solves the final size equation z=1−e−R0zz = 1 - e^{-R_0 z}. We check both.

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 τ\tau and assumes that the rates barely change during a step, so that the number of events of type jj in the step is Poisson distributed with mean ajτa_j \tau. With fixed time steps, NumPy can advance many runs at once.

The two methods give nearly the same distribution of outcomes, and tau-leaping is much faster. The price is an error that grows with τ\tau, 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 2DΔt2D\Delta t in each coordinate. Plot the mean squared distance from the origin against time and compare with 4Dt4Dt. Then estimate the distribution of the first time a walker reaches distance 1 from the origin.