Algorithm Search⌘K

Algorithmcore

First reaction method

Also called Gillespie first reaction method.

Exact stochastic simulation that draws a tentative firing time for every reaction and fires the earliest, equivalent to the direct method.

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 first reaction method draws exact sample paths of the jump process of the chemical master equation, like the direct method of the Gillespie algorithm, but it organizes each step in another way. In every step it gives each reaction its own exponential clock, with the rate equal to the reaction's current propensity, and fires the reaction whose clock rings first. The time of the event is the smallest clock. The minimum of independent exponential clocks is exponential with the sum of the rates, and the index of the minimum has probabilities proportional to the rates, so the step has exactly the law of a step of the direct method. Gillespie gave both methods in the same 1976 paper. The first reaction method costs up to mm random numbers per event for mm reactions, against 2 for the direct method, so it is rarely the fastest choice. Its value is as the basis of the next reaction method, which keeps the clocks and reuses them.

In plain words

Every kind of reaction in the cell gets its own alarm clock. A reaction that is likely to happen soon gets a clock that tends to ring early. Set all the clocks at random, see which one rings first, and let that reaction happen. Move time forward to that moment and change the counts.

Now the counts are different, so the chances have changed. Throw all the clocks away, set new ones for the new counts, and look again for the first to ring. Keep going until you reach the end time.

This gives exactly the same kind of story as spinning a wheel to pick the reaction, but it needs one random number for every kind of reaction, every time.

The problem

Input. A network with nn species and mm reactions: change vectors νj∈Zn\nu_j \in \mathbb{Z}^n and propensity functions aj(x)≥0a_j(x) \ge 0; a start state x0x_0; an end time TT; a source of random numbers.

Output. Event times and the states just after them, with the same law as the Markov jump process XX of the chemical master equation on [0,T][0, T]. The state at TT is the last recorded state.

The next reaction of XX from state xx comes after a time τ\tau and is reaction JJ, with the joint density aj(x)e−a0(x)sa_j(x) e^{-a_0(x) s}, where a0=∑jaja_0 = \sum_j a_j. The method samples this density by a minimum of clocks.

The algorithm

  1. FIRST-REACTION(x0, ν, a, T)
  2. 1t ← 0; x ← x0; record (0, x)
  3. 2loop
  4. 3compute a_j(x) for j = 1, ..., m
  5. 4best ← ∞; μ ← none
  6. 5for j ← 1 to m with a_j(x) > 0 do
  7. 6τ_j ← an exponential random number with rate a_j(x)
  8. 7if τ_j < best then best ← τ_j; μ ← j
  9. 8if μ = none then return the record
  10. 9if t + best > T then return the record
  11. 10t ← t + best; x ← x + ν_μ
  12. 11record (t, x)

Line L5 skips the reactions with a zero propensity: their clocks are infinite, and they cannot fire. Line L8 stops when no reaction can fire. Line L9 stops without firing when the first clock rings after TT, so the current state is the state at TT.

Example

Take immigration-death again: R1:∅→XR_1: \emptyset \to X with a1=10a_1 = 10, and R2:X→∅R_2: X \to \emptyset with a2=xa_2 = x. Start from x0=2x_0 = 2 and draw the clocks with Python's random.Random(1), R1R_1 first.

step a1,a2a_1, a_2 τ1\tau_1 τ2\tau_2 fires tt after xx after
1 10, 2 0.0144 0.9401 R1R_1 0.0144 3
2 10, 3 0.1443 0.0982 R2R_2 0.1126 2
3 10, 2 0.0684 0.2985 R1R_1 0.1810 3
4 10, 3 0.1054 0.5182 R1R_1 0.2864 4
5 10, 4 0.0099 0.0072 R2R_2 0.2936 3

In step 2 the death clock 0.09820.0982 rings before the immigration clock 0.14430.1443, so a molecule dies at 0.0144+0.0982=0.11260.0144 + 0.0982 = 0.1126. The immigration clock of step 2 is then thrown away, and step 3 draws a new one. The path is not the one the direct method gives with the same seed (it fires R2R_2 first there), because the two methods use the random numbers in another way. The law is the same: the tests of the implementation check the Binomial law of pure death from 100 molecules (mean 36.787944 and variance 23.254416 at t=1t = 1), the Poisson laws of immigration-death, and the histogram of a dimerization network against runs of the direct method.

Correctness

Let EjE_j be independent exponentials with rates aj>0a_j > 0, and let S=min⁡jEjS = \min_j E_j with index MM. The event {M=j,S∈[s,s+ds)}\{M = j, S \in [s, s + ds)\} is the event that EjE_j lands in [s,s+ds)[s, s + ds) and every other clock is later than ss, with probability aje−ajsds∏k≠je−aks=aje−a0sdsa_j e^{-a_j s} ds \prod_{k \ne j} e^{-a_k s} = a_j e^{-a_0 s} ds. This is the next reaction density of XX. So SS is exponential with rate a0a_0, M=jM = j with probability aj/a0a_j / a_0, and they are independent, as in the direct method. Each step draws fresh clocks and depends on the past only through xx, so by induction on the events the path has the law of XX. The full proof is below.

Proof: The first reaction method samples the process of the chemical master equationfull

Use the setting of the direct method: propensities aj(x)≥0a_j(x) \ge 0, a0(x)=∑jaj(x)a_0(x) = \sum_j a_j(x), and the Markov jump process XX whose forward equation is the chemical master equation. In state xx the next reaction of XX comes after a time τ\tau and is reaction JJ, where (τ,J)(\tau, J) has the joint density aj(x)e−a0(x)sa_j(x) e^{-a_0(x) s} (Lemma 1 of the proof for the direct method). We assume that XX does not explode on [0,T][0, T].

Lemma (the minimum of exponential clocks). Let EjE_j, for the indices jj with aj>0a_j > 0, be independent with EjE_j exponential of rate aja_j. Let S=min⁡jEjS = \min_j E_j and let MM be the index where the minimum is reached. Then (S,M)(S, M) has the joint density aje−a0sa_j e^{-a_0 s}, with a0=∑jaja_0 = \sum_j a_j. In particular SS is exponential with rate a0a_0, Pr⁡(M=j)=aj/a0\Pr(M = j) = a_j / a_0, and SS and MM are independent.

Proof. Ties have probability 0, because the EjE_j have densities. For s≥0s \ge 0, the event {M=j,S∈[s,s+ds)}\{M = j, S \in [s, s + ds)\} is the event that Ej∈[s,s+ds)E_j \in [s, s + ds) and Ek>sE_k > s for all k≠jk \ne j (up to o(ds)o(ds)). By independence its probability is

aje−ajs ds∏k≠je−aks=aje−a0s ds.a_j e^{-a_j s}\, ds \prod_{k \ne j} e^{-a_k s} = a_j e^{-a_0 s}\, ds.

Summing over jj gives the density a0e−a0sa_0 e^{-a_0 s} of SS, and integrating over ss gives Pr⁡(M=j)=aj/a0\Pr(M = j) = a_j / a_0. The joint density is the product of the two marginals, so SS and MM are independent. □\square

Theorem. The first reaction method run from x0x_0 up to TT records event times and states with the same joint law as the jumps of XX on [0,T][0, T]. So its last state has the law P(⋅,T)P(\cdot, T) of the chemical master equation, and it has the same law as the output of the direct method.

Proof. Lines L4 to L7 draw one exponential EjE_j of rate aj(x)a_j(x) for each jj with aj(x)>0a_j(x) > 0, all independent of each other and of the past, and keep the smallest. Reactions with aj(x)=0a_j(x) = 0 get no clock and cannot fire, and in XX they have probability 0 of firing in state xx. By the lemma, the pair (time to the event, reaction) has the density aj(x)e−a0(x)sa_j(x) e^{-a_0(x) s}, which is the next reaction density of XX. Line L8 stops when no clock was drawn, that is, when a0(x)=0a_0(x) = 0, and then XX stays in xx. Line L9 stops when the first clock rings after TT; in XX, no reaction in (t,T](t, T] has probability e−a0(x)(T−t)e^{-a_0(x)(T - t)}, which is Pr⁡(S>T−t)\Pr(S > T - t). The induction on the number of events is then the same as for the direct method: given the past, each step uses fresh clocks and depends on the past only through the current state, as XX does by the strong Markov property. □\square

Remark (cost). A step draws one exponential for each reaction with a positive propensity, so it uses up to mm random numbers where the direct method uses 2. The clocks of the reactions that did not fire are thrown away. The next reaction method shows that they can be kept: by the memoryless property, a clock that has not rung yet still has an exponential remaining time.

Complexity

  • Per event. Line L3 computes mm propensities, lines L5 to L7 draw up to mm exponentials and keep the minimum, and line L10 changes up to nn counts. So a step costs Θ(m+n)\Theta(m + n) work, like the direct method, but with up to mm logarithms instead of one.
  • Random numbers. A step uses one number per reaction with a positive propensity, so a run with NN events uses up to m(N+1)m(N + 1) numbers, against 2N+12N + 1 for the direct method. For a network with 1000 reactions this is the dominant cost.
  • Per run. The number of events has the same law as for the direct method, with mean ∫0TE[a0(X(t))] dt\int_0^T \mathbb{E}[a_0(X(t))]\, dt. The expected time is Θ(E[N](m+n))\Theta(\mathbb{E}[N](m + n)).
  • Space. Θ(n+m)\Theta(n + m), plus the record.

Properties

  • Exact. The paths have the law of the jump process of the chemical master equation, with no step size and no bias.
  • Same law as the direct method. For the same network and start, the first reaction method and the direct method give the same distribution of paths. For the same seed, they give different paths.
  • Natural for clocks. Each reaction has its own clock. This makes the method easy to extend to events that are not exponential, for example a reaction with a fixed delay, where a clock for the delayed completion goes into the same minimum.
  • Waste. All the clocks except one are thrown away at each step, even for reactions whose propensities did not change. By the memoryless property of the exponential law, these clocks are still valid, which is the idea of the next reaction method.

Variants and improvements

  • Next reaction method. Keep the clocks of the reactions that did not fire, store absolute firing times in an indexed priority queue, and change only the clocks whose propensities change, by rescaling (next reaction method, Gibson and Bruck 2000). It uses one random number per event.
  • Direct method. Draw the total waiting time and the reaction separately, with two random numbers per event (Gillespie algorithm).
  • Delays. Put the completion times of delayed reactions in the same set of clocks, and fire whichever comes first. This gives exact methods for reactions with fixed delays, such as transcription and translation.
  • Other event simulators. The same minimum of clocks is the core of event-driven simulation and of kinetic Monte Carlo codes that keep one candidate time per event type.

When to use it

Use it to teach or to check the exact methods, for networks with a handful of reactions, or as the base of a simulator with delayed or non-exponential events. For an exact simulation of a large network, use the next reaction method, or the direct method with a fast search. For large counts, use an approximate method such as tau-leaping.

Pitfalls

  • Zero propensities. A reaction with aj=0a_j = 0 must get an infinite clock, not a call to an exponential sampler with rate 0, which fails or returns an infinite value with a division by 0.
  • Ties. Two equal clocks have probability 0 in exact arithmetic, but they can happen in floating point. Any fixed rule for ties is fine; the code keeps the first.
  • Reusing clocks. Keeping the clock of a reaction whose propensity changed, without rescaling it, gives the wrong law. Throw it away (this method) or rescale it (the next reaction method).
  • The last step. If the smallest clock rings after TT, stop without firing it.
  • Units. The propensities need the stochastic rate constants: c=k/(NAV)c = k/(N_A V) for A+BA + B, and c=2k/(NAV)c = 2k/(N_A V) for 2A2A with the propensity c xA(xA−1)/2c\, x_A(x_A - 1)/2.

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)
first_reaction_method.py 59 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/first-reaction-method/. The authors are listed in prov/4TMPNZ.jsonl.
"""Gillespie's first reaction method for the chemical master equation.

A network with n species and m reactions is given by stoich, the m change
vectors (stoich[j][i] = S[i][j]), and propensity(x), which returns the m
propensities for a state x (a tuple of n integer counts).

Draw order in each step: one rng.expovariate(a_j) for each reaction j with
a_j > 0, in index order j = 0, 1, ..., m - 1. Reactions with a_j = 0 draw
nothing. A step therefore uses as many random numbers as there are
reactions with a positive propensity.
"""

from __future__ import annotations

import math
from typing import Callable, Sequence, Tuple

State = Tuple[int, ...]


def first_reaction_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) in the format of the direct method:
    times[0] = 0.0, states[0] = x0, and entry k > 0 is the time of event k
    and the state just after it. 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
        best = math.inf  # @line L4
        mu = -1
        for j in range(m):  # @line L5
            if a[j] < 0:
                raise ValueError("propensities must be >= 0")
            if a[j] > 0:
                tau_j = rng.expovariate(a[j])  # @line L6
                if tau_j < best:  # @line L7
                    best = tau_j
                    mu = j
        if mu < 0:  # @line L8
            return times, states, True
        if t + best > t_end:  # @line L9
            return times, states, True
        t += best  # @line L10
        nu = stoich[mu]
        x = tuple(x[i] + nu[i] for i in range(len(x)))
        times.append(t)  # @line L11
        states.append(x)
    return times, states, False
test_first_reaction_method.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/first-reaction-method/. The authors are listed in prov/4TMPNZ.jsonl.
"""Tests of the first reaction method.

A sample mean of n values with exact mean mu and variance var must satisfy
|mean - mu| <= 4 sqrt(var / n). A distribution must pass a chi-square test
with chi2_sf(statistic, df) > 0.001.
"""

import math
import random

from biostoch import (
    binom_pmf,
    check_mean,
    chi2_sf,
    mean_var,
    poisson,
    poisson_pmf,
    ssa_direct,
)
from first_reaction_method import first_reaction_method

Z = 4.0

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


# 0 -> A (c = 4), 2A -> B (c = 0.5, propensity 0.5 x_A (x_A - 1) / 2),
# B -> 2A (c = 1). No closed form; used to compare methods.
DIMER = [(1, 0), (-2, 1), (2, -1)]


def dimer_prop(x):
    return (4.0, 0.5 * x[0] * (x[0] - 1) / 2.0, 1.0 * x[1])


def pooled_cells(cells):
    """Pool (observed, expected) cells left to right until each expected
    count is at least 5; a short last group joins the one before it."""
    pooled, acc = [], [0, 0.0]
    for o, e in cells:
        acc = [acc[0] + o, acc[1] + e]
        if acc[1] >= 5.0:
            pooled.append(acc)
            acc = [0, 0.0]
    if acc != [0, 0.0]:
        if pooled:
            pooled[-1] = [pooled[-1][0] + acc[0], pooled[-1][1] + acc[1]]
        else:
            pooled.append(acc)
    return pooled


def chi_square_ok(samples, pmf, support):
    n = len(samples)
    counts = {}
    for s in samples:
        counts[s] = counts.get(s, 0) + 1
    assert all(s in support for s in counts)
    cells = [(counts.get(k, 0), n * pmf(k)) for k in support]
    pooled = pooled_cells(cells)
    stat = sum((o - e) ** 2 / e for o, e in pooled)
    return chi2_sf(stat, len(pooled) - 1) > 0.001


def two_sample_ok(xs, ys):
    """Chi-square test that two samples of equal size have the same law."""
    keys = sorted(set(xs) | set(ys))
    cx, cy = {}, {}
    for v in xs:
        cx[v] = cx.get(v, 0) + 1
    for v in ys:
        cy[v] = cy.get(v, 0) + 1
    # Each cell: (label, count in xs, count in ys); pool by the smaller count.
    cells = []
    acc = [0, 0]
    for k in keys:
        acc[0] += cx.get(k, 0)
        acc[1] += cy.get(k, 0)
        if (acc[0] + acc[1]) / 2 >= 5:
            cells.append(acc)
            acc = [0, 0]
    if acc != [0, 0]:
        cells[-1] = [cells[-1][0] + acc[0], cells[-1][1] + acc[1]]
    nx, ny = len(xs), len(ys)
    stat = 0.0
    for ox, oy in cells:
        tot = ox + oy
        ex, ey = tot * nx / (nx + ny), tot * ny / (nx + ny)
        stat += (ox - ex) ** 2 / ex + (oy - ey) ** 2 / ey
    return chi2_sf(stat, len(cells) - 1) > 0.001


def test_pure_death_law():
    rng = random.Random(21)
    q = math.exp(-1)
    xs = [first_reaction_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)


def test_pure_death_moments_from_100():
    rng = random.Random(22)
    reps = 150
    xs = [first_reaction_method(rng, (100,), DEATH, death_prop, 1.0)[1][-1][0] for _ in range(reps)]
    mu = 100 * math.exp(-1)
    var = mu * (1 - math.exp(-1))
    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_immigration_death_from_zero():
    rng = random.Random(23)
    lam = 10 * (1 - math.exp(-1))
    xs = [first_reaction_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(max(xs) + 1)))


def test_immigration_death_stationary():
    rng = random.Random(24)
    reps = 800
    xs = []
    for _ in range(reps):
        x0 = poisson(rng, 10.0)
        xs.append(first_reaction_method(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))


def test_one_step_law():
    # The minimum of independent Exp(a_j) is Exp(a0), and its index is j
    # with probability a_j / a0.
    x = (5, 4)
    a = dimer_prop(x)
    a0 = sum(a)
    rng = random.Random(25)
    reps = 3000
    waits, picks = [], []
    for _ in range(reps):
        times, states, _ = first_reaction_method(rng, x, DIMER, dimer_prop, math.inf, 1)
        waits.append(times[1])
        picks.append(DIMER.index((states[1][0] - x[0], states[1][1] - x[1])))
    m, v = 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_same_law_as_direct_method():
    # The state of A at t = 2 from (3, 1), first reaction against direct.
    reps = 1200
    rng_f, rng_d = random.Random(26), random.Random(27)
    fx = [first_reaction_method(rng_f, (3, 1), DIMER, dimer_prop, 2.0)[1][-1] for _ in range(reps)]
    dx = [ssa_direct(rng_d, (3, 1), DIMER, dimer_prop, 2.0)[1][-1] for _ in range(reps)]
    assert two_sample_ok([s[0] for s in fx], [s[0] for s in dx])
    assert two_sample_ok([s[1] for s in fx], [s[1] for s in dx])
    # Conservation: x_A + 2 x_B changes only by the source reaction.
    assert all(s[0] + 2 * s[1] >= 5 for s in fx)


class CountingRandom(random.Random):
    def __init__(self, seed):
        super().__init__(seed)
        self.calls = 0

    def expovariate(self, lambd=1.0):
        self.calls += 1
        return super().expovariate(lambd)


def test_draws_per_step():
    # One exponential per reaction with a positive propensity in each step.
    rng = CountingRandom(28)
    times, states, _ = first_reaction_method(rng, (3, 0), DIMER, dimer_prop, math.inf, 40)
    expected = 0
    for x in states[:-1]:
        expected += sum(1 for v in dimer_prop(x) if v > 0)
    assert rng.calls == expected
    # Pure death to extinction: x0 events, then a step with no draw.
    times, states, complete = first_reaction_method(random.Random(29), (6,), DEATH, death_prop, math.inf)
    assert complete and len(times) == 7 and states[-1] == (0,)

History

Gillespie's 1976 paper in the Journal of Computational Physics derived the reaction probability density function aje−a0sa_j e^{-a_0 s} and gave two ways to sample it, the direct method and the first reaction method, with a proof that both are exact. He preferred the direct method for its smaller use of random numbers, and his 1977 paper used it for all its examples. Gibson and Bruck (2000) returned to the first reaction method and showed that, with a dependency graph, rescaled clocks and a priority queue, it becomes the next reaction method, which needs one random number per event.

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 first reaction method and the proof that it samples the reaction probability density function
  2. Michael A. Gibson and Jehoshua Bruck, Efficient exact stochastic simulation of chemical systems with many species and many channels, Journal of Physical Chemistry A 104(9), 2000, 1876-1889, the discussion of the first reaction method as the starting point of the next reaction method
  3. Darren J. Wilkinson, Stochastic Modelling for Systems Biology, 3rd edition, CRC Press, 2018, the chapter on stochastic simulation algorithms (the first reaction method)

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