Algorithm Search⌘K

Algorithmadvanced

Next reaction method

Also called Gibson-Bruck algorithm.

An exact stochastic simulation that keeps one firing time per reaction in a priority queue and updates only the reactions a firing affects.

Time
O(m + N (n + d log m)) expected
Space
Θ(n + m + m d) extra
Where
N = the expected number of reaction events in the run; d = the largest number of reactions whose propensity one firing changes; m = the number of reactions; n = the number of species
Properties
randomizedexactrandomizediterative
Origin
Michael A. Gibson, Jehoshua Bruck, 2000

The next reaction method is an exact simulation method for the jump process of the chemical master equation. It starts from the first reaction method, which draws a new exponential clock for every reaction at every step, and removes the waste. The clock of a reaction that did not fire is still valid after the event, by the memoryless property of the exponential law: only its rate may have changed, and then the remaining time can be rescaled. So the method stores one absolute firing time per reaction in an indexed priority queue, fires the reaction at the top, draws a fresh clock only for that reaction, and recomputes the propensities and the times only for the reactions that the firing affects, as listed in a dependency graph. An event then costs one random number and O(dlog⁡m)O(d \log m) queue work, where dd is the number of affected reactions, instead of Θ(m)\Theta(m). The paths have exactly the same law as those of the Gillespie algorithm.

In plain words

Give every reaction an alarm clock set to the moment it would happen if nothing else changed. Keep the clocks in a line ordered by their alarm times, so the next one to ring is always in front.

When the front clock rings, that reaction happens, and the counts change. Most reactions do not care about this change, so their clocks stay as they are. For the few reactions that use the molecules that changed, the clocks must speed up or slow down: a reaction that became twice as likely should ring in half the time it still had left. Only the reaction that just happened gets a brand new clock.

So each step needs one new random number and touches only a few clocks, even in a cell model with thousands of reactions.

The problem

Input. A network with nn species and mm reactions: change vectors νj\nu_j, propensity functions aj(x)≥0a_j(x) \ge 0, and for each jj the set of species that aja_j reads; 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 jump process XX of the chemical master equation on [0,T][0, T].

The dependency graph. G[μ]G[\mu] lists μ\mu itself and every reaction kk whose propensity reads a species that νμ\nu_\mu changes. After μ\mu fires, the propensities of the reactions outside G[μ]G[\mu] are the same as before. For the dimerization network R1:2A→BR_1: 2A \to B, R2:B→2AR_2: B \to 2A, R3:B→∅R_3: B \to \emptyset, R1R_1 and R2R_2 change AA and BB, and R3R_3 changes BB, so G[R1]={R1,R2,R3}G[R_1] = \{R_1, R_2, R_3\}, G[R2]={R1,R2,R3}G[R_2] = \{R_1, R_2, R_3\} and G[R3]={R2,R3}G[R_3] = \{R_2, R_3\}.

The algorithm

Each reaction kk has a propensity aka_k and a firing time τk\tau_k in the queue. A reaction whose propensity is 0 has τk=∞\tau_k = \infty and keeps its unused unit clock rkr_k.

  1. NEXT-REACTION(x0, ν, a, G, T)
  2. 1t ← 0; x ← x0; record (0, x)
  3. 2for k ← 1 to m do r ← Exp(1); a_k ← a_k(x); if a_k > 0 then τ_k ← t + r / a_k else τ_k ← ∞; r_k ← r
  4. 3build an indexed min-queue Q on τ_1, ..., τ_m
  5. 4loop
  6. 5(τ_μ, μ) ← the minimum of Q
  7. 6if τ_μ = ∞ or τ_μ > T then return the record
  8. 7t ← τ_μ; x ← x + ν_μ; record (t, x)
  9. 8for each k in G[μ] do
  10. 9a_new ← a_k(x)
  11. 10if k = μ then r ← Exp(1)
  12. else if a_new = a_k then skip to the next k
  13. 11else if a_k > 0 then r ← a_k (τ_k - t) else r ← r_k
  14. a_k ← a_new; if a_new > 0 then τ_k ← t + r / a_new else τ_k ← ∞; r_k ← r
  15. 12update the key of k in Q to τ_k

Line L11 is the reuse rule. The quantity r=ak(τk−t)r = a_k(\tau_k - t) is the part of the reaction's unit-rate clock that has not been used yet. Dividing it by the new propensity gives the new remaining time, so τknew=t+(akold/aknew)(τk−t)\tau_k^{\text{new}} = t + (a_k^{\text{old}} / a_k^{\text{new}})(\tau_k - t). When a propensity drops to 0, the unused part is stored in rkr_k and used again when the propensity becomes positive.

Example

Immigration-death: R1:∅→XR_1: \emptyset \to X with a1=10a_1 = 10, R2:X→∅R_2: X \to \emptyset with a2=xa_2 = x, from x0=2x_0 = 2, with Python's random.Random(1). Each firing changes XX, which R2R_2 reads, so G[R1]=G[R2]={R1,R2}G[R_1] = G[R_2] = \{R_1, R_2\}.

Line L2 draws r=(0.1443,1.8802)r = (0.1443, 1.8802), so τ1=0.1443/10=0.0144\tau_1 = 0.1443 / 10 = 0.0144 and τ2=1.8802/2=0.9401\tau_2 = 1.8802 / 2 = 0.9401.

event fires at xx new τ1\tau_1 unused clock of R2R_2 new τ2\tau_2
1 0.0144 (R1R_1) 3 0.1587 2(0.9401−0.0144)=1.85142(0.9401 - 0.0144) = 1.8514 0.0144+1.8514/3=0.63150.0144 + 1.8514/3 = 0.6315
2 0.1587 (R1R_1) 4 0.1882 3(0.6315−0.1587)=1.41843(0.6315 - 0.1587) = 1.4184 0.1587+1.4184/4=0.51330.1587 + 1.4184/4 = 0.5133
3 0.1882 (R1R_1) 5 0.2566 4(0.5133−0.1882)=1.30044(0.5133 - 0.1882) = 1.3004 0.1882+1.3004/5=0.44830.1882 + 1.3004/5 = 0.4483
4 0.2566 (R1R_1) 6 0.3163 5(0.4483−0.2566)=0.95855(0.4483 - 0.2566) = 0.9585 0.2566+0.9585/6=0.41630.2566 + 0.9585/6 = 0.4163

The new τ1\tau_1 comes from a fresh draw each time (1.4430, 0.2945, 0.6841, 0.5969, each divided by 10). The death reaction never fires in these four events, and it never gets a new random number: its single clock, drawn at the start, is used up step by step (1.8802, 1.8514, 1.4184, 1.3004, 0.9585) while its rate grows with xx. The first four events use 2+4=62 + 4 = 6 random numbers; the first reaction method would use 10. The tests of the implementation check the queue against a brute-force minimum, the dependency graph of small networks, the Binomial law of pure death, the Poisson laws of immigration-death, the law of a dimerization network against the direct method, and the count of m+Nm + N random numbers for NN events.

Correctness

Call rk=ak(τk−t)r_k = a_k(\tau_k - t) the residual of reaction kk, in the units of a unit-rate clock. Between events the state, and so each aka_k, is constant, so each residual goes down by aksa_k s in a time ss, and line L11 stores exactly this value. Just after each event, given the whole history, the residuals are independent unit exponentials: the reaction that fired got a fresh one, and for every other reaction the history says only that rk>aksr_k > a_k s, and an exponential conditioned in this way is again exponential by the memoryless property. So the numbers rk/akr_k / a_k are independent exponentials with the rates ak(x)a_k(x), and their minimum has the next reaction density aje−a0sa_j e^{-a_0 s} of the first reaction method. Induction on the events gives the law of the path. The full proof is below.

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

Use the setting of the first reaction method: propensities aj(x)≥0a_j(x) \ge 0, a0=∑jaja_0 = \sum_j a_j, and the Markov jump process XX of the chemical master equation, assumed not to explode on [0,T][0, T]. In state xx, the next reaction of 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}.

The residuals. At any moment of the run, give each reaction kk a residual rk≥0r_k \ge 0, in the units of a unit-rate clock:

  • if ak>0a_k > 0, then rk=ak(τk−t)r_k = a_k (\tau_k - t), where τk\tau_k is the time stored in the queue and tt is the current time;
  • if ak=0a_k = 0, then rkr_k is the stored clock of line L11, and τk=∞\tau_k = \infty.

So τk=t+rk/ak\tau_k = t + r_k / a_k when ak>0a_k > 0. Line L2 sets rkr_k to a fresh unit exponential for each kk.

Lemma 1 (the update keeps the residuals). Let reaction μ\mu fire at time t′t', after the previous event at time tt, and let s=t′−ts = t' - t. Then after lines L8 to L12, for each k≠μk \ne \mu, the new residual of kk is rk−aksr_k - a_k s, where rkr_k and aka_k are the residual and the propensity just after the previous event. The residual of μ\mu is a fresh unit exponential.

Proof. Between the two events the state does not change, so aka_k is constant on [t,t′)[t, t'). For kk with ak>0a_k > 0, the residual at time t′t' is ak(τk−t′)=ak(τk−t)−aks=rk−aksa_k(\tau_k - t') = a_k(\tau_k - t) - a_k s = r_k - a_k s. Line L11 computes exactly this number when k∈G[μ]k \in G[\mu] and the propensity changes, and stores it in the new time t′+r/aknewt' + r / a_k^{\text{new}}, or in the stored clock if aknew=0a_k^{\text{new}} = 0. If k∉G[μ]k \notin G[\mu], or the propensity does not change, the stored τk\tau_k is kept, and ak(τk−t′)a_k(\tau_k - t') is the same number. For kk with ak=0a_k = 0, nothing is consumed (aks=0a_k s = 0), and the stored clock is kept or moved into a time, unchanged. For k=μk = \mu, line L10 draws a fresh unit exponential. Reactions outside G[μ]G[\mu] keep their propensity by the definition of the dependency graph, so no reaction that needs a new propensity is missed. □\square

Lemma 2 (the residuals are fresh). Just after each event (and at the start), given the whole history of the run so far (the event times, the fired reactions and the states), the residuals r1,…,rmr_1, \ldots, r_m are independent unit exponentials.

Proof. By induction on the number of events. At the start it holds by line L2. Assume it holds just after an event at time tt in state xx. The next event is at t+St + S with S=min⁡k:ak>0rk/akS = \min_{k : a_k > 0} r_k / a_k, and it is the reaction MM that reaches the minimum. Condition on S=sS = s and M=μM = \mu. For k≠μk \ne \mu with ak>0a_k > 0, this conditions rkr_k only through the event rk>aksr_k > a_k s, and the rkr_k are independent, so the rkr_k stay independent. By the memoryless property of the exponential law, rk−aksr_k - a_k s given rk>aksr_k > a_k s is again a unit exponential. For kk with ak=0a_k = 0, rkr_k does not enter SS or MM, so it is unchanged and still a unit exponential, independent of the rest. The residual of μ\mu is a fresh draw. By Lemma 1 these are the new residuals, so the claim holds after the new event. □\square

Theorem. The next 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), and it has the same law as the outputs of the direct method and the first reaction method.

Proof. Just after an event in state xx, by Lemma 2 the numbers rk/akr_k / a_k for ak>0a_k > 0 are, given the history, independent exponentials with rates aka_k. The queue returns their minimum and its index (lines L5 and L7). By the lemma on the minimum of exponential clocks (in the proof for the first reaction method), the pair (time to the event, reaction) has the density aj(x)e−a0(x)sa_j(x) e^{-a_0(x) s}, the next reaction density of XX, and it depends on the history only through xx. Line L6 stops when the smallest time is infinite (a0(x)=0a_0(x) = 0, so XX stays in xx) or after TT (no reaction of XX in (t,T](t, T], which has the same probability e−a0(x)(T−t)e^{-a_0(x)(T - t)}). The induction over the events is then the same as for the direct method. □\square

Remark (one random number per event). Line L2 draws mm unit exponentials, and each event draws one more, at line L10. So a run with NN events uses m+Nm + N random numbers. The direct method uses 2N2N (plus one for the last, discarded waiting time), and the first reaction method uses up to mNmN.

Remark (the source of the reuse rule). Gibson and Bruck (2000) reuse the clocks of the reactions that did not fire by rescaling the remaining time, τk←t+(akold/aknew)(τk−t)\tau_k \leftarrow t + (a_k^{\text{old}} / a_k^{\text{new}})(\tau_k - t), which is line L11. The handling of a propensity that drops to 0 and later becomes positive here keeps the residual rkr_k of the unit clock. This is the view of the random time change representation of the process, in which each reaction has its own unit-rate Poisson process, run at the speed ak(X(t))a_k(X(t)).

Complexity

  • Setup. Line L2 draws mm numbers and computes mm propensities, and line L3 builds a binary heap in Θ(m)\Theta(m). The dependency graph is computed one time before the run, from the species that each reaction changes and reads.
  • Per event. Line L5 reads the minimum in O(1)O(1). Line L7 changes up to nn counts. Lines L8 to L12 run for the ∣G[μ]∣≤d|G[\mu]| \le d affected reactions, each with one propensity and one heap update in O(log⁡m)O(\log m). So an event costs O(n+dlog⁡m)O(n + d \log m), and the run costs O(m+N(n+dlog⁡m))O(m + N(n + d \log m)) for NN events.
  • Random numbers. m+Nm + N in total, about one per event, against 2N+12N + 1 for the direct method and up to m(N+1)m(N + 1) for the first reaction method.
  • Space. The heap, the positions of the reactions in the heap, the propensities, the stored clocks, and the graph: Θ(n+m+∑μ∣G[μ]∣)⊆Θ(n+m+md)\Theta(n + m + \sum_\mu |G[\mu]|) \subseteq \Theta(n + m + m d).
  • In practice. The O(log⁡m)O(\log m) queue work and the poor memory locality of a heap can make the method slower than a well-tuned direct method for small and medium networks. Its advantage grows when mm is large and dd is small, as in large sparse models of signaling or of spatial compartments.

Properties

  • Exact. The paths have the law of the jump process of the chemical master equation, like those of the direct method and the first reaction method.
  • One random number per event. Only the fired reaction draws a new clock.
  • Local updates. An event touches only the reactions in G[μ]G[\mu]. The cost does not grow with mm except through log⁡m\log m.
  • Absolute times. The queue holds absolute firing times, not waiting times, so the reactions outside G[μ]G[\mu] need no change at all.
  • Equal propensities. If the new propensity equals the old one, the time is kept as it is (the skip after line L10). This is the rescaling rule with factor 1, and it saves a heap update.

Variants and improvements

  • Modified next reaction method. Anderson (2007) writes each reaction as a unit-rate Poisson process run at the speed ak(X(t))a_k(X(t)), and tracks for each reaction the internal time used so far and the internal time of its next firing. This is the same reuse in another form. It handles propensities that depend on time and reactions with delays, and it is the base of coupling methods for multilevel Monte Carlo.
  • Other queues. A binary heap is the usual choice. Bucket queues and calendar queues give O(1)O(1) expected time when the firing times are spread evenly, as in event-driven simulation.
  • Direct methods with partial sums. A tree of partial sums of the propensities lets the direct method update one propensity and pick the reaction in O(log⁡m)O(\log m), with the same cost order and simpler code. The composition-rejection method of Slepoy, Thompson and Plimpton (2008) has an expected cost per event that does not depend on mm.
  • Approximate leaps. For large counts, tau-leaping fires many reactions per step and is no longer exact.

When to use it

Use it for exact simulation of large networks in which each reaction affects few others: genome-scale models of gene expression, signaling cascades, and models with many spatial compartments in which each diffusion jump is a reaction between two neighbors. It is also the right form when some reactions have delays or time-dependent rates, through the modified version. For a network with ten reactions, the direct method is shorter and as fast.

Pitfalls

  • Missing dependencies. If G[μ]G[\mu] leaves out a reaction whose propensity changes, the old time stays in the queue and the law is wrong, with no error message. Compute GG from the reactants of each propensity, and include μ\mu itself.
  • Reusing the fired clock. The reaction that fired must get a fresh exponential (line L10). Rescaling its old clock, whose residual is 0, would make it fire again at once.
  • Rescaling with the wrong times. The rule is τk←t+(akold/aknew)(τk−t)\tau_k \leftarrow t + (a_k^{\text{old}} / a_k^{\text{new}})(\tau_k - t) with tt the time of the current event. Using the time of the previous event, or the waiting time from the previous event, gives a wrong law.
  • Propensities that reach 0. With aknew=0a_k^{\text{new}} = 0 the rescaling divides by 0. Store the unused clock and set the time to ∞\infty, then use the stored clock when the propensity becomes positive again.
  • Heap positions. An indexed queue must keep the position of each reaction up to date in every swap, or an update moves the wrong entry.
  • Units. As in every exact method, the propensities need the stochastic rate constants, with c=2k/(NAV)c = 2k/(N_A V) and the propensity c xA(xA−1)/2c\, x_A(x_A - 1)/2 for 2A2A.

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)
next_reaction_method.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/next-reaction-method/. The authors are listed in prov/KRZQSZ.jsonl.
"""The next reaction method of Gibson and Bruck (2000).

A network with n species and m reactions is given by:
- stoich: the m change vectors (stoich[j][i] = S[i][j]);
- rate(j, x): the propensity a_j(x) of reaction j in state x;
- depends: depends[j] is the set of species indices that a_j reads.

Each reaction j has an absolute putative firing time tau[j] in an indexed
priority queue. After reaction mu fires, only the reactions in G[mu] (the
dependency graph) get a new propensity and a new time. The fired reaction
draws a new Exp(1) number; every other reaction reuses its clock: the
unused part of its unit-rate exponential, r = a_old (tau - t), gives
tau = t + r / a_new. When a propensity drops to 0, r is kept and the time
is infinite until the propensity is positive again.

Draw order: m numbers rng.expovariate(1.0) at the start, for j = 0, ...,
m - 1, then one rng.expovariate(1.0) for each event, for the fired reaction.
"""

from __future__ import annotations

import math
from typing import Callable, List, Sequence, Set, Tuple

State = Tuple[int, ...]


class IndexedMinHeap:
    """A binary min-heap of the keys key[0..m-1] with a position map, so
    that the key of any index can change in O(log m) time."""

    def __init__(self, keys: Sequence[float]):
        self.key = list(keys)
        self.heap = list(range(len(self.key)))
        self.pos = list(range(len(self.key)))
        for i in range(len(self.heap) // 2 - 1, -1, -1):
            self._down(i)

    def top(self) -> Tuple[float, int]:
        j = self.heap[0]
        return self.key[j], j

    def update(self, j: int, k: float) -> None:
        old = self.key[j]
        self.key[j] = k
        if k < old:
            self._up(self.pos[j])
        elif k > old:
            self._down(self.pos[j])

    def _swap(self, p: int, q: int) -> None:
        h = self.heap
        h[p], h[q] = h[q], h[p]
        self.pos[h[p]] = p
        self.pos[h[q]] = q

    def _up(self, p: int) -> None:
        while p > 0:
            parent = (p - 1) // 2
            if self.key[self.heap[p]] < self.key[self.heap[parent]]:
                self._swap(p, parent)
                p = parent
            else:
                return

    def _down(self, p: int) -> None:
        n = len(self.heap)
        while True:
            c = 2 * p + 1
            if c >= n:
                return
            if c + 1 < n and self.key[self.heap[c + 1]] < self.key[self.heap[c]]:
                c += 1
            if self.key[self.heap[c]] < self.key[self.heap[p]]:
                self._swap(p, c)
                p = c
            else:
                return


def dependency_graph(stoich: Sequence[Sequence[int]], depends: Sequence[Set[int]]) -> List[List[int]]:
    """G[j] lists the reactions whose propensity can change when j fires:
    every k with a species in depends[k] that j changes, and j itself."""
    m = len(stoich)
    graph = []
    for j in range(m):
        changed = {i for i, d in enumerate(stoich[j]) if d != 0}
        out = [k for k in range(m) if k == j or changed & set(depends[k])]
        graph.append(out)
    return graph


def mass_action_rates(reactants: Sequence[Sequence[int]], rates: Sequence[float]):
    """Return (rate, depends) for stochastic mass action. reactants[j][i] is
    the number of molecules of species i that reaction j uses (0, 1 or 2);
    2X has propensity c x (x - 1) / 2."""
    def rate(j: int, x: State) -> float:
        a = rates[j]
        for i, k in enumerate(reactants[j]):
            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")
        return float(a)
    depends = [{i for i, k in enumerate(row) if k} for row in reactants]
    return rate, depends


def next_reaction_method(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
                         rate: Callable[[int, State], float], depends: Sequence[Set[int]],
                         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) as the direct method does.
    """
    m = len(stoich)
    t = 0.0  # @line L1
    x = tuple(int(v) for v in x0)
    graph = dependency_graph(stoich, depends)
    a = [0.0] * m
    clock = [0.0] * m  # the unused unit-rate time of a reaction with a = 0
    tau = [math.inf] * m
    for j in range(m):  # @line L2
        a[j] = rate(j, x)
        r = rng.expovariate(1.0)
        if a[j] > 0:
            tau[j] = t + r / a[j]
        else:
            clock[j] = r
    queue = IndexedMinHeap(tau)  # @line L3
    times = [t]
    states = [x]
    for _ in range(max_events):  # @line L4
        t_mu, mu = queue.top()  # @line L5
        if t_mu == math.inf or t_mu > t_end:  # @line L6
            return times, states, True
        t = t_mu  # @line L7
        nu = stoich[mu]
        x = tuple(x[i] + nu[i] for i in range(len(x)))
        times.append(t)
        states.append(x)
        for k in graph[mu]:  # @line L8
            a_new = rate(k, x)  # @line L9
            if a_new < 0:
                raise ValueError("propensities must be >= 0")
            if k == mu:  # @line L10
                r = rng.expovariate(1.0)
            elif a_new == a[k]:
                continue
            elif a[k] > 0:  # @line L11
                r = a[k] * (tau[k] - t)
            else:
                r = clock[k]
            a[k] = a_new
            if a_new > 0:
                tau[k] = t + r / a_new
            else:
                clock[k] = r
                tau[k] = math.inf
            queue.update(k, tau[k])  # @line L12
    return times, states, False
test_next_reaction_method.py 194 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/next-reaction-method/. The authors are listed in prov/KRZQSZ.jsonl.
"""Tests of the next 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 next_reaction_method import (
    IndexedMinHeap,
    dependency_graph,
    mass_action_rates,
    next_reaction_method,
)

Z = 4.0

DEATH = [(-1,)]
DEATH_RATE, DEATH_DEP = mass_action_rates([(1,)], [1.0])
IMMIG_DEATH = [(1,), (-1,)]
ID_RATE, ID_DEP = mass_action_rates([(0,), (1,)], [10.0, 1.0])

# 0 -> A (c = 4), 2A -> B (c = 0.5, propensity 0.5 x_A (x_A - 1) / 2),
# B -> 2A (c = 1).
DIMER = [(1, 0), (-2, 1), (2, -1)]
DIMER_REACTANTS = [(0, 0), (2, 0), (0, 1)]
DIMER_RATE, DIMER_DEP = mass_action_rates(DIMER_REACTANTS, [4.0, 0.5, 1.0])


def dimer_prop(x):
    return [DIMER_RATE(j, x) for j in range(3)]


def pooled_stat(cells):
    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]:
        pooled[-1] = [pooled[-1][0] + acc[0], pooled[-1][1] + acc[1]]
    return sum((o - e) ** 2 / e for o, e in pooled), len(pooled) - 1


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)
    stat, df = pooled_stat([(counts.get(k, 0), n * pmf(k)) for k in support])
    return chi2_sf(stat, df) > 0.001


def two_sample_ok(xs, ys):
    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
    cells, acc = [], [0, 0]
    for k in keys:
        acc = [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:
        ex, ey = (ox + oy) * nx / (nx + ny), (ox + oy) * ny / (nx + ny)
        stat += (ox - ex) ** 2 / ex + (oy - ey) ** 2 / ey
    return chi2_sf(stat, len(cells) - 1) > 0.001


def test_indexed_heap_against_brute_force():
    rng = random.Random(31)
    keys = [rng.random() for _ in range(17)]
    heap = IndexedMinHeap(keys)
    for _ in range(2000):
        j = rng.randrange(17)
        k = math.inf if rng.random() < 0.1 else rng.random()
        heap.update(j, k)
        keys[j] = k
        top_key, top_j = heap.top()
        assert top_key == min(keys) and keys[top_j] == top_key
        assert all(heap.heap[heap.pos[i]] == i for i in range(17))


def test_dependency_graph():
    # R0: 0 -> A, R1: 2A -> B, R2: B -> 2A. R0 changes A, so it affects R1
    # (which reads A) and itself. R1 and R2 change A and B: they affect R1, R2.
    assert dependency_graph(DIMER, DIMER_DEP) == [[0, 1], [1, 2], [1, 2]]
    # A chain A -> B -> C -> 0: firing A -> B changes A and B.
    stoich = [(-1, 1, 0), (0, -1, 1), (0, 0, -1)]
    deps = [{0}, {1}, {2}]
    assert dependency_graph(stoich, deps) == [[0, 1], [1, 2], [2]]


def test_pure_death_law():
    rng = random.Random(32)
    q = math.exp(-1)
    xs = [next_reaction_method(rng, (10,), DEATH, DEATH_RATE, DEATH_DEP, 1.0)[1][-1][0]
          for _ in range(1500)]
    assert chi_square_ok(xs, lambda k: binom_pmf(k, 10, q), list(range(11)))
    reps = 150
    xs = [next_reaction_method(rng, (100,), DEATH, DEATH_RATE, DEATH_DEP, 1.0)[1][-1][0]
          for _ in range(reps)]
    mu, var = 100 * q, 100 * q * (1 - q)
    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():
    rng = random.Random(33)
    lam = 10 * (1 - math.exp(-1))
    xs = [next_reaction_method(rng, (0,), IMMIG_DEATH, ID_RATE, ID_DEP, 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)))
    reps = 800
    xs = []
    for _ in range(reps):
        x0 = poisson(rng, 10.0)
        xs.append(next_reaction_method(rng, (x0,), IMMIG_DEATH, ID_RATE, ID_DEP, 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_same_law_as_direct_method():
    # From (1, 0) the reaction 2A -> B starts with propensity 0, so the
    # stored clock of a reaction that wakes up is used.
    reps = 1200
    rng_n, rng_d = random.Random(34), random.Random(35)
    nx = [next_reaction_method(rng_n, (1, 0), DIMER, DIMER_RATE, DIMER_DEP, 2.0)[1][-1]
          for _ in range(reps)]
    dx = [ssa_direct(rng_d, (1, 0), DIMER, dimer_prop, 2.0)[1][-1] for _ in range(reps)]
    assert two_sample_ok([s[0] for s in nx], [s[0] for s in dx])
    assert two_sample_ok([s[1] for s in nx], [s[1] for s in dx])


def test_one_step_law():
    x = (5, 4)
    a = dimer_prop(x)
    a0 = sum(a)
    rng = random.Random(36)
    reps = 3000
    waits, picks = [], []
    for _ in range(reps):
        times, states, _ = next_reaction_method(rng, x, DIMER, DIMER_RATE, DIMER_DEP, math.inf, 1)
        waits.append(times[1])
        picks.append(DIMER.index((states[1][0] - x[0], states[1][1] - x[1])))
    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])


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_one_random_number_per_event():
    rng = CountingRandom(37)
    times, states, complete = next_reaction_method(rng, (1, 0), DIMER, DIMER_RATE, DIMER_DEP, math.inf, 200)
    assert not complete
    assert rng.calls == 3 + 200
    # Pure death to extinction stops with complete = True.
    times, states, complete = next_reaction_method(random.Random(38), (6,), DEATH, DEATH_RATE, DEATH_DEP, math.inf)
    assert complete and len(times) == 7 and states[-1] == (0,)

History

Gillespie (1976) gave the first reaction method and noted that it wastes random numbers. Gibson and Bruck (2000) turned it into the next reaction method: they kept the putative times of the reactions that did not fire, showed that rescaling them keeps the method exact, and used a dependency graph and an indexed priority queue so that the cost per event grows only as log⁡m\log m. Cao, Li and Petzold (2004) showed that a direct method with the reactions sorted by frequency is often faster in practice. Anderson (2007) rewrote the method with internal unit-rate clocks, which extended it to time-dependent propensities and delays.

References

  1. 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 dependency graph, the reuse of the putative times by rescaling, the indexed priority queue, and the proof that the method is exact
  2. David F. Anderson, A modified next reaction method for simulating chemical systems with time dependent propensities and delays, Journal of Chemical Physics 127(21), 2007, 214107, the formulation by unit-rate internal clocks of each reaction, which also covers propensities that drop to 0
  3. 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, on which the next reaction method is built

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