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. is the number of individuals in generation , for . Usually . The state 0 is absorbing: a generation with no individuals has no children.
The parameters. The offspring distribution , for , with . Its probability generating function is
its mean is and its variance is . The mean 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 be independent draws from , independent of everything before generation . Then
So is a Markov chain on the non-negative integers, and the law of given is the -fold convolution of .
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 . 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 by the iteration of the extinction theorem. The second one simulates a path.
EXTINCTION-PROBABILITY(f, ε)- 1
q ← 0 - 2
repeat - 3
q_old ← q - 4
q ← f(q_old) ▷ q is now P(Z_n = 0) for the next n - 5
until q - q_old < ε - 6
return q SIMULATE-GW(p, Z0, T)- 7
Z ← Z0, path ← [Z0] - 8
for t ← 1 to T do - 9
Z ← sum of Z independent draws from p - 10
append Z to path - 11
if Z = 0 then return path - 12
return path
After rounds of line L4, , where is composed with itself times (see below). SIMULATE-GW draws one offspring count per individual, so a path costs draws. For Poisson offspring, the sum of independent Poisson() counts is Poisson(), so one draw per generation is enough, and the implementation uses this.
A worked example. Take , and . Then , and . The equation is , with the roots and , so . The iterates of line L4 are
| 1 | 2 | 3 | 4 | 5 | 10 | 20 | |
|---|---|---|---|---|---|---|---|
| 0.25 | 0.34375 | 0.39502 | 0.42678 | 0.44776 | 0.48882 | 0.49939 |
They increase to . The law of comes from . Its mean is and its variance is , as the formulas below give. With seed 2, the implementation draws the path 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 , a difference of 1.3 standard errors.
What it counts
- The law of . Given , the generating function of is . So , and by induction , with and . With , the generating function is , because the lines are independent.
- The probability of extinction by generation . . This is also for the extinction time .
- The probability of ultimate extinction. , the smallest root of in . From it is .
- The mean and the variance. , and for , and for .
- The total progeny. , 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 and gives birth at rate while it lives. The number of children of one individual is geometric, , with mean . 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 during an exponential infectious period of rate . This is the birth-death process above with and , so the early phase is a Galton-Watson process with geometric offspring of mean . Andersson and Britton (chapter 3) make the approximation exact with a coupling as the population size grows.
- Reed-Frost model. In a population of with a contact probability , one case infects a Binomial(, ) number of others at the start. For large this is close to Poisson(), so the early phase is a Galton-Watson process with Poisson offspring.
- Epidemic renewal equation. The Poisson renewal model with a constant reproduction number gives each case Poisson() 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 , and the extinction probabilities solve a system of equations of the form .
- 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. and , because is a sum of independent draws. So , which gives . The law of total variance gives with , where . The solution is , which is for and for . Check: , and .
The extinction theorem. Assume . Then is the smallest root of in , and if and only if . If , every individual has exactly one child, and the line never dies. The proof is on the page of the extinction theorem. For Poisson() offspring, , and for , for and for . For geometric offspring with mean , , and for .
The three regimes. For (subcritical), , so the line dies out fast, and the expected total progeny is . For (critical), the line dies out with probability 1, but slowly: if , then (Kolmogorov's estimate; see Athreya and Ney, chapter I). For Poisson(1) offspring, , against . The expected total progeny is infinite in the critical case, even though the line dies. For (supercritical), the line survives with probability .
Growth on survival. For , is a non-negative martingale, since . So converges almost surely to a limit . The Kesten-Stigum theorem says that , and , if and only if ; otherwise almost surely (Athreya and Ney, chapter I). So in the usual case a surviving line grows like with : the growth is exponential with the rate per generation, and the random factor is fixed by the first few generations.
No middle ground. If , every state is transient, so with probability 1 either or . A population in this model never settles at a stable size.
Total progeny. In the subcritical or critical case, the total progeny is finite with probability 1, and the hitting time theorem gives for . For Poisson() offspring the sum is Poisson(), so , the Borel distribution. For : , , , with mean .
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 , and is the probability of a major outbreak. For Poisson offspring, solves , the same equation as the final size relation: for , , equal to the final size . For geometric offspring (an exponential infectious period), the probability of a minor outbreak is instead. So two diseases with the same 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.
# 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
- Watson and Galton 1875, the question of the extinction of surnames, and the iteration of the generating function of the number of sons
- Harris 1963, Chapter I, the Galton-Watson process (generating functions, moments, the extinction probability and the limit of Z_n / m^n)
- Athreya and Ney 1972, Chapter I, the Galton-Watson process (the critical case, the Kesten-Stigum theorem and the limit laws)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 1ZKR7A Edit this page History Report an error Markdown