Module contents
Lesson 5 of 27Core 95 min

Exact and approximate stochastic simulation: Gillespie, tau-leaping and agents

Model intrinsic fluctuations in small populations with the chemical master equation, Gillespie simulation, tau-leaping, chemical Langevin dynamics and agent-based models.

After this lesson you can

  • Formulate a reaction system as a continuous-time Markov chain and write its chemical master equation.
  • Implement Gillespie's direct algorithm and check it against an exact master-equation solution in a small case.
  • Implement tau-leaping with step control and explain when it produces negative populations.
  • Derive the chemical Langevin equation and relate jump, diffusion and ODE levels to system size.
  • Design a simple agent-based model and measure outputs with replicates and error bars.

Before you start

When individuals matter

In a cell with few molecules or at the beginning of an outbreak, one reaction or recovery appreciably changes the state. An ODE for concentrations can describe a useful mean while hiding extinction probability. The choice between deterministic and stochastic descriptions depends on the question and scale, not on whether a curve looks smooth.

A network has count state X∈NdX\in\mathbb N^d, stoichiometric vectors νj\nu_j and propensities aj(x)a_j(x). Over a short interval, the probability of reaction jj is aj(x)  ⁣dt+o( ⁣dt)a_j(x)\,\dd t+o(\dd t). For A→BA\to B, ν=(−1,1)\nu=(-1,1) and one can take a(x)=kxAa(x)=k x_A. For 2A→B2A\to B, the number of unordered pairs is xA(xA−1)/2x_A(x_A-1)/2: the stochastic constant must use that convention and the corresponding volume scale.

The chemical master equation expresses probability balance for a continuous-time Markov chain:

 ⁣dP(x,t) ⁣dt=∑j[aj(x−νj)P(x−νj,t)−aj(x)P(x,t)].\frac{\dd P(x,t)}{\dd t}=\sum_j\bigl[a_j(x-\nu_j)P(x-\nu_j,t)-a_j(x)P(x,t)\bigr].

Terms outside the state space are taken to be zero. In a finite space, p˙=Qp\dot p=Qp and p(t)=eQtp(0)p(t)=e^{Qt}p(0), using columns that sum to zero here. To truncate an infinite space, escaping probability can be sent to an absorbing state: its mass quantifies loss from the finite projection without silently making it disappear.

For immigration ∅→X\varnothing\to X at constant rate kk and death X→∅X\to\varnothing at rate γX\gamma X, stationary balance between neighboring states gives πn+1γ(n+1)=πnk\pi_{n+1}\gamma(n+1)=\pi_n k. Iterating and normalizing gives πn=e−k/γ(k/γ)n/n!\pi_n=e^{-k/\gamma}(k/\gamma)^n/n!. Stationary mean and variance equal k/γk/\gamma. Starting from zero, the mean still changes with time: m(t)=(k/γ)(1−e−γt)m(t)=(k/\gamma)(1-e^{-\gamma t}). Equilibrium is not the expected value at every instant.

The lab matrix contains states 0,…,300,\dots,30 and a sink. A trajectory leaving that set remains in the sink even if the infinite chain could later return. Its mass is therefore a conservative bound on probability affected by truncation, not a physical description of that exit. Increasing the limit and checking that the mass decreases is part of validation.

Gillespie: two draws per event

With propensities constant between jumps, the total rate is a0=∑jaja_0=\sum_j a_j. Survival without reaction until tt satisfies S(t+h)=S(t)(1−a0h)+o(h)S(t+h)=S(t)(1-a_0h)+o(h); therefore S(t)=e−a0tS(t)=e^{-a_0t}. Conditional on an event occurring, the probability of channel jj is aj/a0a_j/a_0, independent of waiting time. The Gillespie direct algorithm draws an exponential wait, chooses the channel and updates the state. If a0=0a_0=0, the state is absorbing.

InteractiveGillespie step by step
  • A
  • B

Network A→B at rate 0.2A and B→A at rate 0.1B; total A+B=30 is conserved.

12
17
Current time2.194
A, B13, 17
Propensities A→B, B→A2.60, 1.70
Next wait0.6399
Next reactionA→B
Next event uniform draws0.0638, 0.0639
Advance event by event in the reversible A↔B network. The bar shows propensities and readouts show both uniform draws, the wait and next reaction; the trajectory is stepwise.

The method is exact for the chain defined by the propensities, apart from numerical and random-generator errors; it does not imply that the chain is a perfect physical model. The Gibson-Bruck next-event method reorganizes reaction clocks and updates dependencies to improve efficiency in sparse networks; it aims to simulate the same chain with a different computational organization.

The direct procedure needs two independent uniform numbers. With U1U_1 in (0,1)(0,1), τ=−log⁡U1/a0\tau=-\log U_1/a_0 has the correct waiting distribution. A second uniform chooses the first channel whose cumulative sum exceeds U2a0U_2a_0. State values on an observation grid use the latest preceding event: a straight line between events would invent fractional states and change temporal statistics. A seed makes one realization repeatable, but one seed does not estimate variability between realizations.

Approximate jumps and diffusion

Tau-leaping freezes propensities over an interval τ\tau and draws independent counts Kj∼Poisson⁡(aj(x)τ)K_j\sim\operatorname{Poisson}(a_j(x)\tau), with update X←X+∑jνjKjX\leftarrow X+\sum_j\nu_jK_j. The approximation requires propensities not to change too much during the leap. A large τ\tau can consume more individuals than available. Limiting the step by drift and variance helps but does not itself guarantee positivity; rejection and step reduction or binomial variants are options with their own biases and constraints.

In the code, drift μi=∑jνjiaj\mu_i=\sum_j\nu_{ji}a_j and instantaneous variance vi=∑jνji2ajv_i=\sum_j\nu_{ji}^2a_j are calculated for each species. τ\tau is bounded using εmax⁡(Xi,1)/∣μi∣\varepsilon\max(X_i,1)/|\mu_i| and (εmax⁡(Xi,1))2/vi(\varepsilon\max(X_i,1))^2/v_i when denominators are positive, plus a global maximum. This rule is a specific heuristic, not a rigorous bound on distribution error. If a proposal is still negative, it is rejected, the step is halved and a new sample is drawn. Near depletion or rapid changes, SSA may be preferable.

InteractiveWhen tau-leaping overshoots
  • Exact death
  • Tau-leaping

Process X→∅, rate X, X(0)=8 and horizon 1. These are 1000 replicates with fixed seeds; the exact reference uses independent survival of each individual. Endpoint −8 groups smaller values. Rejection changes the approximate law.

0.8
Negative tau fraction0.188
Tau mean1.182
Exact mean2.943
Rejected leaps0
Compare 1000 replicates of exact death and tau-leaping. Enable adaptive steps with rejection: negative counts disappear in this implementation, but not all approximation error does.

If each channel undergoes many reactions over an interval where its propensities change little, the normal approximation to Poisson formally leads to the chemical Langevin equation:

 ⁣dX=∑jνjaj(X)  ⁣dt+∑jνjaj(X)  ⁣dWj.\dd X=\sum_j\nu_j a_j(X)\,\dd t+\sum_j\nu_j\sqrt{a_j(X)}\,\dd W_j.

The WjW_j are independent. The continuous approximation can produce negative values and fail near boundaries or sparse populations; clipping does not restore the exact law. Under suitable scaling with size Ω\Omega, relative fluctuations of numerous reactions often decrease as Ω−1/2\Omega^{-1/2} and an ODE for concentrations emerges. The scaling assumption matters: a slowly changing discrete variable can retain macroscopic noise.

InteractiveJumps, diffusion and ODE
  • SSA
  • Hybrid Langevin
  • ODE mean

Gene off/on switches at rate 0.08; production is 0.05Ω or Ω and degradation is X. The CLE keeps the gene discrete with steps of 0.1, approximates switches per step and clips negative values; the ODE gives the mean. Frequencies use correlated time samples after t=40, not independent replicates; the last bin groups values from 1.5 onward. The gene signal persists with Ω: a hybrid CLE can also show two modes.

40
Negative CLE clips24
Horizon200
CLE step0.1
A discrete genetic switch controls molecule production. An SSA trajectory, hybrid Langevin approximation and deterministic mean are shown; time frequencies are not independent replicates.

In this figure the gene remains discrete as Ω\Omega increases. A trajectory therefore need not approach the ODE mean, and hybrid diffusion can also retain bimodality. The displayed CLE approximates switching by steps and clips negative values; the counter reports those clips. The histogram uses one trajectory after discarding a transient: its correlation limits conclusions about the stationary distribution.

Lab: networks, master equation and outbreaks

The simulator takes one stoichiometric row per reaction and a propensity function. Sampling on a time grid retains the latest state rather than interpolating between jumps, and requires the simulated horizon to reject later queries. Adaptive tau limits the step using drift and variance, rejects negative proposals and reduces τ\tau; rejection changes the approximate distribution and does not guarantee exactness.

[ ]Generic SSA and tau-leapingBrowser
import numpy as np
def _validate(x0,stoich,t_end):
    rawx=np.asarray(x0);rawS=np.asarray(stoich)
    if not np.all(np.isfinite(rawx)) or not np.all(np.isfinite(rawS)) or np.any(rawx!=np.floor(rawx)) or np.any(rawS!=np.floor(rawS)): raise ValueError('se requieren conteos enteros')
    x=rawx.astype(int).copy();S=rawS.astype(int)
    if x.ndim!=1 or S.ndim!=2 or S.shape[1]!=len(x) or np.any(x<0) or not np.isfinite(t_end) or t_end<0: raise ValueError('dimensiones o estado inválidos')
    return x,S
def _rates(propensities,x,S):
    a=np.asarray(propensities(x),dtype=float)
    if a.shape!=(len(S),) or np.any(a<0) or not np.all(np.isfinite(a)): raise ValueError('propensiones inválidas')
    if np.any((a>0)&np.any(x+S<0,axis=1)): raise ValueError('una reacción habilitada produce población negativa')
    return a
def gillespie(x0,stoich,propensities,t_end,rng,max_events=1000000):
    x,S=_validate(x0,stoich,t_end);t=0.;times=[t];states=[x.copy()]
    for _ in range(max_events):
        a=_rates(propensities,x,S);a0=a.sum()
        if a0==0: break
        wait=rng.exponential(1/a0)
        if t+wait>t_end: break
        reaction=min(np.searchsorted(np.cumsum(a),rng.random()*a0,side='right'),len(a)-1)
        t+=wait;x=x+S[reaction];times.append(t);states.append(x.copy())
    else: raise RuntimeError('límite de eventos alcanzado')
    return np.asarray(times),np.asarray(states)
def sample_path(times,states,grid,t_end):
    grid=np.asarray(grid)
    if np.any(grid>t_end): raise ValueError('tiempo posterior al horizonte simulado')
    idx=np.searchsorted(times,grid,side='right')-1
    if np.any(idx<0): raise ValueError('tiempo anterior al estado inicial')
    return states[idx]
def tau_leap(x0,stoich,propensities,t_end,rng,tau_max=.2,epsilon=.1,max_steps=1000000):
    x,S=_validate(x0,stoich,t_end);t=0.;times=[t];states=[x.copy()];rejections=0
    if tau_max<=0 or epsilon<=0: raise ValueError('parámetros inválidos')
    for _ in range(max_steps):
        if t>=t_end: break
        a=_rates(propensities,x,S)
        if a.sum()==0: break
        mu=a@S;var=a@(S*S);limit=epsilon*np.maximum(x,1)
        candidates=[tau_max,t_end-t]
        candidates.extend((limit[np.abs(mu)>0]/np.abs(mu[np.abs(mu)>0])).tolist())
        candidates.extend(((limit[var>0]**2)/var[var>0]).tolist())
        tau=min(candidates)
        for attempt in range(30):
            proposed=x+rng.poisson(a*tau)@S
            if np.all(proposed>=0): break
            tau/=2;rejections+=1
        else: raise RuntimeError('rechazos excesivos; usa SSA')
        if tau<=np.finfo(float).eps*max(1.,t): raise RuntimeError('paso demasiado pequeño; usa SSA')
        t+=tau;x=proposed;times.append(t);states.append(x.copy())
    else: raise RuntimeError('límite de pasos alcanzado')
    return np.asarray(times),np.asarray(states),rejections

For birth at rate 4 and death at rate 0.5X0.5X, starting at zero, X(2)X(2) has a Poisson law with mean 8(1−e−1)8(1-e^{-1}). The next cell constructs a finite generator with an absorbing state for exits above 30 and compares its distribution with SSA.

[ ]Master equation versus SSABrowser
from scipy.linalg import expm
N=30;Q=np.zeros((N+2,N+2))
for x in range(N+1):
    Q[x+1 if x<N else N+1,x]+=4;Q[x,x]-=4
    if x: Q[x-1,x]+=.5*x;Q[x,x]-=.5*x
p=expm(2*Q)[:,0];S=np.array([[1],[-1]])
def birth_death(x): return np.array([4.,.5*x[0]])
rng=np.random.default_rng(104)
samples=np.array([gillespie([0],S,birth_death,2.,rng)[1][-1,0] for _ in range(1500)])
mean=8*(1-np.exp(-1))
print('media y varianza SSA:',samples.mean(),samples.var(),'media exacta:',mean)
print('media FSP:',np.arange(N+1)@p[:-1],'masa absorbida:',p[-1])

The empirical mean varies between samples; its Monte Carlo uncertainty decreases as replicates increase. Absorbed mass shows how much of the truncated chain exited the domain at any time, not merely how much remains outside at the end.

To compare distributions, close means are insufficient: also examine variance, tail probabilities and effects of changing horizon or truncation. Cell trajectories are independent because they share a generator that advances between calls, not because the same seed is reset for each replicate. Resetting the same seed every time would repeat the same trajectory and give a false impression of precision.

[ ]Positivity of an approximationBrowser
rng=np.random.default_rng(78); rejected=0;minimum=10**9
for _ in range(100):
    t,x,n=tau_leap([2],S,birth_death,3.,rng,tau_max=.5,epsilon=.2)
    minimum=min(minimum,int(x.min()));rejected+=n
print('mínimo observado:',minimum,'propuestas rechazadas:',rejected)

The jump SIR model has infection rate βSI/N\beta SI/N and recovery rate γI\gamma I. Here a “small outbreak” means not reaching ten simultaneous infections before t=100t=100; this is an operational definition, not a synonym for all eventual extinction.

[ ]Stochastic outbreak versus the ODEBrowser
from scipy.integrate import solve_ivp
N=100;beta=.5;gamma=.2;S_sir=np.array([[-1,1,0],[0,-1,1]])
def rates_sir(x): return np.array([beta*x[0]*x[1]/N,gamma*x[1]])
rng=np.random.default_rng(2026);small=[]
for _ in range(200):
    times,states=gillespie([98,2,0],S_sir,rates_sir,100.,rng)
    small.append(np.max(states[:,1])<10)
fraction=np.mean(small);se=np.sqrt(fraction*(1-fraction)/len(small))
def sir_ode(t,x):
    infection=beta*x[0]*x[1]/N;recovery=gamma*x[1]
    return [-infection,infection-recovery,recovery]
sol=solve_ivp(sir_ode,(0,100),[98,2,0],dense_output=True,rtol=1e-8,atol=1e-10)
if not sol.success: raise RuntimeError(sol.message)
print('fracción de brotes pequeños y error estándar:',fraction,se)
print('máximo de infectados en la EDO:',sol.sol(np.linspace(0,100,1001))[1].max())

Agents and replication

An agent-based model specifies states and local rules for individuals. Contact network, heterogeneity and update order can change the result even if aggregate averages are preserved. The next synthetic model uses a ring of 80 agents, two initial infections and simultaneous daily updates: each infected agent attempts to infect both neighbors and recovers with fixed probability. It is not the same model as the well-mixed SIR above.

[ ]Agent replicates on a ringBrowser
import numpy as np
def agents(rng,n=80,days=100,p=.25,recover=.15):
    state=np.zeros(n,dtype=int);state[rng.choice(n,2,replace=False)]=1
    for _ in range(days):
        infected=np.flatnonzero(state==1)
        if not len(infected): break
        newly=np.zeros(n,dtype=bool)
        for i in infected:
            for j in ((i-1)%n,(i+1)%n):
                if state[j]==0 and rng.random()<p: newly[j]=True
        removed=infected[rng.random(len(infected))<recover]
        state[newly]=1;state[removed]=2
    return np.count_nonzero(state!=0)
rng=np.random.default_rng(314);sizes=np.array([agents(rng) for _ in range(200)])
print('tamaño final medio y error estándar:',sizes.mean(),sizes.std(ddof=1)/np.sqrt(len(sizes)))
print('rango observado:',sizes.min(),sizes.max())

Standard error measures variation across replicates of these rules and seed, not uncertainty about a real population. Changing network, probabilities or simultaneity rule requires repeating the experiment. The direct method is derived in the original paper by Gillespie (1977); his 2001 work on tau-leaping details the approximation and its conditions.

The SIR result uses a binomial estimate p^\hat p and approximate standard error p^(1−p^)/R\sqrt{\hat p(1-\hat p)/R} from RR independent replicates. For probabilities near zero or one, use a suitable binomial interval rather than relying on a symmetric normal approximation. On the ring, repeated infections accumulate before states update; a newly infected agent cannot infect others until the next day. A sequential update within the day would be another model and could give another distribution.

Exercises

ProofThe two draws
Prove: Derive the wait and channel of the next reaction.
0
Between events a_j are constant and a₀ is their sum.

Step 1 of 3. What equation does S(t), the probability of no event, satisfy?

NumericStationary birth and death
If immigration occurs at rate 4 and each individual dies at rate 0.5, what is the stationary mean?
CodeA jump simulator
Implement gillespie(x0, stoich, propensities, t_end, rng), with one stoich row per channel. Return arrays (times, states), including the initial state; do not add an event occurring after t_end. Stop if the total rate is zero.
import numpy as np
def gillespie(x0,stoich,propensities,t_end,rng):
  pass
Shift+Enter to run
QuizChoose a level
There are very few molecules and extinction probability is required. Which description is most appropriate as a reference?
Key idea
SSA exactly simulates the chosen chain; tau-leaping and Langevin trade fidelity for cost under checkable assumptions. Agents add local structure and require replicates.