Algorithm Search⌘K

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
Properties
randomizedexactrandomizediterative
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 Θ(m)\Theta(m) work for mm 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 nn species and mm reactions: for each reaction jj a change vector νj∈Zn\nu_j \in \mathbb{Z}^n and a propensity function aj(x)≥0a_j(x) \ge 0 of the state x∈Nnx \in \mathbb{N}^n. A start state x0x_0, an end time TT, and a source of uniform random numbers. The propensities usually come from stochastic mass action: cc for a source, c xAc\, x_A for A→…A \to \ldots, c xAxBc\, x_A x_B for A+B→…A + B \to \ldots, and c xA(xA−1)/2c\, x_A (x_A - 1)/2 for 2A→…2A \to \ldots, with c=2k/(NAV)c = 2k/(N_A V) in the last case for a deterministic rate constant kk in molar units.

Output. The event times 0<t1<t2<…≤T0 < t_1 < t_2 < \ldots \le T and the states just after them, such that the path has the same law as the Markov jump process XX of the chemical master equation on [0,T][0, T]. The state at time TT is the last recorded state.

The next reaction density. Given X(t)=xX(t) = x, let τ\tau be the time to the next reaction and JJ the reaction. With a0(x)=∑jaj(x)a_0(x) = \sum_j a_j(x),

Pr⁡(τ∈[s,s+ds), J=j)=aj(x) e−a0(x)s ds.\Pr(\tau \in [s, s + ds),\ J = j) = a_j(x)\, e^{-a_0(x) s}\, ds .

So τ\tau is exponential with rate a0(x)a_0(x), J=jJ = j with probability aj(x)/a0(x)a_j(x)/a_0(x), and the two are independent. The direct method samples the two factors one after the other.

The algorithm

  1. DIRECT-METHOD(x0, ν, a, T)
  2. 1t ← 0; x ← x0; record (0, x)
  3. 2loop
  4. 3compute a_j(x) for j = 1, ..., m and a0 ← a_1(x) + ... + a_m(x)
  5. 4if a0 = 0 then return the record
  6. 5τ ← -ln(1 - U1) / a0 with U1 uniform on [0, 1)
  7. 6if t + τ > T then return the record
  8. 7u ← U2 · a0 with U2 uniform on [0, 1)
  9. 8j ← the smallest index with a_1(x) + ... + a_j(x) > u
  10. 9t ← t + τ; x ← x + ν_j
  11. 10record (t, x)

Line L5 is inverse transform sampling of the exponential law. Line L8 is inverse transform sampling of the discrete law aj/a0a_j / a_0 by a linear search over the cumulative sums. Line L6 discards the last waiting time: the process stays in xx until after TT, so xx is the state at TT, and the reaction is not fired.

Example

Take immigration-death: R1:∅→XR_1: \emptyset \to X with propensity a1=10a_1 = 10, and R2:X→∅R_2: X \to \emptyset with propensity a2=xa_2 = x (rate 1 per molecule). Start from x0=2x_0 = 2 and use Python's random.Random(1).

step a1,a2a_1, a_2 a0a_0 τ\tau uu fires tt after xx after
1 10, 2 12 0.0120 10.1692 R2R_2 0.0120 1
2 10, 1 11 0.1312 2.8058 R1R_1 0.1432 2
3 10, 2 12 0.0570 5.3939 R1R_1 0.2002 3
4 10, 3 13 0.0811 10.2534 R2R_2 0.2813 2
5 10, 2 12 0.0082 0.3402 R1R_1 0.2895 3
6 10, 3 13 0.1390 5.6260 R1R_1 0.4285 4

In step 1 the cumulative sums are 10 and 12, and u=10.1692u = 10.1692 falls in [10,12)[10, 12), so R2R_2 fires. In step 2 the sums are 10 and 11, and u=2.8058<10u = 2.8058 < 10, so R1R_1 fires. The count drifts up toward the stationary mean 10.

To check a simulator, use networks with a known law. Pure death X→∅X \to \emptyset at rate 1 per molecule from 100 molecules gives X(1)X(1) Binomial(100,e−1)(100, e^{-1}), with mean 36.787944 and variance 23.254416. Immigration-death with rates 10 and 1 has the stationary law Poisson(10)(10), and from x0=0x_0 = 0, X(1)X(1) is Poisson$(10(1 - e^{-1})) = $ Poisson(6.321206)(6.321206). 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 [t,t+s)[t, t + s) satisfies p0′(s)=−a0(x)p0(s)p_0'(s) = -a_0(x) p_0(s), so p0(s)=e−a0(x)sp_0(s) = e^{-a_0(x) s}, and then reaction jj fires in [s,s+ds)[s, s + ds) with probability aj(x) dsa_j(x)\, ds. Line L5 gives τ\tau with density a0e−a0sa_0 e^{-a_0 s}, and line L8 gives J=jJ = j with probability aj/a0a_j / a_0, independent of τ\tau, so one step has the joint density aje−a0sa_j e^{-a_0 s}. Each step uses fresh random numbers and depends on the past only through xx, which matches the strong Markov property of XX. By induction on the number of events, the recorded path has the law of XX on [0,T][0, T]. The full proof is below.

Proof: The direct method samples the process of the chemical master equationfull

Fix a network with stoichiometric vectors ν1,…,νm\nu_1, \ldots, \nu_m and propensities aj(x)≥0a_j(x) \ge 0, and write a0(x)=∑jaj(x)a_0(x) = \sum_j a_j(x). The chemical master equation is the forward equation of the Markov jump process X(t)X(t) with these jump rates: in a state xx, the process waits an exponential time with rate a0(x)a_0(x), and then it jumps to x+νjx + \nu_j with probability aj(x)/a0(x)a_j(x) / a_0(x). We assume that this process does not explode on [0,T][0, T], that is, it makes finitely many jumps in [0,T][0, T] with probability 1. This holds, for example, when the reachable states are finite, or when a0a_0 is bounded on them.

Lemma 1 (the next reaction density). Let the process be in state xx at time tt, with a0(x)>0a_0(x) > 0. Let τ\tau be the time to the next reaction and JJ the index of that reaction. Then (τ,J)(\tau, J) has the joint density

p(s,j∣x)=aj(x) e−a0(x)s,s≥0,  j=1,…,m.p(s, j \mid x) = a_j(x)\, e^{-a_0(x) s}, \qquad s \ge 0, \; j = 1, \ldots, m.

Proof. In the jump process, reaction jj fires in [t+s,t+s+ds)[t + s, t + s + ds) with probability aj(x) ds+o(ds)a_j(x)\, ds + o(ds), given that the state is still xx. Let P0(s)P_0(s) be the probability that no reaction fires in [t,t+s)[t, t + s). Then P0(s+ds)=P0(s) (1−a0(x) ds+o(ds))P_0(s + ds) = P_0(s)\,(1 - a_0(x)\, ds + o(ds)), so P0′=−a0P0P_0' = -a_0 P_0 with P0(0)=1P_0(0) = 1, and P0(s)=e−a0(x)sP_0(s) = e^{-a_0(x) s}. The probability that the first reaction is jj and fires in [t+s,t+s+ds)[t + s, t + s + ds) is P0(s) aj(x) dsP_0(s)\, a_j(x)\, ds. □\square

Lemma 2 (one step of the direct method). In state xx with a0=a0(x)>0a_0 = a_0(x) > 0, lines L5 to L8 return a pair (τ,μ)(\tau, \mu) with the density p(s,j∣x)p(s, j \mid x) of Lemma 1.

Proof. Line L5 draws τ\tau with density a0e−a0sa_0 e^{-a_0 s}. Line L7 draws uu uniform on [0,a0)[0, a_0), independent of τ\tau. Line L8 returns the first index μ\mu with a1+⋯+aμ>ua_1 + \cdots + a_\mu > u. Indices with aj=0a_j = 0 add nothing to the sum, so they are never returned. For an index jj with aj>0a_j > 0, the event μ=j\mu = j is the event a1+⋯+aj−1≤u<a1+⋯+aja_1 + \cdots + a_{j-1} \le u < a_1 + \cdots + a_j, which has probability aj/a0a_j / a_0. So (τ,μ)(\tau, \mu) has the density a0e−a0s⋅aj/a0=aje−a0sa_0 e^{-a_0 s} \cdot a_j / a_0 = a_j e^{-a_0 s}. □\square

Theorem. Run the direct method from x0x_0 up to TT. Let t1<t2<⋯t_1 < t_2 < \cdots be the event times and x1,x2,…x_1, x_2, \ldots the states that it records. Then the sequence (tk,xk)(t_k, x_k) has the same joint law as the jump times and the states after the jumps of XX on [0,T][0, T]. In particular, the last recorded state has the law P(⋅,T)P(\cdot, T), the solution of the chemical master equation at time TT.

Proof. By induction on kk. Assume that (t1,x1,…,tk,xk)(t_1, x_1, \ldots, t_k, x_k) has the law of the first kk jumps of XX (for k=0k = 0 there is nothing to prove). By the strong Markov property of XX at its kk-th jump time, the next waiting time and the next reaction of XX, given the past, have the density p(s,j∣xk)p(s, j \mid x_k) of Lemma 1, and they depend on the past only through xkx_k. 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 k+1k + 1 jumps have the same law.

If a0(xk)=0a_0(x_k) = 0, then XX stays in xkx_k for ever, and line L4 stops the run in xkx_k: both agree.

Stopping at TT: line L6 discards a waiting time with tk+τ>Tt_k + \tau > T and stops. In XX, the event that no reaction fires in (tk,T](t_k, T] has probability e−a0(xk)(T−tk)=Pr⁡(τ>T−tk)e^{-a_0(x_k)(T - t_k)} = \Pr(\tau > T - t_k), so the two agree on the event that there is no further event before TT, and the state at TT is xkx_k in both. Since XX does not explode on [0,T][0, T], the run stops after finitely many events with probability 1. □\square

Remark (number of events). The number of events in [0,T][0, T] is the number of jumps of XX in [0,T][0, T]. For pure death X→0X \to 0 with rate cc per molecule from x0x_0, each molecule dies by time TT with probability 1−e−cT1 - e^{-cT}, so the mean number of events is x0(1−e−cT)x_0 (1 - e^{-cT}). For immigration-death at stationarity, births and deaths each fire at the mean rate bb, so the mean number of events in [0,T][0, T] is 2bT2 b T.

Complexity

  • Per event. Line L3 recomputes mm propensities, line L8 scans up to mm cumulative sums, and line L9 changes up to nn counts. So a step costs Θ(m+n)\Theta(m + n) with a constant number of random numbers.
  • Per run. The number of events NN is random. Its mean is E[N]=∫0TE[a0(X(t))] dt\mathbb{E}[N] = \int_0^T \mathbb{E}[a_0(X(t))]\, dt, because events come at the rate a0a_0. For pure death from x0x_0 at rate cc it is x0(1−e−cT)x_0(1 - e^{-cT}); for immigration-death at stationarity it is 2bT2bT, where bb is the immigration rate. The expected time is Θ(E[N](m+n))\Theta(\mathbb{E}[N](m + n)).
  • Large networks. With a dependency graph, line L3 only updates the propensities that the last reaction changed, and a0a_0 is updated by the differences. The search in line L8 is then the bottleneck, Θ(m)\Theta(m) per step; a tree of partial sums makes it O(log⁡m)O(\log m).
  • Space. Θ(n+m)\Theta(n + m) 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 10610^6 times per second costs 10610^6 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 1/R1/\sqrt{R} for RR runs, by the central limit theorem.
  • Two random numbers per event. One for the time and one for the reaction. A run with NN events uses 2N+12N + 1 numbers when it stops at TT, 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 ≥0\ge 0 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 mm 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 O(log⁡m)O(\log m) 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 mm (Slepoy, Thompson and Plimpton 2008). For a fixed set of weights, the alias method does the same in O(1)O(1), but propensities change at every step.
  • Tau-leaping. Fire many reactions in one step of length τ\tau 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 tt (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 cc, not the molar constant kk. For A+BA + B, c=k/(NAV)c = k/(N_A V); for 2A2A, c=2k/(NAV)c = 2k/(N_A V) with the propensity c xA(xA−1)/2c\, x_A(x_A - 1)/2. A wrong factor of 2 for dimerization gives the wrong equilibrium, and nothing in the output shows it.
  • The last step. When t+τ>Tt + \tau > T, the run must stop without firing the reaction. Firing it and then stopping biases the state at TT.
  • Sampling on a grid. The state at a grid time ss is the state after the last event at or before ss. Taking the state of the first event after ss, or interpolating between events, gives a biased estimate.
  • Rounding in the search. The cumulative sum can end slightly below uu when uu is close to a0a_0. The search must then return the last reaction with a positive propensity, never a reaction with aj=0a_j = 0, which could make a count negative.
  • The logarithm. Use −ln⁡(1−U)-\ln(1 - U) with UU in [0,1)[0, 1), or a library exponential sampler. −ln⁡U-\ln U is infinite when U=0U = 0.
  • 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.

biostoch.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example