Algorithm Search⌘K

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
Properties
deterministicnot exactiterative
Origin
Brian Munsky, Mustafa Khammash, 2006

Finite state projection (FSP) computes the probabilities of the chemical master equation directly, without sampling. The master equation P˙=AP\dot P = AP is linear, but its state space is usually infinite, or finite and far too large to list. FSP keeps only a finite set JJ of states, solves the master equation restricted to JJ with the matrix exponential, and lets the probability that flows out of JJ 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 JJ 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 10−610^{-6} 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 νj\nu_j and propensities aj(x)a_j(x); a start state x0x_0 (or a start distribution with finite support); a time tt; a tolerance ϵ>0\epsilon > 0.

Output. A finite set JJ of states and a vector pp on JJ such that

0≤p(x)≤P(x,t) for x∈J,∑x∈J∣P(x,t)−p(x)∣+∑x∉JP(x,t)≤ϵ,0 \le p(x) \le P(x, t) \text{ for } x \in J, \qquad \sum_{x \in J} |P(x, t) - p(x)| + \sum_{x \notin J} P(x, t) \le \epsilon,

where PP solves the master equation. The second sum is the L1 distance between P(⋅,t)P(\cdot, t) and pp extended by 0.

The projection. Let AJA_J be the generator restricted to the rows and columns in JJ: (AJ)xx=−a0(x)(A_J)_{xx} = -a_0(x) and (AJ)yx=aj(x)(A_J)_{yx} = a_j(x) when y=x+νjy = x + \nu_j, for x,y∈Jx, y \in J. Its columns sum to 0 or less: the deficit in column xx is the rate at which probability leaves JJ from xx. The projected solution is p(t)=eAJtp(0)p(t) = e^{A_J t} p(0).

The algorithm

  1. FSP(x0, ν, a, t, ε)
  2. 1J ← {x0}
  3. 2loop
  4. 3build the sparse matrix A_J on J
  5. 4p ← exp(A_J t) e_x0
  6. 5if 1 - Σ_{x ∈ J} p(x) ≤ ε then return (J, p)
  7. 6J ← 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 q≥max⁡x∈Ja0(x)q \ge \max_{x \in J} a_0(x) and Q=I+AJ/qQ = I + A_J/q, eAJt=∑ke−qt(qt)kk!Qke^{A_J t} = \sum_k e^{-qt} \frac{(qt)^k}{k!} Q^k, where every term is ≥0\ge 0. It splits tt into pieces with q δt≤10q\,\delta t \le 10 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 JJ, so after NN rounds JJ holds every state reachable in at most NN reactions.

Example

Take immigration-death, ∅→X\emptyset \to X at rate 10 and X→∅X \to \emptyset at rate xx, from x0=0x_0 = 0 to t=1t = 1. The exact law is Poisson(10(1−e−1))(10(1 - e^{-1})) = Poisson(6.321206)(6.321206). Here line L6 adds one state per round, so J={0,…,s−1}J = \{0, \ldots, s - 1\} after ss rounds.

tolerance ϵ\epsilon states in JJ lost mass
10−210^{-2} 15 4.2×10−34.2 \times 10^{-3}
10−410^{-4} 19 7.0×10−57.0 \times 10^{-5}
10−610^{-6} 23 5.19×10−75.19 \times 10^{-7}
10−810^{-8} 26 8.3×10−98.3 \times 10^{-9}
10−1210^{-12} 32 8.1×10−138.1 \times 10^{-13}

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 J={0,…,5}J = \{0, \ldots, 5\}:

xx 0 1 2 3 4 5
FSP p(x)p(x) 0.001761 0.010878 0.032807 0.062846 0.081337 0.063639
exact P(x,1)P(x, 1) 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 P(X>5)=0.604442P(X > 5) = 0.604442: the projection also loses the paths that leave JJ and come back. The sum of the errors in JJ, 0.746732−0.604442=0.1422900.746732 - 0.604442 = 0.142290, plus the tail is the lost mass, as the identity says.

Correctness

The key fact is that eAJse^{A_J s} has entries ≥0\ge 0, because AJ+qIA_J + qI has entries ≥0\ge 0. Write the rows of the full master equation for the states in JJ as P˙J=AJPJ+f\dot P_J = A_J P_J + f, where f≥0f \ge 0 is the flow into JJ from outside. By variation of constants, PJ(t)=eAJtPJ(0)+∫0teAJ(t−s)f(s) ds≥eAJtPJ(0)=p(t)P_J(t) = e^{A_J t} P_J(0) + \int_0^t e^{A_J(t-s)} f(s)\, ds \ge e^{A_J t} P_J(0) = p(t). So p≤Pp \le P on JJ, every error term in JJ is P(x,t)−p(x)P(x, t) - p(x), and the L1 error adds up to 1−∑p1 - \sum p. A larger JJ gives larger values, so the lost mass only goes down as JJ grows. The loop stops: JNJ_N holds all states reachable in NN reactions, the lost mass is at most the probability of more than NN jumps in [0,t][0, t], and this tends to 0 if the process does not explode. Cutting the uniformization series keeps the bound, since every term is ≥0\ge 0. 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 AA be the generator of the chemical master equation P˙=AP\dot P = A P: Axx=−a0(x)A_{xx} = -a_0(x), Ayx=∑j:x+νj=yaj(x)A_{yx} = \sum_{j : x + \nu_j = y} a_j(x) for y≠xy \ne x, and all other entries 0. So Ayx≥0A_{yx} \ge 0 for y≠xy \ne x, and each column sums to 0. Assume that the jump process XX with these rates does not explode on [0,t][0, t], so that P(⋅,s)P(\cdot, s) is a probability vector for s≤ts \le t and solves the master equation.

For a finite set JJ of states, let AJA_J be the submatrix of AA on the rows and columns in JJ, and let pJ(s)=eAJsPJ(0)p_J(s) = e^{A_J s} P_J(0), where PJ(0)P_J(0) is the start distribution restricted to JJ.

Lemma 1 (eAJs≥0e^{A_J s} \ge 0). Every entry of eAJse^{A_J s} is ≥0\ge 0 for s≥0s \ge 0.

Proof. Let q=max⁡x∈Ja0(x)q = \max_{x \in J} a_0(x). Then B=AJ+qIB = A_J + q I has entries ≥0\ge 0: off the diagonal they are those of AA, and on the diagonal q−a0(x)≥0q - a_0(x) \ge 0. Since qIqI commutes with AJA_J, eAJs=e−qseBs=e−qs∑k≥0(sB)k/k!e^{A_J s} = e^{-qs} e^{Bs} = e^{-qs} \sum_{k \ge 0} (s B)^k / k!, a sum of matrices with entries ≥0\ge 0. □\square

Theorem 1 (Munsky and Khammash 2006). For every x∈Jx \in J, 0≤pJ(x,t)≤P(x,t)0 \le p_J(x, t) \le P(x, t), and

∑x∈J∣P(x,t)−pJ(x,t)∣+∑x∉JP(x,t)=1−∑x∈JpJ(x,t).\sum_{x \in J} |P(x, t) - p_J(x, t)| + \sum_{x \notin J} P(x, t) = 1 - \sum_{x \in J} p_J(x, t).

So if ∑x∈JpJ(x,t)≥1−ε\sum_{x \in J} p_J(x, t) \ge 1 - \varepsilon, the L1 error of pJp_J (set to 0 outside JJ) is at most ε\varepsilon.

Proof. Split the states into JJ and its complement J′J'. The rows of the master equation for the states in JJ read

P˙J=AJPJ+AJJ′PJ′,\dot P_J = A_J P_J + A_{J J'} P_{J'},

where AJJ′A_{JJ'} holds the rates from states outside JJ into JJ. Its entries are ≥0\ge 0, and so are those of PJ′P_{J'}. Let f(s)=AJJ′PJ′(s)≥0f(s) = A_{JJ'} P_{J'}(s) \ge 0. By variation of constants,

PJ(t)=eAJtPJ(0)+∫0teAJ(t−s)f(s) ds.P_J(t) = e^{A_J t} P_J(0) + \int_0^t e^{A_J (t - s)} f(s)\, ds.

By Lemma 1 the integrand has entries ≥0\ge 0, so PJ(t)≥eAJtPJ(0)=pJ(t)P_J(t) \ge e^{A_J t} P_J(0) = p_J(t) in every entry, and pJ(t)≥0p_J(t) \ge 0 by Lemma 1 again. Then each term ∣P(x,t)−pJ(x,t)∣|P(x, t) - p_J(x, t)| for x∈Jx \in J equals P(x,t)−pJ(x,t)P(x, t) - p_J(x, t), and the left side of the identity is ∑xP(x,t)−∑x∈JpJ(x,t)=1−∑x∈JpJ(x,t)\sum_x P(x, t) - \sum_{x \in J} p_J(x, t) = 1 - \sum_{x \in J} p_J(x, t). □\square

There is also a probabilistic reading: pJ(x,t)p_J(x, t) is the probability that X(t)=xX(t) = x and that XX stayed in JJ during all of [0,t][0, t]. Mass that leaves JJ is lost, even if the process could come back.

Lemma 2 (larger sets give larger values). If J⊆KJ \subseteq K, then pJ(x,t)≤pK(x,t)p_J(x, t) \le p_K(x, t) for x∈Jx \in J.

Proof. Apply the proof of Theorem 1 with KK in place of the full space: the rows of p˙K=AKpK\dot p_K = A_K p_K for the states in JJ are p˙K,J=AJpK,J+AJ,K∖J pK,K∖J\dot p_{K, J} = A_J p_{K, J} + A_{J, K \setminus J}\, p_{K, K \setminus J}, with a forcing term ≥0\ge 0, so pK,J(t)≥eAJtpK,J(0)=pJ(t)p_{K, J}(t) \ge e^{A_J t} p_{K, J}(0) = p_J(t). □\square

So the lost mass 1−∑x∈JpJ(x,t)1 - \sum_{x \in J} p_J(x, t) can only go down when JJ grows.

Theorem 2 (the loop stops). Start the loop with J0∋x0J_0 \ni x_0 and the start law δx0\delta_{x_0}, and let line L6 add every state that one reaction with a positive propensity reaches from JJ. For every ε>0\varepsilon > 0, the loop stops after finitely many rounds.

Proof. After NN rounds, JNJ_N contains every state that XX can reach from x0x_0 with at most NN reactions. On the event that XX makes at most NN jumps in [0,t][0, t], the path stays in JNJ_N. By the probabilistic reading above, ∑x∈JNpJN(x,t)≥Pr⁡(at most N jumps in [0,t])\sum_{x \in J_N} p_{J_N}(x, t) \ge \Pr(\text{at most } N \text{ jumps in } [0, t]). Since XX does not explode, this probability tends to 1 as N→∞N \to \infty, so the lost mass drops below ε\varepsilon for some finite NN. □\square

Lemma 3 (uniformization in the code). Let q≥max⁡x∈Ja0(x)q \ge \max_{x \in J} a_0(x), q>0q > 0, and Q=I+AJ/qQ = I + A_J / q. Then eAJt=∑k≥0e−qt(qt)kk!Qke^{A_J t} = \sum_{k \ge 0} e^{-qt} \frac{(qt)^k}{k!} Q^k, every term has entries ≥0\ge 0, and cutting the series after any number of terms gives a vector ≤pJ(t)\le p_J(t) in every entry.

Proof. Q=B/qQ = B / q with BB as in Lemma 1, and eAJt=e−qteqtQe^{A_J t} = e^{-qt} e^{qt Q}. The terms are ≥0\ge 0 because Q≥0Q \ge 0 and PJ(0)≥0P_J(0) \ge 0, so a partial sum is below the full sum. The code splits tt into pieces of length δ\delta with qδ≤10q \delta \le 10 and uses eAJt=(eAJδ)t/δe^{A_J t} = (e^{A_J \delta})^{t / \delta}. Each cut series gives a vector below the exact one, and applying the nonnegative matrix eAJδe^{A_J \delta} to a smaller vector gives a smaller vector, so the computed result is still below pJ(t)p_J(t). □\square

So the mass that the code reports as lost, 1−∑p1 - \sum p, 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. AJA_J has at most m+1m + 1 nonzeros per column. Uniformization needs about qt+O(qt)qt + O(\sqrt{qt}) products with QQ, so a round costs O(s m (qt+1))O(s\, m\, (qt + 1)). With a Krylov method the number of products is often much smaller than qtqt for stiff problems.
  • Rounds. Growth by one reaction step per round needs as many rounds as the number of reactions that typical paths make, RR in the bound. Growing JJ by several steps at a time, or starting with a good guess (for example from a few runs of the Gillespie algorithm), cuts RR to a few.
  • States. The main cost is ss, the size of the final projection. For nn species whose counts each range over about ww values, ss is about wnw^n, 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 O(sm)O(sm) nonzeros and a few vectors of length ss.

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 JJ holds every reachable state, nothing is lost, and pp is the exact solution up to the error of the matrix exponential.

Variants and improvements

  • Krylov methods. Compute eAJtve^{A_J t} v 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 [0,t][0, t] into intervals and allow a different JJ 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 10610^6, 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 pp 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 JJ at any time, not only those outside JJ at time tt, so it is larger than the tail probability. A projection can lose much mass even when the final distribution lies inside JJ.
  • Bad growth. Adding states in all directions in many species makes JJ 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 [0,t][0, t]. As t→∞t \to \infty in an open system, nearly all mass leaves any fixed JJ, so stationary laws need the variant with the outflow sent back.
  • Floating point. For large qtqt, plain uniformization underflows (e−qte^{-qt} 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.

finite_state_projection.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • 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