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
- Model
- Real RAM
- Properties
- randomizednot exactrandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and fires every reaction a random number of times, drawn from a Poisson law with mean , 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 is small enough that they change little: the leap condition. The method of Cao, Gillespie and Petzold (2006) chooses from a parameter 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 species and reactions: change vectors , mass action propensities , and the reactant orders of each reaction; a start state ; an end time ; the error control parameter (0.03 is common); the threshold for critical reactions (10 is common).
Output. An approximate sample path of the jump process on : times and states, with every count .
The leap. If in state the propensities stay at for all of , the numbers of firings are independent with Poisson, and
The step size. Let and , over the noncritical reactions, for each species that is a reactant somewhere. The rule of Cao, Gillespie and Petzold (2006, eq. 33) is
which bounds the expected change and the standard deviation of the change of each in one leap by (or by 1 for small counts). The factor depends on the highest order reaction in which species is a reactant (eq. 27): for first order, for , for , and similar values for third order. It makes the relative change of every propensity at most about .
The algorithm
A reaction is critical if it can fire fewer than more times before one of its reactants runs out.
TAU-LEAP(x0, ν, a, T, ε, n_c)- 1
t ← 0; x ← x0; record (0, x) - 2
while t < T do - 3
compute a_j(x) and a0; if a0 = 0 then return the record - 4
mark reaction j critical if a_j(x) > 0 and it can fire fewer than n_c times - 5
τ' ← the step size of eq. 33 over the noncritical reactions - 6
if τ' < 10 / a0 then do 100 steps of the direct method and go to L2 - 7
τ'' ← Exp(a0c), where a0c is the sum of the critical propensities (∞ if a0c = 0) - 8
τ ← min(τ', τ'', T - t) - 9
K_j ← Poisson(a_j(x) τ) for each noncritical j; K_j ← 0 for each critical j - 10
if τ = τ'' then pick one critical j with probability a_j / a0c and set K_j ← 1 - 11
if x + Σ K_j ν_j has a negative entry then τ' ← τ' / 2 and go to L7 - 12
t ← 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 at rate 1 per molecule, , and leap with a fixed (no critical reactions, no switch). A leap maps to with Poisson, so the mean is multiplied by per leap, and the mean at is . The variance follows from .
| leaps | mean at | variance at | |
|---|---|---|---|
| 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 , as for the Euler method. With 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 and , line L5 gives while . A run to takes about 34 leaps, against an average of events for the exact method. The mean over 200 runs is 363.5, and the leap chain with predicts , against the exact 367.9: about 1.5 percent low.
Noise is distorted too. For immigration-death ( at rate , at rate ), a leap chain with a fixed has the right stationary mean , but the stationary variance instead of . With and that is 10.526; with it is 13.33. With , the adaptive method gives a mean near 1000 and a variance near 1340, with mean step 0.444, close to . 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 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 the method tends to the exact process; as the counts grow with 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 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 , change vectors , and the Markov jump process of the chemical master equation.
Claim 1 (exact for constant propensities). Suppose that the propensities stay at on whatever reactions fire. Then the numbers of firings of the reactions in that interval are independent, with Poisson of mean .
Proof. With constant rates, the firings of reaction form a Poisson process of rate , and the processes of different reactions are independent (a jump process with constant rates splits into independent Poisson processes, one per reaction). The count of a Poisson process of rate in an interval of length is Poisson of mean .
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 , and a leap uses their values at the start of the step. That is the approximation.
Claim 2 (the leap condition). Let be the value of line L5, and let be the set of reactant species. For each , write and . Then for every leap of length in which no critical reaction fires,
where is the change of species in the leap.
Proof. In such a leap, the of the noncritical reactions are independent Poisson variables of mean , so and . Write . Line L5 takes and for each (a term with a zero denominator puts no bound). So and .
Cao, Gillespie and Petzold (2006) choose from the highest order reaction in which species is a reactant so that a relative change of at most in changes each propensity by a relative amount of at most about . For example, for with propensity , a change in changes the propensity by the factor , whose first order part in is , the value of for this case. The bound "at least 1" on 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 .
Proof. A leap is accepted at line L11 only if 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 . The repeat terminates with probability 1: as , the probability that every noncritical is 0 tends to 1, and a leap in which only one critical reaction fires once (or nothing fires) never makes a count negative.
Claim 4 (all critical gives the direct method). If every reaction with is critical in the state , the step from has the law of one step of the direct method.
Proof. With no noncritical reaction, , so and line L6 does not switch. Line L7 draws exponential with rate . Line L8 gives , and line L9 sets every . If , line L10 picks one reaction with probability and fires it once. This is the next reaction density of Lemma 2 of the proof for the direct method, and when no reaction fires in , as in the direct method.
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 at rate 1 per molecule, a leap of length maps to with Poisson of mean (ignore the rare rejected leaps). By the laws of total expectation and variance, and . So after steps the mean is , against the exact . For immigration-death with rates and 1, and . The fixed point is and , against the exact stationary variance . So the leap chain has the right stationary mean, and a stationary variance that is too large by the factor , for .
Complexity
- Per leap. Line L3 costs propensities, line L4 for the critical test, and line L5 for the sums and (less with a sparse stoichiometric matrix). Line L9 draws up to Poisson numbers, each in expected time with a good sampler. So a leap costs , and with sparse loops.
- Number of leaps. The step is about times the time scale on which the counts change, so the number of leaps over a fixed interval is about 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. , plus the record.
Properties
- Approximate. The bias in the mean and the variance is of order for a fixed step. The adaptive rule keeps the relative change of the propensities in a step near .
- Nonnegative counts. With critical reactions and the check of line L11, every recorded count is .
- 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 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 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 and 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 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 in the immigration-death example. If the noise is the object of the study, check it against an exact run.
- The factor for dimerization. For the factor is , not 2. The convention for the propensity, with , must be the same in the propensities and in the rule for .
- The last step. The step must be cut at (line L8), or the state at is that of a later time.
- Poisson samplers. For a large mean , 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.
# 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Q8TJ4W Edit this page History Report an error Markdown