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
- 29Deterministic versus stochastic modelsCompartmental modelsErgodic statistics of a simulation
- 26Holding times and jump chainKolmogorov equations for CTMCsHomogeneous Poisson processStochastic differential equationEuler-Maruyama scheme
- 09Inverse transform samplingDiscrete-event simulationMonte Carlo error and confidence intervals
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 , stoichiometric vectors and propensities . Over a short interval, the probability of reaction is . For , and one can take . For , the number of unordered pairs is : 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:
Terms outside the state space are taken to be zero. In a finite space, and , 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 at constant rate and death at rate , stationary balance between neighboring states gives . Iterating and normalizing gives . Stationary mean and variance equal . Starting from zero, the mean still changes with time: . Equilibrium is not the expected value at every instant.
The lab matrix contains states 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 . Survival without reaction until satisfies ; therefore . Conditional on an event occurring, the probability of channel is , independent of waiting time. The Gillespie direct algorithm draws an exponential wait, chooses the channel and updates the state. If , the state is absorbing.
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 in , has the correct waiting distribution. A second uniform chooses the first channel whose cumulative sum exceeds . 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 and draws independent counts , with update . The approximation requires propensities not to change too much during the leap. A large 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 and instantaneous variance are calculated for each species. is bounded using and 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.
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:
The 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 , relative fluctuations of numerous reactions often decrease as and an ODE for concentrations emerges. The scaling assumption matters: a slowly changing discrete variable can retain macroscopic noise.
In this figure the gene remains discrete as 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 ; rejection changes the approximate distribution and does not guarantee exactness.
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),rejectionsFor birth at rate 4 and death at rate , starting at zero, has a Poisson law with mean . The next cell constructs a finite generator with an absorbing state for exits above 30 and compares its distribution with SSA.
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.
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 and recovery rate . Here a “small outbreak” means not reaching ten simultaneous infections before ; this is an operational definition, not a synonym for all eventual extinction.
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.
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 and approximate standard error from 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
Step 1 of 3. What equation does S(t), the probability of no event, satisfy?
import numpy as np
def gillespie(x0,stoich,propensities,t_end,rng):
pass