Algorithmresearch
Finite state projection
Also called FSP.
Solves the chemical master equation on a finite set of states, with a certified bound on the error from the probability that leaves the set.
- Time
- O(R s m (q t + 1)) worst
- Space
- Θ(s m) extra
- Where
- R = the number of rounds of growth; epsilon = the error tolerance; m = the number of reactions; q = the largest total propensity on the projection; s = the number of states in the final projection; t = the end time
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian Munsky, Mustafa Khammash, 2006
Finite state projection (FSP) computes the probabilities of the chemical master equation directly, without sampling. The master equation is linear, but its state space is usually infinite, or finite and far too large to list. FSP keeps only a finite set of states, solves the master equation restricted to with the matrix exponential, and lets the probability that flows out of disappear. Munsky and Khammash (2006) proved that this is safe in a precise sense: the computed values are never above the true probabilities, and the total error, measured in the L1 norm over all states, equals exactly the probability that was lost. So the sum of the computed values certifies its own accuracy. If the lost mass is larger than the tolerance, the algorithm adds the states that the reactions reach from and solves again. It is the method of choice for small networks such as models of one or two genes, where it gives the full distribution with an error of or less.
In plain words
The exact equation tracks the chance of every possible count of molecules, and there are endlessly many counts. But most of them are so unlikely that they do not matter.
So pick a list of counts that you think matter, and track only those. Chance that would move to a count outside the list is simply dropped. At the end, add up what is left. If the total is 0.999999, you know that you lost at most one part in a million, and that no answer is off by more than that in total.
If too much was lost, the list was too short. Add the counts that can be reached in one reaction from the list, and solve again. Repeat until the loss is small enough.
The problem
Input. A network with change vectors and propensities ; a start state (or a start distribution with finite support); a time ; a tolerance .
Output. A finite set of states and a vector on such that
where solves the master equation. The second sum is the L1 distance between and extended by 0.
The projection. Let be the generator restricted to the rows and columns in : and when , for . Its columns sum to 0 or less: the deficit in column is the rate at which probability leaves from . The projected solution is .
The algorithm
FSP(x0, ν, a, t, ε)- 1
J ← {x0} - 2
loop - 3
build the sparse matrix A_J on J - 4
p ← exp(A_J t) e_x0 - 5
if 1 - Σ_{x ∈ J} p(x) ≤ ε then return (J, p) - 6
J ← J ∪ {x + ν_j : x ∈ J, a_j(x) > 0}
Line L4 is the action of the matrix exponential on a vector. The implementation uses uniformization: with and , , where every term is . It splits into pieces with so that the Poisson weights stay in floating point range. Large problems use a Krylov method instead. Line L6 adds every state that one reaction reaches from , so after rounds holds every state reachable in at most reactions.
Example
Take immigration-death, at rate 10 and at rate , from to . The exact law is Poisson = Poisson. Here line L6 adds one state per round, so after rounds.
| tolerance | states in | lost mass |
|---|---|---|
| 15 | ||
| 19 | ||
| 23 | ||
| 26 | ||
| 32 |
Each factor of 100 in the tolerance costs only a few more states, because the Poisson tail falls faster than geometrically.
A projection that is too small shows how the bound works. With :
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| FSP | 0.001761 | 0.010878 | 0.032807 | 0.062846 | 0.081337 | 0.063639 |
| exact | 0.001798 | 0.011364 | 0.035917 | 0.075680 | 0.119598 | 0.151201 |
Every value is below the exact one, as the theorem says. The lost mass is 0.746732, which is larger than the true tail : the projection also loses the paths that leave and come back. The sum of the errors in , , plus the tail is the lost mass, as the identity says.
Correctness
The key fact is that has entries , because has entries . Write the rows of the full master equation for the states in as , where is the flow into from outside. By variation of constants, . So on , every error term in is , and the L1 error adds up to . A larger gives larger values, so the lost mass only goes down as grows. The loop stops: holds all states reachable in reactions, the lost mass is at most the probability of more than jumps in , and this tends to 0 if the process does not explode. Cutting the uniformization series keeps the bound, since every term is . The full proof is below.
Proof: The finite state projection bound and its convergencefull
Let the reachable states of a network be countable, ordered in some way, and let be the generator of the chemical master equation : , for , and all other entries 0. So for , and each column sums to 0. Assume that the jump process with these rates does not explode on , so that is a probability vector for and solves the master equation.
For a finite set of states, let be the submatrix of on the rows and columns in , and let , where is the start distribution restricted to .
Lemma 1 (). Every entry of is for .
Proof. Let . Then has entries : off the diagonal they are those of , and on the diagonal . Since commutes with , , a sum of matrices with entries .
Theorem 1 (Munsky and Khammash 2006). For every , , and
So if , the L1 error of (set to 0 outside ) is at most .
Proof. Split the states into and its complement . The rows of the master equation for the states in read
where holds the rates from states outside into . Its entries are , and so are those of . Let . By variation of constants,
By Lemma 1 the integrand has entries , so in every entry, and by Lemma 1 again. Then each term for equals , and the left side of the identity is .
There is also a probabilistic reading: is the probability that and that stayed in during all of . Mass that leaves is lost, even if the process could come back.
Lemma 2 (larger sets give larger values). If , then for .
Proof. Apply the proof of Theorem 1 with in place of the full space: the rows of for the states in are , with a forcing term , so .
So the lost mass can only go down when grows.
Theorem 2 (the loop stops). Start the loop with and the start law , and let line L6 add every state that one reaction with a positive propensity reaches from . For every , the loop stops after finitely many rounds.
Proof. After rounds, contains every state that can reach from with at most reactions. On the event that makes at most jumps in , the path stays in . By the probabilistic reading above, . Since does not explode, this probability tends to 1 as , so the lost mass drops below for some finite .
Lemma 3 (uniformization in the code). Let , , and . Then , every term has entries , and cutting the series after any number of terms gives a vector in every entry.
Proof. with as in Lemma 1, and . The terms are because and , so a partial sum is below the full sum. The code splits into pieces of length with and uses . Each cut series gives a vector below the exact one, and applying the nonnegative matrix to a smaller vector gives a smaller vector, so the computed result is still below .
So the mass that the code reports as lost, , is at least the true lost mass of Theorem 1, and the bound of Theorem 1 still holds for the computed vector (up to rounding in floating point).
Complexity
- One round. has at most nonzeros per column. Uniformization needs about products with , so a round costs . With a Krylov method the number of products is often much smaller than for stiff problems.
- Rounds. Growth by one reaction step per round needs as many rounds as the number of reactions that typical paths make, in the bound. Growing by several steps at a time, or starting with a good guess (for example from a few runs of the Gillespie algorithm), cuts to a few.
- States. The main cost is , the size of the final projection. For species whose counts each range over about values, is about , so the method is limited to a few species with moderate counts. This is the curse of dimensionality of the master equation.
- Space. The sparse matrix with nonzeros and a few vectors of length .
Properties
- Certified error. The output carries its own bound: the lost mass is an upper bound on the L1 error, with no sampling noise and no unknown constant.
- One-sided. Every computed probability is at most the true one. Sums over sets of states are lower bounds, and adding the lost mass gives upper bounds.
- Monotone. A larger projection gives larger values in every state of the smaller one.
- Deterministic. The same input gives the same output. The whole distribution comes at once, including the tails and rare states that sampling would almost never visit.
- Exact for finite closed systems. If holds every reachable state, nothing is lost, and is the exact solution up to the error of the matrix exponential.
Variants and improvements
- Krylov methods. Compute with an Arnoldi iteration in a Krylov subspace, which works well for the stiff matrices of networks with fast and slow reactions.
- Time stepping. Split into intervals and allow a different on each, adding states where the mass moves and dropping states that become negligible (sliding windows). The error bounds of the intervals add up.
- Aggregation and reduction. Lump states that behave alike, or reduce the number of states with a reduced basis or a tensor format, at the cost of a bound that is harder to prove.
- Stationary distributions. The same truncation idea, with the outflow sent back to a chosen state, gives approximations of the stationary distribution, with error bounds under conditions on the drift.
- Inference. Because FSP gives exact likelihoods of measured count distributions, it is used to fit gene expression models to single-cell data, for example from smFISH, by maximum likelihood.
When to use it
Use it when the network has few species and the counts are at most a few hundred, so that the relevant states number up to about , and when the full distribution or small probabilities are needed with a guaranteed error: models of a gene that switches between active and inactive, of transcription bursts, or of a small regulatory circuit fit to single-cell counts. For many species or large counts, sample with the Gillespie algorithm, or approximate with the linear noise approximation or moment closure.
Pitfalls
- Normalizing the result. Dividing by its sum gives a vector that looks better but has no error bound; it can be above the true values. Report the lost mass instead.
- Lost mass is not the tail. The lost mass counts paths that left at any time, not only those outside at time , so it is larger than the tail probability. A projection can lose much mass even when the final distribution lies inside .
- Bad growth. Adding states in all directions in many species makes huge. Grow along the directions where the mass flows out, or use a shape such as a box or a simplex guided by sample runs.
- Explosion and infinite time. The bound needs a process that does not explode on . As in an open system, nearly all mass leaves any fixed , so stationary laws need the variant with the outflow sent back.
- Floating point. For large , plain uniformization underflows ( is 0), which is why the code splits the time. Rounding errors can also make tiny probabilities slightly negative in other matrix exponential methods; clip them.
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
# Part of https://algorithm.tamnd.com/finite-state-projection/. The authors are listed in prov/62X0PG.jsonl.
"""The finite state projection (FSP) of Munsky and Khammash (2006).
A network with n species and m reactions is given by stoich (the m change
vectors) and propensity(x) (the m propensities of the state x). The
chemical master equation is dP/dt = A P for the generator A on all states.
The FSP keeps a finite set J of states and solves dp/dt = A_J p, where A_J
is A with the rows and columns outside J removed. Probability that flows
out of J is lost, so 1 - sum(p) is the mass that left J. That mass is a
bound on the L1 error of p against the exact solution.
exp(A_J t) p0 is computed by uniformization: with q >= max a0(x) on J,
P = I + A_J / q has entries >= 0 and exp(A_J t) = sum over k of
Poisson(k; q t) P^k. Every term is >= 0, so cutting the series only lowers
the result, and the computed mass that left J is still an upper bound on
the error.
"""
from __future__ import annotations
import math
from typing import Callable, Dict, List, Sequence, Tuple
State = Tuple[int, ...]
def project_generator(states: Sequence[State], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]]):
"""The sparse generator A_J on the list `states`.
Returns (out_rate, edges): out_rate[s] = a0 of states[s] (the negative
of the diagonal of A_J), and edges is a list of (s, r, rate) for the
flows from states[s] to states[r] inside J. Flows to states outside J
are left out: that mass is lost.
"""
index = {x: s for s, x in enumerate(states)}
out_rate = []
edges = []
for s, x in enumerate(states):
a = propensity(x)
total = 0.0
for j, aj in enumerate(a):
if aj < 0:
raise ValueError("propensities must be >= 0")
if aj == 0:
continue
total += aj
y = tuple(x[i] + stoich[j][i] for i in range(len(x)))
r = index.get(y)
if r is not None:
edges.append((s, r, aj))
out_rate.append(total)
return out_rate, edges
def expm_action(out_rate: Sequence[float], edges, p0: Sequence[float], t: float,
tol: float = 1e-15) -> List[float]:
"""exp(A_J t) p0 by uniformization, in pieces with q dt <= 10."""
q = max(out_rate, default=0.0)
p = [float(v) for v in p0]
if q == 0.0 or t == 0.0:
return p
pieces = max(1, math.ceil(q * t / 10.0))
lam = q * t / pieces
keep = [1.0 - r / q for r in out_rate]
k_max = int(lam + 10.0 * math.sqrt(lam) + 40)
for _ in range(pieces):
term = p
weight = math.exp(-lam)
acc = [weight * v for v in term]
cum = weight
for k in range(1, k_max + 1):
nxt = [keep[s] * term[s] for s in range(len(term))]
for s, r, rate in edges:
nxt[r] += rate / q * term[s]
term = nxt
weight *= lam / k
cum += weight
for s in range(len(acc)):
acc[s] += weight * term[s]
if 1.0 - cum < tol:
break
p = acc
return p
def neighbors(states: Sequence[State], stoich, propensity) -> List[State]:
"""The states outside `states` that one reaction with a positive
propensity reaches from a state in `states`."""
inside = set(states)
new = []
for x in states:
for j, aj in enumerate(propensity(x)):
if aj > 0:
y = tuple(x[i] + stoich[j][i] for i in range(len(x)))
if y not in inside:
inside.add(y)
new.append(y)
return new
def finite_state_projection(x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t: float,
eps: float, initial: Sequence[State] = (), max_states: int = 20000):
"""Grow J from {x0} (and `initial`) until the mass that left J by time t
is at most eps.
Returns (states, p, lost, rounds): p[s] is the FSP probability of
states[s] at time t, lost = 1 - sum(p), and rounds is the number of
solves. Then 0 <= P(x, t) - p(x) for every x in J, and the sum of
|P(x, t) - p(x)| over all states (p = 0 outside J) is lost.
"""
x0 = tuple(int(v) for v in x0)
states = [x0] + [tuple(s) for s in initial if tuple(s) != x0] # @line L1
rounds = 0
while True: # @line L2
out_rate, edges = project_generator(states, stoich, propensity) # @line L3
p0 = [1.0 if s == 0 else 0.0 for s in range(len(states))]
p = expm_action(out_rate, edges, p0, t) # @line L4
rounds += 1
lost = 1.0 - sum(p)
if lost <= eps: # @line L5
return states, p, lost, rounds
new = neighbors(states, stoich, propensity) # @line L6
if not new or len(states) + len(new) > max_states:
raise RuntimeError("the projection cannot grow to reach the tolerance")
states = states + new
test_finite_state_projection.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-state-projection/. The authors are listed in prov/62X0PG.jsonl.
"""Tests of the finite state projection.
The exact laws are closed forms: Binomial(x0, e^-t) for pure death,
Binomial(x0, e^-t) + Poisson(10 (1 - e^-t)) for immigration-death, and
Binomial(N, p(t)) for N independent molecules that switch A <-> B. A
closed dimerization system is checked against a dense matrix exponential
by scaling and squaring of the Taylor series.
"""
import math
from finite_state_projection import expm_action, finite_state_projection, project_generator
def binom_pmf(k, n, p):
if k < 0 or k > n:
return 0.0
return math.comb(n, k) * p ** k * (1 - p) ** (n - k)
def poisson_pmf(k, lam):
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def immigration_death_pmf(k, x0, t, b=10.0):
q = math.exp(-t)
lam = b * (1 - q)
return sum(binom_pmf(i, x0, q) * poisson_pmf(k - i, lam) for i in range(min(k, x0) + 1))
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 test_pure_death_on_the_full_space():
states = [(k,) for k in range(101)]
J, p, lost, rounds = finite_state_projection((100,), DEATH, death_prop, 1.0, 1e-12, initial=states)
assert rounds == 1 and abs(lost) < 1e-12
q = math.exp(-1)
assert max(abs(p[s] - binom_pmf(J[s][0], 100, q)) for s in range(len(J))) < 1e-12
mean = sum(J[s][0] * p[s] for s in range(len(J)))
var = sum(J[s][0] ** 2 * p[s] for s in range(len(J))) - mean ** 2
assert abs(mean - 36.787944) < 1e-6 and abs(var - 23.254416) < 1e-6
def test_growth_reaches_the_tolerance_and_bounds_the_error():
eps = 1e-6
J, p, lost, rounds = finite_state_projection((0,), IMMIG_DEATH, immig_death_prop, 1.0, eps)
assert 0 <= lost <= eps and rounds == len(J)
exact = [immigration_death_pmf(x[0], 0, 1.0) for x in J]
# The FSP value is below the exact value in every state.
assert all(p[s] <= exact[s] + 1e-13 for s in range(len(J)))
# The L1 error over all states is the lost mass.
l1 = sum(abs(exact[s] - p[s]) for s in range(len(J))) + (1 - sum(exact))
assert abs(l1 - lost) < 1e-12
def test_immigration_death_from_five():
J, p, lost, _ = finite_state_projection((5,), IMMIG_DEATH, immig_death_prop, 2.0, 1e-9)
assert lost <= 1e-9
assert max(abs(p[s] - immigration_death_pmf(J[s][0], 5, 2.0)) for s in range(len(J))) <= 1e-9
def test_small_projection_loses_mass():
# J = {0, ..., 5} for immigration-death from 0 at t = 1. Mass that leaves
# J is lost even if the process could come back, so the lost mass is at
# least the exact P(X(1) > 5), and it is still the L1 error.
states = [(k,) for k in range(6)]
J, p, lost, _ = finite_state_projection((0,), IMMIG_DEATH, immig_death_prop, 1.0, 1.0, initial=states)
exact = [immigration_death_pmf(k, 0, 1.0) for k in range(6)]
tail = 1 - sum(exact)
assert lost >= tail > 0.3
l1 = sum(abs(exact[s] - p[s]) for s in range(6)) + tail
assert abs(l1 - lost) < 1e-12
def test_larger_projection_is_larger_everywhere():
small = [(k,) for k in range(8)]
large = [(k,) for k in range(15)]
_, p_small, lost_small, _ = finite_state_projection((0,), IMMIG_DEATH, immig_death_prop, 1.0, 1.0, initial=small)
_, p_large, lost_large, _ = finite_state_projection((0,), IMMIG_DEATH, immig_death_prop, 1.0, 1.0, initial=large)
assert lost_large < lost_small
assert all(p_small[s] <= p_large[s] + 1e-15 for s in range(8))
def test_two_state_molecules_are_binomial():
# A -> B at rate 2 per molecule and B -> A at rate 1, 12 molecules, all
# A at t = 0. Each molecule is A at time t with probability
# 1/3 + 2/3 e^-3t, independently of the others.
stoich = [(-1, 1), (1, -1)]
def prop(x):
return (2.0 * x[0], 1.0 * x[1])
t = 0.4
J, p, lost, _ = finite_state_projection((12, 0), stoich, prop, t, 1e-12)
assert len(J) == 13 and abs(lost) < 1e-12
pa = 1 / 3 + 2 / 3 * math.exp(-3 * t)
assert max(abs(p[s] - binom_pmf(J[s][0], 12, pa)) for s in range(13)) < 1e-12
def dense_expm(a):
"""exp(a) by scaling and squaring of the Taylor series (dense)."""
n = len(a)
norm = max(sum(abs(v) for v in row) for row in a)
s = max(0, math.ceil(math.log2(norm / 0.5))) if norm > 0.5 else 0
b = [[v / 2 ** s for v in row] for row in a]
result = [[float(i == j) for j in range(n)] for i in range(n)]
term = [row[:] for row in result]
for k in range(1, 30):
term = [[sum(term[i][l] * b[l][j] for l in range(n)) / k for j in range(n)] for i in range(n)]
result = [[result[i][j] + term[i][j] for j in range(n)] for i in range(n)]
for _ in range(s):
result = [[sum(result[i][l] * result[l][j] for l in range(n)) for j in range(n)] for i in range(n)]
return result
def test_dimerization_against_dense_expm():
# 2A -> B with propensity 1 * x_A (x_A - 1) / 2 and B -> 2A at rate 0.5
# per molecule, from (10, 0). The states are (10 - 2b, b), b = 0..5.
stoich = [(-2, 1), (2, -1)]
def prop(x):
return (1.0 * x[0] * (x[0] - 1) / 2, 0.5 * x[1])
t = 0.7
J, p, lost, _ = finite_state_projection((10, 0), stoich, prop, t, 1e-12)
assert sorted(J) == [(10 - 2 * b, b) for b in range(5, -1, -1)]
# The dense generator, written from the reactions directly.
n = 6
gen = [[0.0] * n for _ in range(n)]
for b in range(n):
xa = 10 - 2 * b
forward = xa * (xa - 1) / 2
backward = 0.5 * b
gen[b][b] = -(forward + backward)
if b + 1 < n:
gen[b + 1][b] += forward
if b > 0:
gen[b - 1][b] += backward
e = dense_expm([[v * t for v in row] for row in gen])
for s, x in enumerate(J):
assert abs(p[s] - e[x[1]][0]) < 1e-11
def test_expm_action_of_zero_rates():
out_rate, edges = project_generator([(0,)], DEATH, death_prop)
assert out_rate == [0.0] and edges == []
assert expm_action(out_rate, edges, [1.0], 5.0) == [1.0]
History
Munsky and Khammash introduced the finite state projection and its error bound in 2006, as a way to solve the chemical master equation directly for the small, noisy circuits of systems biology, where Monte Carlo estimates of rare events converge slowly. Many refinements followed in the next years: Krylov methods for the matrix exponential, multiple time intervals with moving sets, sliding windows, and stationary versions. Since about 2013, FSP has been used to fit models of transcription to single-molecule counts of mRNA in single cells, in work by Munsky and others.
References
- Brian Munsky and Mustafa Khammash, The finite state projection algorithm for the solution of the chemical master equation, Journal of Chemical Physics 124(4), 2006, 044104, the projection of the master equation onto a finite set of states, the bound on the error by the lost probability, and the algorithm that grows the set
- Tobias Jahnke and Wilhelm Huisinga, Solving the chemical master equation for monomolecular reaction systems analytically, Journal of Mathematical Biology 54(1), 2007, 1-26, closed form solutions for first order networks, useful as test cases
- Darren J. Wilkinson, Stochastic Modelling for Systems Biology, 3rd edition, CRC Press, 2018, the chapter on Markov processes in continuous time (the generator and the matrix exponential)
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 62X0PG Edit this page History Report an error Markdown