Algorithm Search⌘K

Modelcore

Galton-Watson branching process

Also called Bienayme-Galton-Watson process.

A population in generations where each individual has an independent random number of children with a fixed offspring distribution.

The Galton-Watson process is the simplest model of a population that grows by reproduction. Time runs in generations. Each individual of a generation has a random number of children, drawn independently from one fixed offspring distribution, and the children form the next generation. The model answers the question of Galton and Watson (1875): what is the chance that a family line dies out? In epidemiology, an individual is an infected person and the children are the people that this person infects, so the model describes the start of an outbreak, before the supply of susceptible people runs short. The main result about it is the extinction theorem.

The machine

The state. Zt∈{0,1,2,…}Z_t \in \{0, 1, 2, \ldots\} is the number of individuals in generation tt, for t=0,1,2,…t = 0, 1, 2, \ldots. Usually Z0=1Z_0 = 1. The state 0 is absorbing: a generation with no individuals has no children.

The parameters. The offspring distribution pk=P(one individual has k children)p_k = P(\text{one individual has } k \text{ children}), for k=0,1,2,…k = 0, 1, 2, \ldots, with ∑kpk=1\sum_k p_k = 1. Its probability generating function is

f(s)=∑k≥0pksk,0≤s≤1,f(s) = \sum_{k \ge 0} p_k s^k, \qquad 0 \le s \le 1,

its mean is m=f′(1)=∑kkpkm = f'(1) = \sum_k k p_k and its variance is σ2\sigma^2. The mean mm is the number of children per individual. In an epidemic it is the reproduction number of the early phase. Time is in generations, not in days.

The update rule. Let ξt,1,ξt,2,…\xi_{t,1}, \xi_{t,2}, \ldots be independent draws from (pk)(p_k), independent of everything before generation tt. Then

Zt+1=∑i=1Ztξt,i.Z_{t+1} = \sum_{i=1}^{Z_t} \xi_{t,i}.

So (Zt)(Z_t) is a Markov chain on the non-negative integers, and the law of Zt+1Z_{t+1} given Zt=zZ_t = z is the zz-fold convolution of (pk)(p_k).

The assumptions. Individuals reproduce independently of each other. All individuals have the same offspring distribution, in every generation. There is no limit from resources or from the depletion of susceptibles: the offspring law does not depend on ZtZ_t. Generations do not overlap. Each of these fails in a real population sooner or later, so the model describes a population that is small compared with its environment.

A simulation and the extinction probability. The first procedure finds the extinction probability qq by the iteration of the extinction theorem. The second one simulates a path.

  1. EXTINCTION-PROBABILITY(f, ε)
  2. 1q ← 0
  3. 2repeat
  4. 3q_old ← q
  5. 4q ← f(q_old) ▷ q is now P(Z_n = 0) for the next n
  6. 5until q - q_old < ε
  7. 6return q
  8. SIMULATE-GW(p, Z0, T)
  9. 7Z ← Z0, path ← [Z0]
  10. 8for t ← 1 to T do
  11. 9Z ← sum of Z independent draws from p
  12. 10append Z to path
  13. 11if Z = 0 then return path
  14. 12return path

After nn rounds of line L4, q=fn(0)=P(Zn=0)q = f_n(0) = P(Z_n = 0), where fnf_n is ff composed with itself nn times (see below). SIMULATE-GW draws one offspring count per individual, so a path costs O(Z0+Z1+⋯+ZT)O(Z_0 + Z_1 + \cdots + Z_T) draws. For Poisson offspring, the sum of zz independent Poisson(mm) counts is Poisson(mzm z), so one draw per generation is enough, and the implementation uses this.

A worked example. Take p0=1/4p_0 = 1/4, p1=1/4p_1 = 1/4 and p2=1/2p_2 = 1/2. Then f(s)=14+14s+12s2f(s) = \tfrac14 + \tfrac14 s + \tfrac12 s^2, m=5/4m = 5/4 and σ2=11/16\sigma^2 = 11/16. The equation f(s)=sf(s) = s is 2s2−3s+1=02s^2 - 3s + 1 = 0, with the roots 1/21/2 and 11, so q=1/2q = 1/2. The iterates of line L4 are

nn 1 2 3 4 5 10 20
P(Zn=0)=fn(0)P(Z_n = 0) = f_n(0) 0.25 0.34375 0.39502 0.42678 0.44776 0.48882 0.49939

They increase to 1/21/2. The law of Z2Z_2 comes from f2(s)=f(f(s))=1132+18s+932s2+18s3+18s4f_2(s) = f(f(s)) = \tfrac{11}{32} + \tfrac18 s + \tfrac{9}{32} s^2 + \tfrac18 s^3 + \tfrac18 s^4. Its mean is 25/16=m225/16 = m^2 and its variance is 495/256495/256, as the formulas below give. With seed 2, the implementation draws the path 1,2,2,2,4,7,10,11,131, 2, 2, 2, 4, 7, 10, 11, 13 over 8 generations. With seeds 1, 3 and 4 the line dies in the first generation, and with seed 7 it dies in the second. Over 3000 paths with seed 20261118, a fraction 0.438 is extinct by generation 4, against the exact f4(0)=0.427f_4(0) = 0.427, a difference of 1.3 standard errors.

What it counts

  • The law of ZnZ_n. Given Zn=zZ_n = z, the generating function of Zn+1Z_{n+1} is f(s)zf(s)^z. So E[sZn+1]=E[f(s)Zn]E[s^{Z_{n+1}}] = E[f(s)^{Z_n}], and by induction E[sZn]=fn(s)E[s^{Z_n}] = f_n(s), with f0(s)=sf_0(s) = s and fn+1=f∘fn=fn∘ff_{n+1} = f \circ f_n = f_n \circ f. With Z0=kZ_0 = k, the generating function is fn(s)kf_n(s)^k, because the kk lines are independent.
  • The probability of extinction by generation nn. P(Zn=0)=fn(0)P(Z_n = 0) = f_n(0). This is also P(T≤n)P(T \le n) for the extinction time T=min⁡{n:Zn=0}T = \min\{n : Z_n = 0\}.
  • The probability of ultimate extinction. q=P(Zn=0 for some n)=lim⁡nfn(0)q = P(Z_n = 0 \text{ for some } n) = \lim_n f_n(0), the smallest root of f(s)=sf(s) = s in [0,1][0, 1]. From Z0=kZ_0 = k it is qkq^k.
  • The mean and the variance. E[Zn]=mnE[Z_n] = m^n, and Var⁡(Zn)=σ2mn−1(mn−1)/(m−1)\operatorname{Var}(Z_n) = \sigma^2 m^{n-1} (m^n - 1)/(m - 1) for m≠1m \ne 1, and nσ2n \sigma^2 for m=1m = 1.
  • The total progeny. Y=∑n≥0ZnY = \sum_{n \ge 0} Z_n, the number of individuals that ever live. In an epidemic, it is the size of a minor outbreak.

Relation to other models

  • Birth-death process. In the linear birth-death process, each individual lives an exponential time with rate μ\mu and gives birth at rate λ\lambda while it lives. The number of children of one individual is geometric, pk=μλ+μ(λλ+μ)kp_k = \frac{\mu}{\lambda + \mu} \left(\frac{\lambda}{\lambda + \mu}\right)^k, with mean λ/μ\lambda / \mu. So the generations of a birth-death process form a Galton-Watson process with this offspring law, while the birth-death process itself runs in continuous time.
  • Stochastic SIR model. While almost everyone is susceptible, a case infects others at rate β\beta during an exponential infectious period of rate γ\gamma. This is the birth-death process above with λ=β\lambda = \beta and μ=γ\mu = \gamma, so the early phase is a Galton-Watson process with geometric offspring of mean R0=β/γR_0 = \beta / \gamma. Andersson and Britton (chapter 3) make the approximation exact with a coupling as the population size grows.
  • Reed-Frost model. In a population of NN with a contact probability p=R0/Np = R_0 / N, one case infects a Binomial(N−1N - 1, pp) number of others at the start. For large NN this is close to Poisson(R0R_0), so the early phase is a Galton-Watson process with Poisson offspring.
  • Epidemic renewal equation. The Poisson renewal model with a constant reproduction number RR gives each case Poisson(RR) children, spread over the days by the generation interval. Counted by generations, not by days, it is a Galton-Watson process.
  • Multitype processes and the next-generation matrix. With several types of individual, the mean numbers of children form a matrix. Its spectral radius plays the role of mm, and the extinction probabilities solve a system of equations of the form q=f(q)q = f(q).
  • Yule model and Kingman coalescent. The Yule model is a pure birth process in continuous time, a branching process with no deaths. The coalescent looks at a population of constant size backward in time; a branching process looks forward with no constraint on the size.

Known results in the model

Mean and variance. E[Zn+1∣Zn]=mZnE[Z_{n+1} \mid Z_n] = m Z_n and Var⁡(Zn+1∣Zn)=σ2Zn\operatorname{Var}(Z_{n+1} \mid Z_n) = \sigma^2 Z_n, because Zn+1Z_{n+1} is a sum of ZnZ_n independent draws. So E[Zn+1]=mE[Zn]E[Z_{n+1}] = m E[Z_n], which gives E[Zn]=mnE[Z_n] = m^n. The law of total variance gives Vn+1=σ2mn+m2VnV_{n+1} = \sigma^2 m^n + m^2 V_n with V0=0V_0 = 0, where Vn=Var⁡(Zn)V_n = \operatorname{Var}(Z_n). The solution is Vn=σ2mn−1(1+m+⋯+mn−1)V_n = \sigma^2 m^{n-1} (1 + m + \cdots + m^{n-1}), which is σ2mn−1(mn−1)/(m−1)\sigma^2 m^{n-1}(m^n - 1)/(m - 1) for m≠1m \ne 1 and nσ2n \sigma^2 for m=1m = 1. Check: V1=σ2V_1 = \sigma^2, and σ2mn+m2σ2mn−2(1+⋯+mn−2)=σ2mn(1+m+⋯+mn−1)\sigma^2 m^{n} + m^2 \sigma^2 m^{n-2}(1 + \cdots + m^{n-2}) = \sigma^2 m^n (1 + m + \cdots + m^{n-1}). □\square

The extinction theorem. Assume p1<1p_1 < 1. Then qq is the smallest root of f(s)=sf(s) = s in [0,1][0, 1], and q=1q = 1 if and only if m≤1m \le 1. If p1=1p_1 = 1, every individual has exactly one child, and the line never dies. The proof is on the page of the extinction theorem. For Poisson(mm) offspring, f(s)=em(s−1)f(s) = e^{m(s - 1)}, and q=0.417188q = 0.417188 for m=1.5m = 1.5, q=0.203188q = 0.203188 for m=2m = 2 and q=0.059520q = 0.059520 for m=3m = 3. For geometric offspring with mean RR, f(s)=1/(1+R−Rs)f(s) = 1/(1 + R - R s), and q=1/Rq = 1/R for R>1R > 1.

The three regimes. For m<1m < 1 (subcritical), P(Zn>0)≤E[Zn]=mnP(Z_n > 0) \le E[Z_n] = m^n, so the line dies out fast, and the expected total progeny is ∑nmn=1/(1−m)\sum_n m^n = 1/(1 - m). For m=1m = 1 (critical), the line dies out with probability 1, but slowly: if σ2<∞\sigma^2 < \infty, then P(Zn>0)∼2/(nσ2)P(Z_n > 0) \sim 2/(n \sigma^2) (Kolmogorov's estimate; see Athreya and Ney, chapter I). For Poisson(1) offspring, 1−f1000(0)=0.0019921 - f_{1000}(0) = 0.001992, against 2/10002/1000. The expected total progeny is infinite in the critical case, even though the line dies. For m>1m > 1 (supercritical), the line survives with probability 1−q>01 - q > 0.

Growth on survival. For 1<m<∞1 < m < \infty, Wn=Zn/mnW_n = Z_n / m^n is a non-negative martingale, since E[Zn+1∣Zn]=mZnE[Z_{n+1} \mid Z_n] = m Z_n. So WnW_n converges almost surely to a limit WW. The Kesten-Stigum theorem says that E[W]=1E[W] = 1, and P(W=0)=qP(W = 0) = q, if and only if E[Z1ln⁡Z1]<∞E[Z_1 \ln Z_1] < \infty; otherwise W=0W = 0 almost surely (Athreya and Ney, chapter I). So in the usual case a surviving line grows like WmnW m^n with W>0W > 0: the growth is exponential with the rate ln⁡m\ln m per generation, and the random factor WW is fixed by the first few generations.

No middle ground. If p1<1p_1 < 1, every state k≥1k \ge 1 is transient, so with probability 1 either Zn→0Z_n \to 0 or Zn→∞Z_n \to \infty. A population in this model never settles at a stable size.

Total progeny. In the subcritical or critical case, the total progeny YY is finite with probability 1, and the hitting time theorem gives P(Y=k)=1kP(ξ1+⋯+ξk=k−1)P(Y = k) = \frac1k P(\xi_1 + \cdots + \xi_k = k - 1) for Z0=1Z_0 = 1. For Poisson(mm) offspring the sum is Poisson(mkm k), so P(Y=k)=e−mk(mk)k−1/k!P(Y = k) = e^{-mk} (mk)^{k-1} / k!, the Borel distribution. For m=0.5m = 0.5: P(Y=1)=0.606531P(Y = 1) = 0.606531, P(Y=2)=0.183940P(Y = 2) = 0.183940, P(Y=3)=0.083674P(Y = 3) = 0.083674, with mean 1/(1−m)=21/(1 - m) = 2.

Use in epidemics. For an outbreak that starts with one case in a large, fully susceptible population, the probability of a minor outbreak is about qq, and 1−q1 - q is the probability of a major outbreak. For Poisson offspring, 1−q1 - q solves 1−q=1−e−R0(1−q)1 - q = 1 - e^{-R_0 (1 - q)}, the same equation as the final size relation: for R0=2R_0 = 2, 1−q=0.7968121 - q = 0.796812, equal to the final size zz. For geometric offspring (an exponential infectious period), the probability of a minor outbreak is 1/R01/R_0 instead. So two diseases with the same R0R_0 can have different chances to take off.

Code

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)
galton_watson_process.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/galton-watson-process/. The authors are listed in prov/1ZKR7A.jsonl.
"""The Galton-Watson branching process.

An offspring distribution is a list p with p[k] = P(one individual has k
children), for k = 0, 1, ..., len(p) - 1. Its probability generating
function is f(s) = sum of p[k] s^k. The process starts with Z_0 individuals,
and Z_(t+1) is the sum of Z_t independent draws from p.

The functions take plain floats or fractions.Fraction values. With Fraction
input, offspring_mean, offspring_variance, pgf and generation_pmf are exact.
"""

from __future__ import annotations

import math
from fractions import Fraction
from typing import Callable, List, Sequence

from biostoch import categorical, poisson


def pgf(p: Sequence, s):
    """f(s) = sum of p[k] s^k, by Horner's rule."""
    acc = 0 * s
    for pk in reversed(p):
        acc = acc * s + pk
    return acc


def offspring_mean(p: Sequence):
    """m = sum of k p[k]."""
    return sum(k * pk for k, pk in enumerate(p))


def offspring_variance(p: Sequence):
    """sigma^2 = sum of k^2 p[k] - m^2."""
    m = offspring_mean(p)
    return sum(k * k * pk for k, pk in enumerate(p)) - m * m


def generation_mean(m, n: int, z0: int = 1):
    """E[Z_n] = z0 m^n."""
    return z0 * m ** n


def generation_variance(m, var, n: int, z0: int = 1):
    """Var(Z_n) for Z_0 = z0: z0 var m^(n-1) (m^n - 1) / (m - 1), or z0 n var if m = 1."""
    if n == 0:
        return 0 * var
    if m == 1:
        return z0 * n * var
    return z0 * var * m ** (n - 1) * (m ** n - 1) / (m - 1)


def extinction_probability(f: Callable[[float], float], eps: float = 1e-13,
                           max_iter: int = 10 ** 6) -> float:
    """The smallest root of f(s) = s in [0, 1], by q_(n+1) = f(q_n) from q_0 = 0.

    q_n = P(Z_n = 0) increases to the root. The loop stops when one step
    moves q by less than eps, or after max_iter steps. Near m = 1 the steps
    are small long before q is close to the root; see the page.
    """
    q = 0.0  # @line L1
    for _ in range(max_iter):  # @line L2
        q_old = q  # @line L3
        q = f(q_old)  # @line L4
        if q - q_old < eps:  # @line L5
            break
    return q  # @line L6


def poisson_pgf(m: float) -> Callable[[float], float]:
    """f(s) = exp(m (s - 1)) for Poisson(m) offspring."""
    return lambda s: math.exp(m * (s - 1.0))


def _poly_mul(a: List, b: List) -> List:
    out = [0 * a[0]] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        if x == 0:
            continue
        for j, y in enumerate(b):
            out[i + j] += x * y
    return out


def generation_pmf(p: Sequence, n: int, z0: int = 1) -> List:
    """The exact law of Z_n as a list: entry k is P(Z_n = k).

    The generating function of Z_n is f composed with itself n times, raised
    to the power z0. Each composition substitutes the current polynomial g
    into f, so the degree is (len(p) - 1)^n z0; use it for small cases.
    """
    one = p[0] - p[0] + 1
    g = [0 * one, one]  # g(s) = s
    for _ in range(n):
        # f(g(s)) by Horner's rule on polynomials.
        acc = [0 * one]
        for pk in reversed(p):
            acc = _poly_mul(acc, g)
            acc[0] += pk
        g = acc
    out = [one]
    for _ in range(z0):
        out = _poly_mul(out, g)
    while len(out) > 1 and out[-1] == 0:
        out.pop()
    return out


def simulate(rng, p: Sequence[float], generations: int, z0: int = 1,
             cap: int = 10 ** 6) -> List[int]:
    """One path Z_0, Z_1, ... of the process with offspring law p.

    Draw order: in each generation, one categorical draw per individual, in
    order. The path stops early at extinction (Z = 0) or when Z exceeds cap.
    """
    z = z0  # @line L7
    path = [z]
    weights = [float(x) for x in p]
    for _ in range(generations):  # @line L8
        z = sum(categorical(rng, weights) for _ in range(z))  # @line L9
        path.append(z)  # @line L10
        if z == 0 or z > cap:  # @line L11
            return path
    return path  # @line L12


def simulate_poisson(rng, m: float, generations: int, z0: int = 1,
                     cap: int = 10 ** 6) -> List[int]:
    """One path with Poisson(m) offspring.

    The sum of z independent Poisson(m) counts is Poisson(m z), so each
    generation takes one biostoch.poisson draw with mean m z.
    """
    z = z0
    path = [z]
    for _ in range(generations):
        z = poisson(rng, m * z)
        path.append(z)
        if z == 0 or z > cap:
            return path
    return path


def smallest_root_quadratic(p: Sequence[Fraction]) -> Fraction:
    """The exact extinction probability when p has length 3 (at most two children).

    f(s) = s is p2 s^2 + (p1 - 1) s + p0 = 0, with the root s = 1. The other
    root is p0 / p2 (the product of the roots), and q is the smaller of the
    two in [0, 1]. If p2 = 0 the process cannot grow, and q = 1 unless p1 = 1.
    """
    p0, p1, p2 = p
    if p1 == 1:
        return Fraction(0)
    if p2 == 0:
        return Fraction(1)
    return min(Fraction(1), Fraction(p0) / Fraction(p2))
test_galton_watson_process.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/galton-watson-process/. The authors are listed in prov/1ZKR7A.jsonl.

import math
import random
from fractions import Fraction as F

from biostoch import check_mean, mean_var
from galton_watson_process import (
    extinction_probability,
    generation_mean,
    generation_pmf,
    generation_variance,
    offspring_mean,
    offspring_variance,
    pgf,
    poisson_pgf,
    simulate,
    simulate_poisson,
    smallest_root_quadratic,
)

EXAMPLE = [F(1, 4), F(1, 4), F(1, 2)]


def test_poisson_check_values():
    assert abs(extinction_probability(poisson_pgf(1.5)) - 0.417188) < 5e-7
    assert abs(extinction_probability(poisson_pgf(2.0)) - 0.203188) < 5e-7


def test_subcritical_and_critical_go_extinct():
    assert abs(extinction_probability(poisson_pgf(0.9)) - 1.0) < 1e-9
    # At m = 1 the iteration creeps up: P(Z_n > 0) is about 2 / (n sigma^2).
    q = extinction_probability(poisson_pgf(1.0), eps=0.0, max_iter=1000)
    assert abs((1.0 - q) - 2.0 / 1000) < 1e-4


def test_one_child_always_never_dies():
    p = [F(0), F(1)]
    assert offspring_mean(p) == 1
    assert extinction_probability(lambda s: pgf(p, s)) == 0.0
    assert smallest_root_quadratic([F(0), F(1), F(0)]) == 0


def test_example_moments_and_root():
    assert offspring_mean(EXAMPLE) == F(5, 4)
    assert offspring_variance(EXAMPLE) == F(11, 16)
    assert smallest_root_quadratic(EXAMPLE) == F(1, 2)
    assert pgf(EXAMPLE, F(1, 2)) == F(1, 2)
    q = extinction_probability(lambda s: pgf(EXAMPLE, s))
    assert abs(q - 0.5) < 1e-11


def test_generation_pmf_exact():
    assert generation_pmf(EXAMPLE, 1) == EXAMPLE
    assert generation_pmf(EXAMPLE, 2) == [F(11, 32), F(1, 8), F(9, 32), F(1, 8), F(1, 8)]
    m, v = offspring_mean(EXAMPLE), offspring_variance(EXAMPLE)
    for n in range(0, 5):
        pmf = generation_pmf(EXAMPLE, n)
        assert sum(pmf) == 1
        mean = sum(k * x for k, x in enumerate(pmf))
        var = sum(k * k * x for k, x in enumerate(pmf)) - mean * mean
        assert mean == generation_mean(m, n)
        assert var == generation_variance(m, v, n)
    # P(Z_n = 0) = f_n(0), the iterates of the extinction loop.
    q = F(0)
    for n in range(1, 5):
        q = pgf(EXAMPLE, q)
        assert generation_pmf(EXAMPLE, n)[0] == q
    # Two ancestors: the generating function is squared.
    two = generation_pmf(EXAMPLE, 2, z0=2)
    assert two[0] == F(11, 32) ** 2


def test_simulation_matches_exact_law():
    rng = random.Random(20261118)
    n, gens = 3000, 4
    pmf = generation_pmf(EXAMPLE, gens)
    p0 = float(pmf[0])
    finals, dead = [], 0
    for _ in range(n):
        path = simulate(rng, EXAMPLE, gens)
        z = path[-1] if len(path) == gens + 1 else 0
        finals.append(z)
        dead += z == 0
    assert check_mean(dead / n, p0, p0 * (1 - p0), n)
    m, v = offspring_mean(EXAMPLE), offspring_variance(EXAMPLE)
    mean, _ = mean_var(finals)
    assert check_mean(mean, float(generation_mean(m, gens)), float(generation_variance(m, v, gens)), n)


def test_poisson_simulation_extinction_frequency():
    rng = random.Random(7)
    n, gens, m = 4000, 30, 2.0
    exact = 0.0
    for _ in range(gens):
        exact = math.exp(m * (exact - 1.0))  # f_30(0) = P(Z_30 = 0)
    dead = 0
    for _ in range(n):
        path = simulate_poisson(rng, m, gens, cap=400)
        dead += path[-1] == 0
    # A path that passes the cap dies later with probability below q^400, which is negligible.
    assert check_mean(dead / n, exact, exact * (1 - exact), n)
    assert abs(exact - 0.203188) < 1e-6

References

  1. Watson and Galton 1875, the question of the extinction of surnames, and the iteration of the generating function of the number of sons
  2. Harris 1963, Chapter I, the Galton-Watson process (generating functions, moments, the extinction probability and the limit of Z_n / m^n)
  3. Athreya and Ney 1972, Chapter I, the Galton-Watson process (the critical case, the Kesten-Stigum theorem and the limit laws)
  4. Hakan Andersson and Tom Britton, Stochastic Epidemic Models and Their Statistical Analysis, Lecture Notes in Statistics 151, Springer, 2000, Chapter 3, Coupling methods (the approximation of the early phase of an epidemic by a branching process)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/1ZKR7A/text.yaml