Algorithm Search⌘K

Algorithmadvanced

Tau-leaping

Also called explicit tau-leaping.

Approximate stochastic simulation that fires a Poisson number of each reaction in a step tau over which propensities change little.

Time
O(L m n) expected
Space
Θ(n + m) extra
Where
L = the number of leaps in the run; epsilon = the error control parameter; m = the number of reactions; n = the number of species
Properties
randomizednot exactrandomizediterative
Origin
Daniel T. Gillespie, Yang Cao, Linda R. Petzold, 2001

Tau-leaping is an approximate method for the jump process of the chemical master equation. The exact methods, such as the Gillespie algorithm, fire one reaction per step, so their cost is the number of reaction events, which is huge when the counts are large. Tau-leaping takes a step of length τ\tau and fires every reaction jj a random number of times, drawn from a Poisson law with mean aj(x)τa_j(x)\tau, with the propensities frozen at the start of the step. This is exact if the propensities do not change in the step, and it is a good approximation if τ\tau is small enough that they change little: the leap condition. The method of Cao, Gillespie and Petzold (2006) chooses τ\tau from a parameter ϵ\epsilon to meet that condition, fires the reactions that are about to use up a reactant at most once per step, and falls back to exact steps when a leap would be too short to be worth it. It is the stochastic analogue of the explicit Euler method, with the same problems for stiff systems.

In plain words

The exact method moves one reaction at a time. With a million molecules that is a huge number of tiny moves.

Tau-leaping takes a bigger jump in time instead. It asks: over the next short while, about how many times will each reaction happen? If the counts barely change in that while, each reaction keeps about the same speed, and the number of times it happens is a known kind of random count. So draw those counts, apply them all at once, and jump the clock forward.

The catch is the word "barely". Jump too far and the speeds you used are out of date, so the answer drifts from the truth, and a jump can even take away more molecules than exist. The method picks the jump length so the speeds stay nearly the same, and goes back to one reaction at a time when molecules are scarce.

The problem

Input. A network with nn species and mm reactions: change vectors νj\nu_j, mass action propensities aj(x)a_j(x), and the reactant orders of each reaction; a start state x0x_0; an end time TT; the error control parameter ϵ\epsilon (0.03 is common); the threshold ncn_c for critical reactions (10 is common).

Output. An approximate sample path of the jump process XX on [0,T][0, T]: times and states, with every count ≥0\ge 0.

The leap. If in state xx the propensities stay at aj(x)a_j(x) for all of [t,t+τ)[t, t + \tau), the numbers of firings KjK_j are independent with Kj∼K_j \sim Poisson(aj(x)τ)(a_j(x)\tau), and

X(t+τ)=x+∑j=1mKj νj.X(t + \tau) = x + \sum_{j=1}^{m} K_j\, \nu_j .

The step size. Let μ^i=∑jνijaj(x)\hat\mu_i = \sum_j \nu_{ij} a_j(x) and σ^i2=∑jνij2aj(x)\hat\sigma_i^2 = \sum_j \nu_{ij}^2 a_j(x), over the noncritical reactions, for each species ii that is a reactant somewhere. The rule of Cao, Gillespie and Petzold (2006, eq. 33) is

τ′=min⁡i{max⁡(ϵxi/gi,1)∣μ^i∣, max⁡(ϵxi/gi,1)2σ^i2},\tau' = \min_i \left\{ \frac{\max(\epsilon x_i / g_i, 1)}{|\hat\mu_i|},\ \frac{\max(\epsilon x_i / g_i, 1)^2}{\hat\sigma_i^2} \right\},

which bounds the expected change and the standard deviation of the change of each xix_i in one leap by ϵxi/gi\epsilon x_i / g_i (or by 1 for small counts). The factor gig_i depends on the highest order reaction in which species ii is a reactant (eq. 27): gi=1g_i = 1 for first order, gi=2g_i = 2 for Xi+XkX_i + X_k, gi=2+1/(xi−1)g_i = 2 + 1/(x_i - 1) for 2Xi2X_i, and similar values for third order. It makes the relative change of every propensity at most about ϵ\epsilon.

The algorithm

A reaction is critical if it can fire fewer than ncn_c more times before one of its reactants runs out.

  1. TAU-LEAP(x0, ν, a, T, ε, n_c)
  2. 1t ← 0; x ← x0; record (0, x)
  3. 2while t < T do
  4. 3compute a_j(x) and a0; if a0 = 0 then return the record
  5. 4mark reaction j critical if a_j(x) > 0 and it can fire fewer than n_c times
  6. 5τ' ← the step size of eq. 33 over the noncritical reactions
  7. 6if τ' < 10 / a0 then do 100 steps of the direct method and go to L2
  8. 7τ'' ← Exp(a0c), where a0c is the sum of the critical propensities (∞ if a0c = 0)
  9. 8τ ← min(τ', τ'', T - t)
  10. 9K_j ← Poisson(a_j(x) τ) for each noncritical j; K_j ← 0 for each critical j
  11. 10if τ = τ'' then pick one critical j with probability a_j / a0c and set K_j ← 1
  12. 11if x + Σ K_j ν_j has a negative entry then τ' ← τ' / 2 and go to L7
  13. 12t ← t + τ; x ← x + Σ K_j ν_j; record (t, x) if some K_j > 0

Line L6 is the switch to exact steps: a leap shorter than about 10 mean waiting times saves nothing, so the method runs the exact method for a while. Lines L7 and L10 let the critical reactions fire at most once per leap, at the rate of an exact step. Line L11 is a safety net, and with critical reactions it is rarely used.

Example

A fixed step on pure death. Take X→∅X \to \emptyset at rate 1 per molecule, x0=100x_0 = 100, and leap with a fixed τ\tau (no critical reactions, no switch). A leap maps xx to x−Kx - K with K∼K \sim Poisson(xτ)(x\tau), so the mean is multiplied by 1−τ1 - \tau per leap, and the mean at t=1t = 1 is 100(1−τ)1/τ100(1 - \tau)^{1/\tau}. The variance follows from Vk+1=(1−τ)2Vk+τmkV_{k+1} = (1 - \tau)^2 V_k + \tau m_k.

τ\tau leaps mean at t=1t = 1 variance at t=1t = 1
0.5 2 25.000 37.500
0.1 10 34.868 25.234
0.01 100 36.603 23.440
exact about 63 events 36.788 23.254

The error of the mean is of order τ\tau, as for the Euler method. With τ=0.01\tau = 0.01 the leap uses more steps than the exact method uses events, so for 100 molecules leaping does not pay.

The adaptive step on 1000 molecules. With x0=1000x_0 = 1000 and ϵ=0.03\epsilon = 0.03, line L5 gives τ′=min⁡(ϵ,ϵ2x)=0.03\tau' = \min(\epsilon, \epsilon^2 x) = 0.03 while x>33x > 33. A run to t=1t = 1 takes about 34 leaps, against an average of 1000(1−e−1)=6321000(1 - e^{-1}) = 632 events for the exact method. The mean over 200 runs is 363.5, and the leap chain with τ=0.03\tau = 0.03 predicts 1000⋅0.9733⋅0.99=362.31000 \cdot 0.97^{33} \cdot 0.99 = 362.3, against the exact 367.9: about 1.5 percent low.

Noise is distorted too. For immigration-death (∅→X\emptyset \to X at rate bb, X→∅X \to \emptyset at rate xx), a leap chain with a fixed τ\tau has the right stationary mean bb, but the stationary variance 2b/(2−τ)2b/(2 - \tau) instead of bb. With τ=0.1\tau = 0.1 and b=10b = 10 that is 10.526; with τ=0.5\tau = 0.5 it is 13.33. With b=1000b = 1000, the adaptive method gives a mean near 1000 and a variance near 1340, with mean step 0.444, close to 2000/(2−0.444)=12902000/(2 - 0.444) = 1290. The tests of the implementation check both effects.

Correctness

Tau-leaping is not exact, so the guarantees are of another kind, proved below. A leap is exact when every propensity is constant, which holds for networks of sources only. The step of line L5 bounds the mean and the variance of the change of each reactant count in a leap by max⁡(ϵxi/gi,1)\max(\epsilon x_i/g_i, 1) and its square. The method never records a negative count, because of line L11, and the repeat ends with probability 1. If every reaction with a positive propensity is critical, one step is exactly a step of the direct method, and the implementation then gives the same path as the direct method for the same seed. As ϵ→0\epsilon \to 0 the method tends to the exact process; as the counts grow with τ\tau fixed and many firings per leap, the leap tends to an Euler-Maruyama step of the chemical Langevin equation, and then to the Euler step of the rate equations (Gillespie 2001). The bias is of order τ\tau in the weak sense for a fixed step.

Proof: What tau-leaping guaranteesfull

Tau-leaping is an approximation, so "correct" here means four precise claims: the leap is exact when the propensities do not change during the leap; the step of lines L5 to L8 meets the leap condition by construction; the method never returns a negative count; and when every reaction is critical, it is the exact direct method. The bias of a leap chain in a linear network is computed at the end. The setting is that of the direct method: propensities aj(x)a_j(x), change vectors νj\nu_j, and the Markov jump process XX of the chemical master equation.

Claim 1 (exact for constant propensities). Suppose that the propensities stay at aj(x)a_j(x) on [t,t+τ)[t, t + \tau) whatever reactions fire. Then the numbers KjK_j of firings of the reactions in that interval are independent, with KjK_j Poisson of mean aj(x)τa_j(x) \tau.

Proof. With constant rates, the firings of reaction jj form a Poisson process of rate aj(x)a_j(x), and the processes of different reactions are independent (a jump process with constant rates a1,…,ama_1, \ldots, a_m splits into independent Poisson processes, one per reaction). The count of a Poisson process of rate aa in an interval of length τ\tau is Poisson of mean aτa \tau. □\square

This holds exactly when every reaction has order 0 (sources only). Then a leap of any length gives the exact law. In general the propensities change with xx, and a leap uses their values at the start of the step. That is the approximation.

Claim 2 (the leap condition). Let τ′\tau' be the value of line L5, and let II be the set of reactant species. For each i∈Ii \in I, write μ^i=∑j noncriticalνijaj(x)\hat\mu_i = \sum_{j \text{ noncritical}} \nu_{ij} a_j(x) and σ^i2=∑j noncriticalνij2aj(x)\hat\sigma_i^2 = \sum_{j \text{ noncritical}} \nu_{ij}^2 a_j(x). Then for every leap of length τ≤τ′\tau \le \tau' in which no critical reaction fires,

∣E[Δxi]∣≤max⁡(εxi/gi,1),Var⁡[Δxi]≤max⁡(εxi/gi,1)2,|\mathbb{E}[\Delta x_i]| \le \max(\varepsilon x_i / g_i, 1), \qquad \operatorname{Var}[\Delta x_i] \le \max(\varepsilon x_i / g_i, 1)^2,

where Δxi=∑jνijKj\Delta x_i = \sum_j \nu_{ij} K_j is the change of species ii in the leap.

Proof. In such a leap, the KjK_j of the noncritical reactions are independent Poisson variables of mean ajτa_j \tau, so E[Δxi]=μ^iτ\mathbb{E}[\Delta x_i] = \hat\mu_i \tau and Var⁡[Δxi]=σ^i2τ\operatorname{Var}[\Delta x_i] = \hat\sigma_i^2 \tau. Write bi=max⁡(εxi/gi,1)b_i = \max(\varepsilon x_i / g_i, 1). Line L5 takes τ′≤bi/∣μ^i∣\tau' \le b_i / |\hat\mu_i| and τ′≤bi2/σ^i2\tau' \le b_i^2 / \hat\sigma_i^2 for each ii (a term with a zero denominator puts no bound). So ∣μ^i∣τ≤bi|\hat\mu_i| \tau \le b_i and σ^i2τ≤bi2\hat\sigma_i^2 \tau \le b_i^2. □\square

Cao, Gillespie and Petzold (2006) choose gig_i from the highest order reaction in which species ii is a reactant so that a relative change of at most ε/gi\varepsilon / g_i in xix_i changes each propensity by a relative amount of at most about ε\varepsilon. For example, for 2Xi→…2X_i \to \ldots with propensity c xi(xi−1)/2c\, x_i (x_i - 1) / 2, a change δ\delta in xix_i changes the propensity by the factor 1+δ(2xi−1+δ)/(xi(xi−1))1 + \delta (2 x_i - 1 + \delta) / (x_i (x_i - 1)), whose first order part in δ/xi\delta / x_i is (2+1/(xi−1)) δ/xi(2 + 1/(x_i - 1))\, \delta / x_i, the value of gig_i for this case. The bound "at least 1" on bib_i lets a species with a small count change by about one molecule.

Claim 3 (no negative counts). Every state that the method records has all counts ≥0\ge 0.

Proof. A leap is accepted at line L11 only if x+∑jKjνj≥0x + \sum_j K_j \nu_j \ge 0 in every entry; otherwise it is drawn again with a smaller step. The steps of the direct method in line L6 fire one reaction with a positive propensity, and a mass action propensity is positive only if the reactants are present, so these steps keep the counts ≥0\ge 0. The repeat terminates with probability 1: as τ′→0\tau' \to 0, the probability that every noncritical KjK_j is 0 tends to 1, and a leap in which only one critical reaction fires once (or nothing fires) never makes a count negative. □\square

Claim 4 (all critical gives the direct method). If every reaction with aj(x)>0a_j(x) > 0 is critical in the state xx, the step from xx has the law of one step of the direct method.

Proof. With no noncritical reaction, μ^i=σ^i2=0\hat\mu_i = \hat\sigma_i^2 = 0, so τ′=∞\tau' = \infty and line L6 does not switch. Line L7 draws τ′′\tau'' exponential with rate a0c=a0(x)a_0^c = a_0(x). Line L8 gives τ=min⁡(τ′′,T−t)\tau = \min(\tau'', T - t), and line L9 sets every Kj=0K_j = 0. If τ=τ′′\tau = \tau'', line L10 picks one reaction with probability aj/a0a_j / a_0 and fires it once. This is the next reaction density aje−a0sa_j e^{-a_0 s} of Lemma 2 of the proof for the direct method, and when t+τ′′>Tt + \tau'' > T no reaction fires in (t,T](t, T], as in the direct method. □\square

In the code the draws are in the same order as in ssa_direct of the helper, so the test checks that the two give the same trajectory, not only the same law.

The bias of a fixed-step leap in two linear networks. For pure death X→0X \to 0 at rate 1 per molecule, a leap of length τ\tau maps xx to x−Kx - K with KK Poisson of mean xτx \tau (ignore the rare rejected leaps). By the laws of total expectation and variance, mk+1=(1−τ)mkm_{k+1} = (1 - \tau) m_k and Vk+1=(1−τ)2Vk+τmkV_{k+1} = (1 - \tau)^2 V_k + \tau m_k. So after T/τT / \tau steps the mean is x0(1−τ)T/τx_0 (1 - \tau)^{T/\tau}, against the exact x0e−Tx_0 e^{-T}. For immigration-death with rates bb and 1, mk+1=mk+τ(b−mk)m_{k+1} = m_k + \tau (b - m_k) and Vk+1=(1−τ)2Vk+τ(b+mk)V_{k+1} = (1 - \tau)^2 V_k + \tau (b + m_k). The fixed point is m=bm = b and V=2bτ/(1−(1−τ)2)=2b/(2−τ)V = 2 b \tau / (1 - (1 - \tau)^2) = 2b / (2 - \tau), against the exact stationary variance bb. So the leap chain has the right stationary mean, and a stationary variance that is too large by the factor 2/(2−τ)2 / (2 - \tau), for 0<τ<20 < \tau < 2.

Complexity

  • Per leap. Line L3 costs Θ(m)\Theta(m) propensities, line L4 O(mn)O(mn) for the critical test, and line L5 O(mn)O(mn) for the sums μ^i\hat\mu_i and σ^i2\hat\sigma_i^2 (less with a sparse stoichiometric matrix). Line L9 draws up to mm Poisson numbers, each in O(1)O(1) expected time with a good sampler. So a leap costs O(mn)O(mn), and O(m+nonzeros of S)O(m + \text{nonzeros of } S) with sparse loops.
  • Number of leaps. The step τ′\tau' is about ϵ\epsilon times the time scale on which the counts change, so the number of leaps over a fixed interval is about 1/ϵ1/\epsilon times the number of those time scales, independent of the counts. The exact method needs a number of events proportional to the counts. The gain grows with the system size.
  • Exact steps. When counts are small, line L6 runs exact steps, and the cost is that of the direct method.
  • Space. Θ(n+m)\Theta(n + m), plus the record.

Properties

  • Approximate. The bias in the mean and the variance is of order τ\tau for a fixed step. The adaptive rule keeps the relative change of the propensities in a step near ϵ\epsilon.
  • Nonnegative counts. With critical reactions and the check of line L11, every recorded count is ≥0\ge 0.
  • Exact in a limit. It is exact when the propensities are constant, and it becomes the direct method when all reactions are critical.
  • Explicit. Like the explicit Euler method, it is unstable or very inaccurate for stiff systems: when a fast reversible pair is near equilibrium, the leap condition forces tiny steps, or a larger step makes the fast species swing too much.
  • Not one event per step. The output holds the state after each leap, not the time of each reaction. Event-level statistics, such as the time of the first firing of a reaction, are not available.

Variants and improvements

  • The first step rule. Gillespie (2001) bounded the expected change of each propensity in a leap, using the derivatives of all propensities, with a cost of O(m2)O(m^2) per leap. The rule of eq. 33 bounds the changes of the counts instead, which is cheaper and less conservative.
  • Implicit tau-leaping. For stiff systems, Rathinam, Petzold, Cao and Gillespie (2003) took the mean part of the leap implicitly, as the implicit Euler method does for a stiff ODE. It allows large steps when fast reactions are near equilibrium, but it damps the fluctuations of the fast species.
  • Binomial leaping. Draw KjK_j from a binomial law whose number of trials is the count of the limiting reactant, so that a leap cannot remove more molecules than exist (Tian and Burrage 2004).
  • Post-leap checks. Anderson (2008) checks after the leap whether the propensities changed too much, and if so rejects the leap and draws a shorter one conditioned on the first, which keeps the law correct.
  • Multilevel Monte Carlo. Coupling leap paths with step τ\tau and τ/2\tau/2 by shared Poisson processes lets multilevel Monte Carlo estimate means with the bias of a fine step at much lower cost, with an exact method on the finest level.
  • The Langevin limit. When every reaction fires many times per leap, the Poisson counts can be replaced by normal ones, which is the Euler-Maruyama method for the chemical Langevin equation.

When to use it

Use it when the counts of the species that react are large (hundreds or more), so that the exact method is too slow, and a bias of a few percent is acceptable. It is common in models of metabolism, of whole cells and of large epidemics. Do not use it when the quantity of interest depends on rare events at low counts, such as the extinction of a species or the switching of a genetic toggle switch, unless the method switches to exact steps there. For stiff systems use an implicit leap or a method that treats the fast reactions separately.

Pitfalls

  • Negative counts. A plain Poisson leap can remove more molecules than exist. Do not set negative counts to 0; that biases the law. Use critical reactions and reject the leap.
  • Too large a step. A fixed τ\tau chosen for the start of a run can be far too large later, when the counts are smaller or the propensities larger. Use an adaptive step.
  • Variance as well as mean. A step that gives a good mean can still give a variance that is too large, by the factor 2/(2−τ)2/(2 - \tau) in the immigration-death example. If the noise is the object of the study, check it against an exact run.
  • The factor gig_i for dimerization. For 2Xi2X_i the factor is 2+1/(xi−1)2 + 1/(x_i - 1), not 2. The convention c x(x−1)/2c\, x(x-1)/2 for the propensity, with c=2k/(NAV)c = 2k/(N_A V), must be the same in the propensities and in the rule for gig_i.
  • The last step. The step must be cut at TT (line L8), or the state at TT is that of a later time.
  • Poisson samplers. For a large mean ajτa_j\tau, inversion by the sum of uniforms is slow and loses accuracy. Use a sampler made for large means.

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)
tau_leaping.py 222 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tau-leaping/. The authors are listed in prov/Q8TJ4W.jsonl.
"""Explicit tau-leaping for stochastic chemical kinetics.

A network with n species and m reactions is given by:
- stoich: the m change vectors (stoich[j][i] = S[i][j]);
- propensity(x): the m propensities a_j(x) of the state x;
- reactants: reactants[j][i] is the number of molecules of species i that
  reaction j uses. Only the adaptive method needs it, for the order rules
  of the step size.

fixed_step_leap is the plain method of Gillespie (2001) with a constant
step. adaptive_tau_leap is the method of Cao, Gillespie and Petzold (2006):
critical reactions, the step size of their eq. (33), the fall back to the
direct method when the step is short, and halving of the step when a leap
gives a negative count.

Both functions return (times, states, info). times[0] = 0.0 and states[0] =
tuple(x0). fixed_step_leap records every step; adaptive_tau_leap records
each step that changes the state, as the direct method does. In both,
states[-1] is the state at t_end (or at the time when all propensities are
0). info counts the leaps, the direct method steps and the rejected leaps.
"""

from __future__ import annotations

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

from biostoch import poisson

State = Tuple[int, ...]


def _apply(x: State, stoich, k: Sequence[int]) -> List[int]:
    y = list(x)
    for j, kj in enumerate(k):
        if kj:
            for i, d in enumerate(stoich[j]):
                y[i] += kj * d
    return y


def fixed_step_leap(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
                    propensity: Callable[[State], Sequence[float]], tau: float,
                    t_end: float):
    """Leap with the step tau (the last step ends at t_end).

    Each step draws k_j = poisson(rng, a_j h) for j = 0, ..., m - 1 with
    a_j > 0, in index order. If the new state has a negative count, the
    draws are thrown away and the same step is tried again with h / 2. The
    next step starts again from h = tau.
    """
    if tau <= 0:
        raise ValueError("tau must be > 0")
    x = tuple(int(v) for v in x0)
    t = 0.0
    times, states = [t], [x]
    info = {"leaps": 0, "ssa_steps": 0, "rejected": 0}
    m = len(stoich)
    while t < t_end:
        a = propensity(x)
        if sum(a) <= 0:
            break
        h = min(tau, t_end - t)
        while True:
            k = [poisson(rng, a[j] * h) if a[j] > 0 else 0 for j in range(m)]
            y = _apply(x, stoich, k)
            if min(y) >= 0:
                break
            info["rejected"] += 1
            h /= 2.0
        t = t_end if h == t_end - t else t + h
        x = tuple(y)
        times.append(t)
        states.append(x)
        info["leaps"] += 1
    return times, states, info


def highest_order_factors(reactants: Sequence[Sequence[int]]):
    """For each species i, a function g_i(x_i) as in eq. (27) of Cao,
    Gillespie and Petzold (2006). The highest order of reaction (HOR) of i
    is the largest total order of a reaction that uses i; if a reaction of
    that order uses i more than once, g_i depends on x_i."""
    n = len(reactants[0]) if reactants else 0
    out = []
    for i in range(n):
        hor, mult = 0, 0
        for row in reactants:
            if row[i] > 0:
                order = sum(row)
                if order > hor or (order == hor and row[i] > mult):
                    hor, mult = order, row[i]
        out.append(_g_rule(hor, mult))
    return out


def _g_rule(hor: int, mult: int):
    if hor <= 1:
        return lambda xi: 1.0
    if hor == 2:
        if mult == 1:
            return lambda xi: 2.0
        return lambda xi: 2.0 + 1.0 / (xi - 1) if xi > 1 else 2.0
    if hor == 3:
        if mult == 1:
            return lambda xi: 3.0
        if mult == 2:
            return lambda xi: 1.5 * (2.0 + 1.0 / (xi - 1)) if xi > 1 else 3.0
        return lambda xi: 3.0 + 1.0 / (xi - 1) + 2.0 / (xi - 2) if xi > 2 else 3.0
    raise ValueError("reactions of order above 3 are not supported")


def _ssa_step(rng, x: State, stoich, a: Sequence[float], a0: float, t: float, t_end: float):
    """One step of the direct method, with the draw order of ssa_direct.
    Returns the new (t, x), or None when the next event is after t_end."""
    tau = rng.expovariate(a0)
    if t + tau > t_end:
        return None
    u = rng.random() * a0
    acc, j = 0.0, -1
    for i, v in enumerate(a):
        if v > 0:
            acc += v
            j = i
            if u < acc:
                break
    nu = stoich[j]
    return t + tau, tuple(x[i] + nu[i] for i in range(len(x)))


def adaptive_tau_leap(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
                      propensity: Callable[[State], Sequence[float]],
                      reactants: Sequence[Sequence[int]], t_end: float,
                      eps: float = 0.03, n_c: int = 10, ssa_factor: float = 10.0,
                      ssa_steps: int = 100):
    """The tau-leaping method of Cao, Gillespie and Petzold (2006).

    Draw order in a leap: tau'' = rng.expovariate(a0c) if a0c > 0; then
    k_j = poisson(rng, a_j tau) for the noncritical j with a_j > 0, in index
    order; then, if a critical reaction fires, one u = rng.random() * a0c
    and a cumulative search over the critical reactions. A rejected leap
    draws again in the same order with tau' halved. A step of the direct
    method draws as ssa_direct does.
    """
    x = tuple(int(v) for v in x0)
    t = 0.0  # @line L1
    times, states = [t], [x]
    info = {"leaps": 0, "ssa_steps": 0, "rejected": 0}
    m, n = len(stoich), len(x)
    g = highest_order_factors(reactants)
    reactant_species = [i for i in range(n) if any(row[i] > 0 for row in reactants)]
    while t < t_end:  # @line L2
        a = list(propensity(x))  # @line L3
        a0 = sum(a)
        if a0 <= 0:
            break
        critical = [False] * m  # @line L4
        for j in range(m):
            if a[j] > 0:
                limit = math.inf
                for i, d in enumerate(stoich[j]):
                    if d < 0:
                        limit = min(limit, x[i] // (-d))
                critical[j] = limit < n_c
        tau1 = math.inf  # @line L5
        for i in reactant_species:
            mu = sum(stoich[j][i] * a[j] for j in range(m) if not critical[j])
            var = sum(stoich[j][i] ** 2 * a[j] for j in range(m) if not critical[j])
            bound = max(eps * x[i] / g[i](x[i]), 1.0)
            if mu != 0:
                tau1 = min(tau1, bound / abs(mu))
            if var > 0:
                tau1 = min(tau1, bound * bound / var)
        if tau1 < ssa_factor / a0:  # @line L6
            for _ in range(ssa_steps):
                step = _ssa_step(rng, x, stoich, a, a0, t, t_end)
                if step is None:
                    t = t_end
                    break
                t, x = step
                times.append(t)
                states.append(x)
                info["ssa_steps"] += 1
                a = list(propensity(x))
                a0 = sum(a)
                if a0 <= 0:
                    break
            if a0 <= 0:
                break
            continue
        a0c = sum(a[j] for j in range(m) if critical[j])
        while True:
            tau2 = rng.expovariate(a0c) if a0c > 0 else math.inf  # @line L7
            tau = min(tau1, tau2, t_end - t)  # @line L8
            k = [poisson(rng, a[j] * tau) if a[j] > 0 and not critical[j] else 0  # @line L9
                 for j in range(m)]
            if tau == tau2:  # @line L10
                u = rng.random() * a0c
                acc = 0.0
                for j in range(m):
                    if critical[j]:
                        acc += a[j]
                        jc = j
                        if u < acc:
                            break
                k[jc] = 1
            y = _apply(x, stoich, k)
            if min(y) >= 0:  # @line L11
                break
            info["rejected"] += 1
            tau1 /= 2.0
        if tau == math.inf:
            raise ValueError("no finite step: give a finite t_end")
        t = t_end if tau == t_end - t else t + tau  # @line L12
        info["leaps"] += 1
        if any(k):
            x = tuple(y)
            times.append(t)
            states.append(x)
    return times, states, info
test_tau_leaping.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tau-leaping/. The authors are listed in prov/Q8TJ4W.jsonl.
"""Tests of tau-leaping.

Tau-leaping is approximate, so the tests check two things: the code gives
the exact law of the leap chain where that law is known, and the error of
the leap chain against the exact process is small where the step is short
and large where it is long.

A sample mean of n values with exact mean mu and variance var must satisfy
|mean - mu| <= 4 sqrt(var / n). A sample variance must be within the
relative tolerance 4 sqrt(2 / (n - 1)) of the exact variance (near-normal
data).
"""

import math
import random

from biostoch import check_mean, mean_var, poisson, ssa_direct
from tau_leaping import adaptive_tau_leap, fixed_step_leap, highest_order_factors

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


def immig_death_1000(x):
    return (1000.0, 1.0 * x[0])


def var_ok(v, var, n):
    return abs(v / var - 1) <= Z * math.sqrt(2 / (n - 1))


def leap_death_moments(x0, tau, steps):
    """Mean and variance of the fixed step leap chain for X -> 0 at rate 1:
    x' = x - Poisson(x tau), so m' = (1 - tau) m and
    V' = (1 - tau)^2 V + tau m."""
    m, v = float(x0), 0.0
    for _ in range(steps):
        v = (1 - tau) ** 2 * v + tau * m
        m = (1 - tau) * m
    return m, v


def test_order_factors():
    # 2A -> B, A + B -> C, B -> 0.
    g = highest_order_factors([(2, 0), (1, 1), (0, 1)])
    assert g[0](11) == 2 + 1 / 10
    assert g[1](11) == 2.0
    g = highest_order_factors([(1, 0), (0, 1)])
    assert g[0](5) == 1.0 and g[1](5) == 1.0
    g = highest_order_factors([(3, 0), (1, 2)])
    assert g[0](7) == 3 + 1 / 6 + 2 / 5
    assert g[1](7) == 1.5 * (2 + 1 / 6)


def test_long_fixed_step_is_biased():
    # tau = 0.5 on pure death from 100: the leap chain has mean 25 and
    # variance 37.5 at t = 1, while the exact X(1) has mean 36.79.
    rng = random.Random(41)
    n = 400
    xs = [fixed_step_leap(rng, (100,), DEATH, death_prop, 0.5, 1.0)[1][-1][0] for _ in range(n)]
    mu, var = leap_death_moments(100, 0.5, 2)
    assert (mu, var) == (25.0, 37.5)
    m, v = mean_var(xs)
    assert check_mean(m, mu, var, n, Z)
    assert var_ok(v, var, n)
    q = math.exp(-1)
    assert not check_mean(m, 100 * q, 100 * q * (1 - q), n, Z)


def test_short_fixed_step_is_close():
    # tau = 0.01: the leap chain has mean 36.603 at t = 1, 0.5 percent
    # below the exact 36.788.
    rng = random.Random(42)
    n = 300
    xs = [fixed_step_leap(rng, (100,), DEATH, death_prop, 0.01, 1.0)[1][-1][0] for _ in range(n)]
    mu, var = leap_death_moments(100, 0.01, 100)
    m, v = mean_var(xs)
    assert check_mean(m, mu, var, n, Z)
    assert var_ok(v, var, n)
    exact = 100 * math.exp(-1)
    assert abs(mu - exact) / exact < 0.006


def test_stationary_variance_of_fixed_step():
    # For immigration-death the leap chain has the stationary mean 10 and
    # the stationary variance 20 / (2 - tau); the exact law is Poisson(10).
    rng = random.Random(43)
    n = 2000
    tau = 0.5
    xs = [fixed_step_leap(rng, (poisson(rng, 10.0),), IMMIG_DEATH, immig_death_prop, tau, 10.0)[1][-1][0]
          for _ in range(n)]
    m, v = mean_var(xs)
    leap_var = 20 / (2 - tau)
    assert check_mean(m, 10.0, leap_var, n, Z)
    assert var_ok(v, leap_var, n)
    assert not var_ok(v, 10.0, n)


def test_negative_counts_are_rejected():
    rng = random.Random(44)
    rejected = 0
    for _ in range(200):
        times, states, info = fixed_step_leap(rng, (3,), DEATH, death_prop, 1.0, 3.0)
        assert all(s[0] >= 0 for s in states)
        assert times[-1] == 3.0 or states[-1] == (0,)
        rejected += info["rejected"]
    assert rejected > 0


def test_all_critical_is_the_direct_method():
    # A <-> B with 8 molecules: every reaction is critical (L_j < 10), so
    # each step fires one reaction after an Exp(a0) wait, with the same
    # draws as ssa_direct.
    stoich = [(-1, 1), (1, -1)]
    reactants = [(1, 0), (0, 1)]

    def prop(x):
        return (1.0 * x[0], 2.0 * x[1])

    for seed in range(5):
        a = adaptive_tau_leap(random.Random(seed), (8, 0), stoich, prop, reactants, 3.0)
        b = ssa_direct(random.Random(seed), (8, 0), stoich, prop, 3.0)
        assert a[0] == b[0] and a[1] == b[1]
        assert a[2]["ssa_steps"] == 0


def test_adaptive_pure_death_is_close():
    # eps = 0.03 from 1000: about 34 leaps instead of about 632 events, and
    # the mean at t = 1 is within 3 percent of 1000 e^-1.
    rng = random.Random(45)
    n = 200
    xs, steps = [], 0
    for _ in range(n):
        times, states, info = adaptive_tau_leap(rng, (1000,), DEATH, death_prop, [(1,)], 1.0)
        xs.append(states[-1][0])
        steps += info["leaps"] + info["ssa_steps"]
    m, _ = mean_var(xs)
    exact = 1000 * math.exp(-1)
    assert abs(m - exact) / exact < 0.03
    assert steps / n < 50
    assert all(x >= 0 for x in xs)


def test_adaptive_stationary_variance_is_inflated():
    # Immigration-death with rates 1000 and 1: the leap condition holds
    # (steps near 0.44) and the mean stays at 1000, but the stationary
    # variance is near 2000 / (2 - 0.44), not the exact 1000.
    rng = random.Random(46)
    n = 1000
    xs = [adaptive_tau_leap(rng, (poisson(rng, 1000.0),), IMMIG_DEATH, immig_death_1000,
                            [(0,), (1,)], 5.0)[1][-1][0] for _ in range(n)]
    m, v = mean_var(xs)
    assert check_mean(m, 1000.0, 2000 / (2 - 0.52), n, Z)
    assert v / 1000.0 - 1 > Z * math.sqrt(2 / (n - 1))

History

Gillespie (2001) proposed tau-leaping and the leap condition, and showed that the Poisson leap tends to the chemical Langevin equation and then to the rate equations as the counts grow. The first versions could make counts negative. Cao, Gillespie and Petzold (2005) introduced critical reactions to avoid this, and in 2006 they gave the step size rule of eq. 33, with the switch to exact steps, which is the form in most software. Rathinam, Petzold, Cao and Gillespie (2003) gave the implicit version for stiff systems, Tian and Burrage (2004) the binomial version, and Anderson (2008) the post-leap checks. Tau-leaping is in StochKit, COPASI and GillesPy2.

References

  1. Daniel T. Gillespie, Approximate accelerated stochastic simulation of chemically reacting systems, Journal of Chemical Physics 115(4), 2001, 1716-1733, the leap condition, the Poisson leap, and its limits as the chemical Langevin equation and the rate equations
  2. Yang Cao, Daniel T. Gillespie and Linda R. Petzold, Avoiding negative populations in explicit Poisson tau-leaping, Journal of Chemical Physics 123(5), 2005, 054104, the critical reactions, which are fired at most once per leap
  3. Yang Cao, Daniel T. Gillespie and Linda R. Petzold, Efficient step size selection for the tau-leaping simulation method, Journal of Chemical Physics 124(4), 2006, 044109, Section II C and eqs. 27 and 33 (the factors g_i and the step size), and Section IV (the full procedure, with the switch to exact steps)
  4. Muruhan Rathinam, Linda R. Petzold, Yang Cao and Daniel T. Gillespie, Stiffness in stochastic chemically reacting systems, the implicit tau-leaping method, Journal of Chemical Physics 119(24), 2003, 12784-12794, the implicit leap for systems with fast reactions that reach equilibrium

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