Algorithmcore
Gillespie algorithm
Also called stochastic simulation algorithm, Gillespie direct method.
Simulate the chemical master equation exactly: draw an exponential time to the next reaction from the total propensity, then pick the reaction.
- Time
- Θ(N (m + n)) expected
- Space
- Θ(n + m) extra
- Where
- N = the expected number of reaction events in the run; m = the number of reactions; n = the number of species
- Model
- Real RAM
- Properties
- randomizedexactrandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel T. Gillespie, 1976
The Gillespie algorithm draws one exact sample path of the jump process whose probabilities solve the chemical master equation. It does not solve the equation. It simulates the reactions one at a time: from the current molecule counts it draws the waiting time to the next reaction from an exponential law whose rate is the sum of all propensities, then picks which reaction fires with probability proportional to its propensity, applies it, and repeats. Every step uses two uniform random numbers and work for reactions. The paths have exactly the law of the master equation, so averages over many runs converge to the true moments and probabilities. This version is the direct method. Gillespie gave a second, equivalent version in the same 1976 paper, the first reaction method, and the next reaction method is a faster form of that one.
In plain words
A cell holds a few hundred molecules of a few kinds, and each kind of reaction happens now and then, at random. Reactions with more fuel around happen more often.
To play this forward, add up how eager all the reactions are right now. The bigger that total, the sooner something happens, so draw a random wait that is short on average when the total is large. Then decide what happened: spin a wheel where each reaction has a slice as wide as its eagerness. Change the counts as that reaction says, move the clock forward by the wait, and do it again.
Each run is one possible story of the cell. Run it many times and count how often each outcome turns up, and you get the chances that the exact equation would give.
The problem
Input. A network with species and reactions: for each reaction a change vector and a propensity function of the state . A start state , an end time , and a source of uniform random numbers. The propensities usually come from stochastic mass action: for a source, for , for , and for , with in the last case for a deterministic rate constant in molar units.
Output. The event times and the states just after them, such that the path has the same law as the Markov jump process of the chemical master equation on . The state at time is the last recorded state.
The next reaction density. Given , let be the time to the next reaction and the reaction. With ,
So is exponential with rate , with probability , and the two are independent. The direct method samples the two factors one after the other.
The algorithm
DIRECT-METHOD(x0, ν, a, T)- 1
t ← 0; x ← x0; record (0, x) - 2
loop - 3
compute a_j(x) for j = 1, ..., m and a0 ← a_1(x) + ... + a_m(x) - 4
if a0 = 0 then return the record - 5
τ ← -ln(1 - U1) / a0 with U1 uniform on [0, 1) - 6
if t + τ > T then return the record - 7
u ← U2 · a0 with U2 uniform on [0, 1) - 8
j ← the smallest index with a_1(x) + ... + a_j(x) > u - 9
t ← t + τ; x ← x + ν_j - 10
record (t, x)
Line L5 is inverse transform sampling of the exponential law. Line L8 is inverse transform sampling of the discrete law by a linear search over the cumulative sums. Line L6 discards the last waiting time: the process stays in until after , so is the state at , and the reaction is not fired.
Example
Take immigration-death: with propensity , and with propensity (rate 1 per molecule). Start from and use Python's random.Random(1).
| step | fires | after | after | ||||
|---|---|---|---|---|---|---|---|
| 1 | 10, 2 | 12 | 0.0120 | 10.1692 | 0.0120 | 1 | |
| 2 | 10, 1 | 11 | 0.1312 | 2.8058 | 0.1432 | 2 | |
| 3 | 10, 2 | 12 | 0.0570 | 5.3939 | 0.2002 | 3 | |
| 4 | 10, 3 | 13 | 0.0811 | 10.2534 | 0.2813 | 2 | |
| 5 | 10, 2 | 12 | 0.0082 | 0.3402 | 0.2895 | 3 | |
| 6 | 10, 3 | 13 | 0.1390 | 5.6260 | 0.4285 | 4 |
In step 1 the cumulative sums are 10 and 12, and falls in , so fires. In step 2 the sums are 10 and 11, and , so fires. The count drifts up toward the stationary mean 10.
To check a simulator, use networks with a known law. Pure death at rate 1 per molecule from 100 molecules gives Binomial, with mean 36.787944 and variance 23.254416. Immigration-death with rates 10 and 1 has the stationary law Poisson, and from , is Poisson$(10(1 - e^{-1})) = $ Poisson. The tests of the implementation compare the sample means and the histograms of many runs with these laws.
Correctness
The next reaction density follows from the definition of the propensity: the probability that nothing fires in satisfies , so , and then reaction fires in with probability . Line L5 gives with density , and line L8 gives with probability , independent of , so one step has the joint density . Each step uses fresh random numbers and depends on the past only through , which matches the strong Markov property of . By induction on the number of events, the recorded path has the law of on . The full proof is below.
Proof: The direct method samples the process of the chemical master equationfull
Fix a network with stoichiometric vectors and propensities , and write . The chemical master equation is the forward equation of the Markov jump process with these jump rates: in a state , the process waits an exponential time with rate , and then it jumps to with probability . We assume that this process does not explode on , that is, it makes finitely many jumps in with probability 1. This holds, for example, when the reachable states are finite, or when is bounded on them.
Lemma 1 (the next reaction density). Let the process be in state at time , with . Let be the time to the next reaction and the index of that reaction. Then has the joint density
Proof. In the jump process, reaction fires in with probability , given that the state is still . Let be the probability that no reaction fires in . Then , so with , and . The probability that the first reaction is and fires in is .
Lemma 2 (one step of the direct method). In state with , lines L5 to L8 return a pair with the density of Lemma 1.
Proof. Line L5 draws with density . Line L7 draws uniform on , independent of . Line L8 returns the first index with . Indices with add nothing to the sum, so they are never returned. For an index with , the event is the event , which has probability . So has the density .
Theorem. Run the direct method from up to . Let be the event times and the states that it records. Then the sequence has the same joint law as the jump times and the states after the jumps of on . In particular, the last recorded state has the law , the solution of the chemical master equation at time .
Proof. By induction on . Assume that has the law of the first jumps of (for there is nothing to prove). By the strong Markov property of at its -th jump time, the next waiting time and the next reaction of , given the past, have the density of Lemma 1, and they depend on the past only through . The direct method draws fresh random numbers in each step, so its next pair, given its past, has the density of Lemma 2, which is the same. So the first jumps have the same law.
If , then stays in for ever, and line L4 stops the run in : both agree.
Stopping at : line L6 discards a waiting time with and stops. In , the event that no reaction fires in has probability , so the two agree on the event that there is no further event before , and the state at is in both. Since does not explode on , the run stops after finitely many events with probability 1.
Remark (number of events). The number of events in is the number of jumps of in . For pure death with rate per molecule from , each molecule dies by time with probability , so the mean number of events is . For immigration-death at stationarity, births and deaths each fire at the mean rate , so the mean number of events in is .
Complexity
- Per event. Line L3 recomputes propensities, line L8 scans up to cumulative sums, and line L9 changes up to counts. So a step costs with a constant number of random numbers.
- Per run. The number of events is random. Its mean is , because events come at the rate . For pure death from at rate it is ; for immigration-death at stationarity it is , where is the immigration rate. The expected time is .
- Large networks. With a dependency graph, line L3 only updates the propensities that the last reaction changed, and is updated by the differences. The search in line L8 is then the bottleneck, per step; a tree of partial sums makes it .
- Space. for the state and the propensities, plus the record. Recording only the state on a fixed time grid keeps the output small.
- Systems with fast reactions. The cost is set by the number of events, not by the time span. A fast reversible reaction that fires times per second costs steps per simulated second even if its net effect is small.
Properties
- Exact. The paths have exactly the law of the jump process of the chemical master equation, up to the quality of the random numbers and floating point rounding. There is no step size and no bias.
- Randomized. Each run is one sample. Estimates of means and probabilities have Monte Carlo error of order for runs, by the central limit theorem.
- Two random numbers per event. One for the time and one for the reaction. A run with events uses numbers when it stops at , because the last waiting time is drawn and discarded.
- Same law, different paths. The first reaction method and the next reaction method give paths with the same law, but they use the random numbers in another way, so for the same seed they give different paths.
- Not tied to mass action. The proof uses only that the propensities depend on the current state. Any propensity function that is works, for example Hill functions of a reduced model, but then the result is only as good as the model.
Variants and improvements
- First reaction method. Draw one exponential clock per reaction and fire the one that rings first (first reaction method, Gillespie 1976). It is equivalent in law and slower when is large.
- Next reaction method. Keep the clocks of the reactions that did not fire, rescale them when their propensities change, and hold them in an indexed priority queue (next reaction method, Gibson and Bruck 2000). It uses about one random number per event and queue work.
- Optimized and sorting direct methods. Order the reactions by how often they fire, so that the linear search of line L8 stops early in most steps (Cao, Li and Petzold 2004; the sorting direct method updates the order during the run).
- Composition and rejection. Group the reactions by the size of their propensity into bins of powers of 2, pick a bin, then pick a reaction in the bin by rejection sampling. The expected work per event does not depend on (Slepoy, Thompson and Plimpton 2008). For a fixed set of weights, the alias method does the same in , but propensities change at every step.
- Tau-leaping. Fire many reactions in one step of length by Poisson draws (tau-leaping). It is faster when counts are large, and it is an approximation.
- Time-dependent propensities and delays. If the propensities depend on (a growing volume, a periodic input), line L5 is no longer valid. Anderson's modified next reaction method handles this case and delays.
When to use it
Use it when counts are small enough that single reactions matter (gene expression, signaling with few molecules, epidemics in a small group), when exact sample paths are needed, and when the number of events in the time span is affordable. It is the reference method against which the approximate methods are checked. If the state space is small enough to list, finite state projection gives the distribution with an error bound and no sampling error. If every species has large counts, tau-leaping, the chemical Langevin equation, or the deterministic rate equations are much faster.
Pitfalls
- The rate constant. The propensity uses the stochastic constant , not the molar constant . For , ; for , with the propensity . A wrong factor of 2 for dimerization gives the wrong equilibrium, and nothing in the output shows it.
- The last step. When , the run must stop without firing the reaction. Firing it and then stopping biases the state at .
- Sampling on a grid. The state at a grid time is the state after the last event at or before . Taking the state of the first event after , or interpolating between events, gives a biased estimate.
- Rounding in the search. The cumulative sum can end slightly below when is close to . The search must then return the last reaction with a positive propensity, never a reaction with , which could make a count negative.
- The logarithm. Use with in , or a library exponential sampler. is infinite when .
- One run is not an answer. A single path shows one possible behavior. Means, variances and probabilities need many runs with independent random streams, and the report needs the Monte Carlo error.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
gillespie_algorithm.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gillespie-algorithm/. The authors are listed in prov/TDM41K.jsonl.
"""Gillespie's direct method for the chemical master equation.
A network with n species and m reactions is given by:
- stoich: the m change vectors nu_1, ..., nu_m (stoich[j][i] = S[i][j]);
- propensity(x): the m propensities a_1(x), ..., a_m(x) for a state x, a
tuple of n integer counts.
Random numbers are drawn in this order in each step: first the waiting time
tau = rng.expovariate(a0), then u = rng.random() * a0 for the choice of the
reaction. A step whose time passes t_end draws only the first number. This is
the same order as ssa_direct in biostoch.py, so both give the same
trajectory for the same seed.
"""
from __future__ import annotations
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
def mass_action(reactants: Sequence[Sequence[int]], rates: Sequence[float]):
"""Return a propensity function for stochastic mass action.
reactants[j][i] is the number of molecules of species i that reaction j
uses (0, 1 or 2). The propensity is c_j times the number of distinct
reactant combinations: c x for one X, c x_A x_B for A + B, and
c x (x - 1) / 2 for 2X. So c for 2X is the convention with the factor 1/2
inside the combination count.
"""
def propensity(x: State) -> List[float]:
out = []
for row, c in zip(reactants, rates):
a = c
for i, k in enumerate(row):
if k == 1:
a *= x[i]
elif k == 2:
a *= x[i] * (x[i] - 1) / 2.0
elif k != 0:
raise ValueError("only orders 0, 1 and 2 per species")
out.append(float(a))
return out
return propensity
def direct_method(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Simulate one trajectory from x0 at time 0 up to time t_end.
Returns (times, states, complete). times[0] = 0.0 and states[0] = x0;
entry k > 0 is the time of event k and the state just after it. The state
at t_end is states[-1]. complete is False only if max_events events
fired before t_end.
"""
t = 0.0 # @line L1
x = tuple(int(v) for v in x0)
times = [t]
states = [x]
m = len(stoich)
for _ in range(max_events): # @line L2
a = propensity(x) # @line L3
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0: # @line L4
return times, states, True
tau = rng.expovariate(a0) # @line L5
if t + tau > t_end: # @line L6
return times, states, True
u = rng.random() * a0 # @line L7
acc = 0.0 # @line L8
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
t += tau # @line L9
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t) # @line L10
states.append(x)
return times, states, False
def state_at(times: Sequence[float], states: Sequence[State], t: float) -> State:
"""The state of a piecewise constant trajectory at time t >= 0."""
lo, hi = 0, len(times)
while hi - lo > 1:
mid = (lo + hi) // 2
if times[mid] <= t:
lo = mid
else:
hi = mid
return states[lo]
test_gillespie_algorithm.py 334 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gillespie-algorithm/. The authors are listed in prov/TDM41K.jsonl.
"""Tests of the shared helper biostoch.py and of the direct method.
Every simulation test compares a sample statistic with an exact value. A
sample mean of n values with exact mean mu and variance var must satisfy
|mean - mu| <= 4 sqrt(var / n). A whole distribution must pass a chi-square
test with chi2_sf(statistic, df) > 0.001.
"""
import math
import random
import statistics
import biostoch
from biostoch import (
binom_pmf,
binomial,
categorical,
check_mean,
chi2_sf,
hypergeom_pmf,
log_choose,
logsumexp,
mean_var,
multinomial,
nbinom_pmf,
normal_sf,
poisson,
poisson_pmf,
ssa_direct,
)
from gillespie_algorithm import direct_method, mass_action, state_at
Z = 4.0
# Networks with exact laws.
DEATH = [(-1,)]
def death_prop(x):
return (1.0 * x[0],)
IMMIG_DEATH = [(1,), (-1,)]
def immig_death_prop(x):
return (10.0, 1.0 * x[0])
def chi_square_ok(samples, pmf, support):
"""Chi-square test of samples against pmf on the integers of support.
Cells with expected count below 5 are pooled from each end inward; the
mass outside the support goes into the two end cells.
"""
n = len(samples)
counts = {}
for s in samples:
counts[s] = counts.get(s, 0) + 1
lo, hi = support[0], support[-1]
cells = []
for k in support:
e = n * pmf(k)
o = counts.get(k, 0)
cells.append([o, e])
below = sum(c for s, c in counts.items() if s < lo)
above = sum(c for s, c in counts.items() if s > hi)
mass_in = sum(pmf(k) for k in support)
cells[0][0] += below
cells[-1][0] += above
cells[-1][1] += n * max(0.0, 1.0 - mass_in)
pooled = []
acc = [0, 0.0]
for o, e in cells:
acc[0] += o
acc[1] += e
if acc[1] >= 5.0:
pooled.append(acc)
acc = [0, 0.0]
if acc[1] > 0 or acc[0] > 0:
if pooled:
pooled[-1][0] += acc[0]
pooled[-1][1] += acc[1]
else:
pooled.append(acc)
if len(pooled) < 2:
return True
stat = sum((o - e) ** 2 / e for o, e in pooled)
return chi2_sf(stat, len(pooled) - 1) > 0.001
# The helper: random variates
def test_poisson_small_and_large():
rng = random.Random(1)
for lam, n in ((0.7, 4000), (4.0, 4000), (75.0, 1500)):
xs = [poisson(rng, lam) for _ in range(n)]
m, v = mean_var(xs)
assert check_mean(m, lam, lam, n, Z)
hi = int(lam + 8 * math.sqrt(lam) + 8)
assert chi_square_ok(xs, lambda k: poisson_pmf(k, lam), list(range(hi + 1)))
assert poisson(rng, 0.0) == 0
def test_binomial_and_multinomial():
rng = random.Random(2)
n, p, reps = 20, 0.3, 4000
xs = [binomial(rng, n, p) for _ in range(reps)]
m, _ = mean_var(xs)
assert check_mean(m, n * p, n * p * (1 - p), reps, Z)
assert chi_square_ok(xs, lambda k: binom_pmf(k, n, p), list(range(n + 1)))
assert binomial(rng, 0, 0.5) == 0 and binomial(rng, 7, 1.0) == 7
probs = [0.2, 0.0, 0.5, 0.3]
reps = 2000
draws = [multinomial(rng, 50, probs) for _ in range(reps)]
assert all(sum(d) == 50 and d[1] == 0 for d in draws)
for i, q in enumerate(probs):
if q > 0:
m, _ = mean_var([d[i] for d in draws])
assert check_mean(m, 50 * q, 50 * q * (1 - q), reps, Z)
# Weights that do not sum to 1 are normalized.
d = multinomial(random.Random(3), 10, [2, 2])
assert sum(d) == 10
def test_categorical():
rng = random.Random(4)
w = [1.0, 0.0, 3.0, 6.0]
n = 5000
xs = [categorical(rng, w) for _ in range(n)]
assert 1 not in xs
assert chi_square_ok(xs, lambda k: w[k] / 10.0, [0, 2, 3])
# The helper: the direct method on networks with exact laws
def test_ssa_direct_pure_death_moments():
# X -> 0 at rate 1 per molecule from 100: X(1) ~ Binomial(100, e^-1).
rng = random.Random(5)
reps = 150 # about 63 events per run
xs = []
for _ in range(reps):
times, states, complete = ssa_direct(rng, (100,), DEATH, death_prop, 1.0)
assert complete
assert all(t <= 1.0 for t in times)
xs.append(states[-1][0])
mu = 100 * math.exp(-1)
var = 100 * math.exp(-1) * (1 - math.exp(-1))
assert abs(mu - 36.787944) < 1e-6 and abs(var - 23.254416) < 1e-6
m, v = mean_var(xs)
assert check_mean(m, mu, var, reps, Z)
assert abs(v / var - 1) <= Z * math.sqrt(2 / (reps - 1))
def test_ssa_direct_pure_death_distribution():
rng = random.Random(6)
reps = 1200 # about 6.3 events per run
q = math.exp(-1)
xs = [ssa_direct(rng, (10,), DEATH, death_prop, 1.0)[1][-1][0] for _ in range(reps)]
assert chi_square_ok(xs, lambda k: binom_pmf(k, 10, q), list(range(11)))
def test_ssa_direct_immigration_death_stationary():
# 0 -> X at rate 10, X -> 0 at rate 1 per molecule. Start from the
# stationary law Poisson(10); then X(t) ~ Poisson(10) for every t.
rng = random.Random(7)
reps = 800 # about 10 events per run
xs = []
for _ in range(reps):
x0 = poisson(rng, 10.0)
xs.append(ssa_direct(rng, (x0,), IMMIG_DEATH, immig_death_prop, 0.5)[1][-1][0])
m, v = mean_var(xs)
assert check_mean(m, 10.0, 10.0, reps, Z)
assert abs(v / 10.0 - 1) <= Z * math.sqrt(2 / (reps - 1))
assert chi_square_ok(xs, lambda k: poisson_pmf(k, 10.0), list(range(40)))
def test_ssa_direct_stops_and_repeats():
# An absorbing state stops the run with complete = True.
times, states, complete = ssa_direct(random.Random(8), (3,), DEATH, death_prop, 1e9)
assert complete and states[-1] == (0,) and len(times) == 4
# max_events cuts the run.
times, states, complete = ssa_direct(random.Random(8), (0,), IMMIG_DEATH, immig_death_prop, 1e9, 25)
assert not complete and len(times) == 26
# The same seed gives the same trajectory.
a = ssa_direct(random.Random(9), (5,), IMMIG_DEATH, immig_death_prop, 3.0)
b = ssa_direct(random.Random(9), (5,), IMMIG_DEATH, immig_death_prop, 3.0)
assert a == b
# The helper: statistics and exact functions
def test_mean_var_and_check_mean():
rng = random.Random(10)
xs = [rng.random() * 7 - 2 for _ in range(500)]
m, v = mean_var(xs)
assert abs(m - statistics.fmean(xs)) < 1e-12
assert abs(v - statistics.variance(xs)) < 1e-12
assert mean_var([3.0]) == (3.0, 0.0)
assert check_mean(10.5, 10.0, 1.0, 64) # 0.5 = 4 * sqrt(1 / 64)
assert not check_mean(10.51, 10.0, 1.0, 64)
def test_pmfs_sum_to_one():
assert abs(sum(binom_pmf(k, 30, 0.37) for k in range(31)) - 1) < 1e-12
assert abs(sum(poisson_pmf(k, 10.0) for k in range(200)) - 1) < 1e-12
assert abs(sum(nbinom_pmf(k, 5.0, 0.5) for k in range(2000)) - 1) < 1e-12
assert abs(sum(hypergeom_pmf(k, 20, 7, 9) for k in range(10)) - 1) < 1e-12
assert binom_pmf(0, 5, 0.0) == 1.0 and binom_pmf(5, 5, 1.0) == 1.0
def test_exact_functions():
for n in range(12):
for k in range(n + 1):
assert abs(log_choose(n, k) - math.log(math.comb(n, k))) < 1e-12
assert log_choose(4, 5) == -math.inf
mu, alpha = 5.0, 0.5
mean = sum(k * nbinom_pmf(k, mu, alpha) for k in range(3000))
second = sum(k * k * nbinom_pmf(k, mu, alpha) for k in range(3000))
assert abs(mean - mu) < 1e-9
assert abs(second - mean ** 2 - (mu + alpha * mu ** 2)) < 1e-8
assert nbinom_pmf(3, 2.0, 0.0) == poisson_pmf(3, 2.0)
assert abs(hypergeom_pmf(2, 10, 4, 3) - math.comb(4, 2) * math.comb(6, 1) / math.comb(10, 3)) < 1e-14
assert abs(logsumexp([1000.0, 1000.0]) - (1000.0 + math.log(2))) < 1e-12
assert logsumexp([]) == -math.inf
assert abs(normal_sf(1.959963984540054) - 0.025) < 1e-12
assert abs(normal_sf(0.0, 3.0, 2.0) - normal_sf(-1.5)) < 1e-15
def test_chi2_sf():
assert abs(chi2_sf(3.841, 1) - 0.05) < 1e-3
for x in (0.01, 0.5, 1.0, 3.0, 10.0, 40.0):
assert abs(chi2_sf(x, 2) - math.exp(-x / 2)) < 1e-12
assert abs(chi2_sf(x, 1) - math.erfc(math.sqrt(x / 2))) < 1e-12
# df = 4: Q(2, x/2) = e^(-x/2) (1 + x/2).
assert abs(chi2_sf(x, 4) - math.exp(-x / 2) * (1 + x / 2)) < 1e-12
assert chi2_sf(0.0, 3) == 1.0
assert abs(chi2_sf(0.454936, 1) - 0.5) < 1e-6
def test_helper_header():
with open(biostoch.__file__, encoding="utf-8") as f:
lines = f.read().splitlines()
assert lines[1].startswith("# Shared helper of the biology pages")
# The slug file: the direct method
# Dimerization 2A <-> B with A from a source: 0 -> A (c = 4), 2A -> B
# (c = 0.5, propensity 0.5 x_A (x_A - 1) / 2), B -> 2A (c = 1).
DIMER_STOICH = [(1, 0), (-2, 1), (2, -1)]
DIMER_PROP = mass_action([(0, 0), (2, 0), (0, 1)], [4.0, 0.5, 1.0])
def test_mass_action_counts_combinations():
prop = mass_action([(0, 0), (1, 0), (1, 1), (2, 0)], [2.0, 3.0, 0.5, 0.5])
assert prop((5, 4)) == [2.0, 15.0, 10.0, 5.0]
assert prop((1, 0)) == [2.0, 3.0, 0.0, 0.0]
def test_direct_method_matches_helper():
for seed in range(5):
a = direct_method(random.Random(seed), (3, 1), DIMER_STOICH, DIMER_PROP, 5.0)
b = ssa_direct(random.Random(seed), (3, 1), DIMER_STOICH, DIMER_PROP, 5.0)
assert a == b and len(a[0]) > 10
a = direct_method(random.Random(11), (7,), IMMIG_DEATH, immig_death_prop, 2.0, 5)
b = ssa_direct(random.Random(11), (7,), IMMIG_DEATH, immig_death_prop, 2.0, 5)
assert a == b and a[2] is False
def test_direct_method_pure_death():
rng = random.Random(12)
q = math.exp(-1)
xs = [direct_method(rng, (10,), DEATH, death_prop, 1.0)[1][-1][0] for _ in range(1500)]
assert chi_square_ok(xs, lambda k: binom_pmf(k, 10, q), list(range(11)))
m, _ = mean_var(xs)
assert check_mean(m, 10 * q, 10 * q * (1 - q), len(xs), Z)
# Until extinction, the run has exactly x0 events.
times, states, complete = direct_method(rng, (40,), DEATH, death_prop, math.inf)
assert complete and len(times) == 41 and states[-1] == (0,)
def test_direct_method_immigration_death_from_zero():
# From x0 = 0, X(t) ~ Poisson(10 (1 - e^(-t))).
rng = random.Random(13)
lam = 10 * (1 - math.exp(-1))
xs = [direct_method(rng, (0,), IMMIG_DEATH, immig_death_prop, 1.0)[1][-1][0] for _ in range(1500)]
m, _ = mean_var(xs)
assert check_mean(m, lam, lam, len(xs), Z)
assert chi_square_ok(xs, lambda k: poisson_pmf(k, lam), list(range(30)))
def test_direct_method_event_count():
# In the stationary immigration-death process, events come at mean rate
# 10 + E[X] = 20, so E[events in time T] = 20 T. Var(count) <= its mean
# times 3 (a loose bound) is used for the tolerance.
rng = random.Random(14)
reps, t_end = 400, 1.0
counts = []
for _ in range(reps):
x0 = poisson(rng, 10.0)
counts.append(len(direct_method(rng, (x0,), IMMIG_DEATH, immig_death_prop, t_end)[0]) - 1)
m, v = mean_var(counts)
assert v < 3 * 20.0
assert check_mean(m, 20.0 * t_end, 3 * 20.0, reps, Z)
def test_direct_method_one_step_law():
# From x = (5, 4) the first event comes after Exp(a0) and is reaction j
# with probability a_j / a0.
a = DIMER_PROP((5, 4))
a0 = sum(a)
rng = random.Random(15)
reps = 3000
waits, picks = [], []
for _ in range(reps):
times, states, _ = direct_method(rng, (5, 4), DIMER_STOICH, DIMER_PROP, math.inf, 1)
waits.append(times[1])
d = (states[1][0] - 5, states[1][1] - 4)
picks.append(DIMER_STOICH.index(d))
m, _ = mean_var(waits)
assert check_mean(m, 1 / a0, 1 / a0 ** 2, reps, Z)
assert chi_square_ok(picks, lambda j: a[j] / a0, [0, 1, 2])
def test_state_at():
times = [0.0, 0.5, 1.25]
states = [(3,), (2,), (1,)]
assert state_at(times, states, 0.0) == (3,)
assert state_at(times, states, 0.49) == (3,)
assert state_at(times, states, 0.5) == (2,)
assert state_at(times, states, 9.0) == (1,)
History
Kendall simulated a birth-death process by hand with random numbers in 1950, and Bortz, Kalos and Lebowitz used the same idea of an exponential waiting time and a choice by rate for spin systems in 1975 (see kinetic Monte Carlo). Gillespie derived the next reaction density for chemical reactions from first principles and gave the direct method and the first reaction method in the Journal of Computational Physics in 1976. His 1977 paper in the Journal of Physical Chemistry made the direct method known to chemists, with simulations of the Lotka reactions, the Brusselator and the Oregonator. In 1992 he showed that the chemical master equation, and so the simulation, is exact for a well-stirred gas in thermal equilibrium. The method became central to systems biology around 2000, when experiments showed noise in gene expression, and it is in tools such as COPASI, StochKit, GillesPy2 and the BioNetGen and VCell packages.
References
- Daniel T. Gillespie, A general method for numerically simulating the stochastic time evolution of coupled chemical reactions, Journal of Computational Physics 22(4), 1976, 403-434, the reaction probability density function and the direct method that samples it
- Daniel T. Gillespie, Exact stochastic simulation of coupled chemical reactions, Journal of Physical Chemistry 81(25), 1977, 2340-2361, the derivation of the next reaction density, the direct method, and the worked examples
- Daniel T. Gillespie, A rigorous derivation of the chemical master equation, Physica A 188(1-3), 1992, 404-425, the physical conditions under which the propensity description, and so the simulation, is exact
- Darren J. Wilkinson, Stochastic Modelling for Systems Biology, 3rd edition, CRC Press, 2018, the chapter on stochastic simulation algorithms (the direct method and its variants)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TDM41K Edit this page History Report an error Markdown