Algorithm Search⌘K

Modelcore

Reed-Frost model

Also called Reed-Frost chain binomial.

A discrete-generation stochastic epidemic in which each susceptible escapes each infective independently, so new cases are binomial.

The Reed-Frost model is a stochastic epidemic in discrete generations. A case is infectious for one generation and then recovers. During that generation, each susceptible person has an independent chance pp of an adequate contact with each case. A susceptible who meets at least one case becomes a case of the next generation. So the number of new cases, given the state, is binomial, and the sequence of case counts I0,I1,I2,…I_0, I_1, I_2, \ldots is called a chain binomial. The model is the simplest exact stochastic version of the SIR epidemic. It is small enough for exact calculation in a household, and in a large population it shows the two behaviours of the epidemic threshold: a minor outbreak or a major one.

The machine

The state. After generation tt, the state is (St,It)(S_t, I_t): StS_t susceptibles and ItI_t new cases. The cases of earlier generations are removed and play no further part. The population has a fixed size N=S0+I0N = S_0 + I_0 plus any people who are immune at the start, who do not take part.

The parameters. The contact probability p∈[0,1]p \in [0, 1]: the chance that one given case infects one given susceptible during the generation. Let q=1−pq = 1 - p. Time is counted in generations, and a generation is about the length of the generation interval of the disease.

The update rule. A susceptible escapes all ItI_t cases with probability qItq^{I_t}, independently of the other susceptibles. So

It+1∣(St,It)∼Binomial⁡(St, 1−qIt),St+1=St−It+1.I_{t+1} \mid (S_t, I_t) \sim \operatorname{Binomial}\big(S_t,\ 1 - q^{I_t}\big), \qquad S_{t+1} = S_t - I_{t+1}.

The epidemic stops at the first tt with It=0I_t = 0, and the final size is S0−StS_0 - S_t, the number of people infected after generation 0.

The Greenwood variant. In Greenwood's version the chance of infection does not depend on the number of cases, as long as there is at least one: It+1∼Binomial⁡(St,p)I_{t+1} \sim \operatorname{Binomial}(S_t, p) if It>0I_t > 0. This fits a household where the exposure comes from the shared space more than from each case.

The assumptions. All people mix equally. Contacts between different pairs are independent. The infectious period is fixed and the same for every case, so the generations do not overlap. A case can infect only during its own generation.

A simulation. One binomial draw per generation.

  1. REED-FROST(S0, I0, p)
  2. 1S ← S0, I ← I0
  3. 2path ← [(S, I)]
  4. 3while I > 0 do
  5. 4π ← 1 - (1 - p)^I ▷ Greenwood: π ← p
  6. 5C ← Binomial(S, π)
  7. 6S ← S - C, I ← C
  8. 7append (S, I) to path
  9. 8return path

Each round of the loop either ends the epidemic (C=0C = 0) or lowers SS by at least one, so there are at most S0+1S_0 + 1 rounds. A run costs O(S0)O(S_0) binomial draws in the worst case.

A worked example: a household of three. One case brings the disease into a household with two susceptibles, and p=0.2p = 0.2, q=0.8q = 0.8. The possible chains and their probabilities are:

chain (I0,I1,…)(I_0, I_1, \ldots) probability final size
1, 0 q2=0.64q^2 = 0.64 0
1, 1, 0 2pq⋅q=0.2562pq \cdot q = 0.256 1
1, 1, 1, 0 2pq⋅p=0.0642pq \cdot p = 0.064 2
1, 2, 0 p2=0.04p^2 = 0.04 2

So the final size is 0, 1 or 2 with probabilities 0.64, 0.256 and 0.104. For a household of five (one case, four susceptibles, p=0.2p = 0.2), the two variants first differ when two cases meet the same susceptible: the mean final size is 1.2701 under Reed-Frost and 1.2030 under Greenwood, and the probability that all four are infected is 0.0819 against 0.0502.

A worked example: a small community. With S0=10S_0 = 10, I0=1I_0 = 1 and p=0.15p = 0.15, the exact law of the final size has two peaks: P(0)=0.19687P(0) = 0.19687, a minimum of 0.049490.04949 at 3, and a second peak of 0.12370.1237 at 9. The mean is 4.911. With seed 2, the implementation draws the chain 1,2,1,2,2,01, 2, 1, 2, 2, 0 (8 people infected after generation 0), and with seed 5 it draws 1,5,5,01, 5, 5, 0 (all 10 infected). In 4000 runs with seed 20261118, 823 runs give final size 0, against 4000×0.19687=787.54000 \times 0.19687 = 787.5 expected.

What it counts

  • The probability of a chain. For a complete chain i0,i1,…,iT=0i_0, i_1, \ldots, i_T = 0 with st+1=st−it+1s_{t+1} = s_t - i_{t+1},
    P=∏t=0T−1(stit+1)(1−qit)it+1(qit)st+1.P = \prod_{t=0}^{T-1} \binom{s_t}{i_{t+1}} \big(1 - q^{i_t}\big)^{i_{t+1}} \big(q^{i_t}\big)^{s_{t+1}}.
    This is the likelihood used to fit the model to household data.
  • The final size. The law of S0−S∞S_0 - S_\infty follows from a pass over the states (S,I)(S, I): each generation spreads the mass of a state over its binomial successors. The implementation computes it exactly with rational arithmetic.
  • The probability of a minor outbreak, and the size of a major one, in a large population (see below).
  • The duration in generations, TT, and the epidemic curve I0,I1,…I_0, I_1, \ldots.

Relation to other models

  • Stochastic SIR model. The Reed-Frost model is the continuous-time SIR model with a fixed infectious period of length 1 in place of an exponential one, seen at the ends of the generations. If each case infects each susceptible at rate β/N\beta / N during its infectious period, then p=1−e−β/Np = 1 - e^{-\beta / N}. The final size law depends only on the law of the infectious period, not on the timing, so this gives the final size of the SIR model with a fixed infectious period (Andersson and Britton, chapter 2).
  • Random graphs and percolation. Draw an edge between each pair of the NN people with probability pp, independently. Then the cases of generation tt are the people at graph distance tt from the initial cases, and the final size is the size of their connected component, less I0I_0. This holds because each pair is tested at most once, at the first generation in which one of the two is a case. So the final size of the Reed-Frost model is the component size in the Erdos-Renyi graph G(N,p)G(N, p), the case of bond percolation with independent edges (Newman). The tests of the implementation sum over all graphs on up to six people and get the same chain law.
  • Galton-Watson process. With p=R0/Np = R_0 / N, a case in an almost fully susceptible population infects a Binomial(N−1N - 1, pp) number of people, which is close to Poisson(R0R_0). So the start of the epidemic is a branching process with Poisson offspring.
  • SIR epidemic model. For large NN and p=R0/Np = R_0 / N, the fraction infected in a major outbreak follows the deterministic final size relation.
  • Epidemic model. The Reed-Frost model is the discrete-time stochastic member of the family of compartmental models, with the compartments S, I and R.

Known results in the model

The threshold in a large population. Let N→∞N \to \infty with p=R0/Np = R_0 / N and one initial case. By the extinction theorem for Poisson offspring, the probability of a minor outbreak tends to q∞q_\infty, the smallest root of s=eR0(s−1)s = e^{R_0(s - 1)}. It is 1 if R0≤1R_0 \le 1 and 0.2031880.203188 for R0=2R_0 = 2. A major outbreak infects a fraction close to the root z>0z > 0 of z=1−e−R0zz = 1 - e^{-R_0 z}, which is 0.7968120.796812 for R0=2R_0 = 2. This is the giant component of G(N,R0/N)G(N, R_0/N). In 2000 runs with N=1000N = 1000, R0=2R_0 = 2 and seed 11, a fraction 0.197 of the runs stays minor, and the major outbreaks infect 0.795 of the population on average.

Limit theorems. Given a major outbreak, the final size is approximately normal around NzN z, with a standard deviation of order N\sqrt N. The threshold limit theorem and the central limit theorem for the final size of the standard SIR model, which covers the Reed-Frost model, are in Andersson and Britton, chapter 4.

Small populations. In a household, there is no clear split into minor and major outbreaks, so the exact chain probabilities are used directly. A household of size nn has at most 2n−12^{n-1} possible chains from one case, and the pass over the states (S,I)(S, I) takes O(n3)O(n^3) arithmetic operations. Households in a large population lead to the two-level mixing models, where the households play the role of individuals in a branching process.

Estimation. Given observed chains from many households, the likelihood is a product of the chain probabilities above, a polynomial in qq. The maximum likelihood estimate of qq follows by a one-dimensional search. Abbey (1952) examined the theory against outbreak data.

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)
reed_frost_model.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reed-frost-model/. The authors are listed in prov/PA1DQR.jsonl.
"""The Reed-Frost chain binomial epidemic and the Greenwood variant.

The state after generation t is (S_t, I_t): the number of susceptibles and
the number of new cases of generation t. A case is infectious for exactly
one generation and is then removed. Each susceptible escapes each case of
the generation independently with probability q = 1 - p, so it is infected
with probability 1 - q^I_t (Reed-Frost) or p whenever I_t > 0 (Greenwood).

The exact functions take p as a float or a fractions.Fraction. With Fraction
input they are exact.
"""

from __future__ import annotations

from itertools import combinations
from math import comb
from typing import Dict, List, Tuple

from biostoch import binomial


def infection_probability(p, i: int, greenwood: bool = False):
    """The chance that one susceptible is infected by a generation of i cases."""
    if i == 0:
        return 0 * p
    if greenwood:
        return p
    return 1 - (1 - p) ** i


def simulate(rng, s0: int, i0: int, p: float,
             greenwood: bool = False) -> List[Tuple[int, int]]:
    """One epidemic as the list of states (S_t, I_t), t = 0, 1, ...

    The list ends at the first generation with no new cases. Draw order: one
    biostoch.binomial draw per generation.
    """
    s, i = s0, i0  # @line L1
    path = [(s, i)]  # @line L2
    while i > 0:  # @line L3
        pi = infection_probability(float(p), i, greenwood)  # @line L4
        c = binomial(rng, s, pi)  # @line L5
        s, i = s - c, c  # @line L6
        path.append((s, i))  # @line L7
    return path  # @line L8


def final_size(path: List[Tuple[int, int]]) -> int:
    """The number of people infected after generation 0: S_0 - S_end."""
    return path[0][0] - path[-1][0]


def chain_probability(chain: List[int], s0: int, p, greenwood: bool = False):
    """P(I_0, I_1, ..., I_T = chain), the last entry being 0, given S_0 = s0.

    This is the product of the binomial terms C(S_t, I_(t+1)) pi^I_(t+1)
    (1 - pi)^S_(t+1), with pi = infection_probability(p, I_t).
    """
    if chain[-1] != 0:
        raise ValueError("a complete chain ends with 0")
    prob = 1 + 0 * p
    s = s0
    for t in range(len(chain) - 1):
        i, c = chain[t], chain[t + 1]
        if c > s:
            return 0 * p
        pi = infection_probability(p, i, greenwood)
        prob *= comb(s, c) * pi ** c * (1 - pi) ** (s - c)
        s -= c
    return prob


def final_size_distribution(s0: int, i0: int, p, greenwood: bool = False) -> Dict[int, object]:
    """The exact law of the final size, by a pass over the states (S, I).

    Each generation either ends the epidemic (no new cases) or lowers S, so
    the loop runs at most s0 + 1 times.
    """
    one = 1 + 0 * p
    live = {(s0, i0): one}
    out: Dict[int, object] = {}
    while live:
        nxt: Dict[Tuple[int, int], object] = {}
        for (s, i), w in live.items():
            if i == 0:
                out[s0 - s] = out.get(s0 - s, 0 * p) + w
                continue
            pi = infection_probability(p, i, greenwood)
            for c in range(s + 1):
                term = w * comb(s, c) * pi ** c * (1 - pi) ** (s - c)
                key = (s - c, c)
                nxt[key] = nxt.get(key, 0 * p) + term
        live = nxt
    return dict(sorted(out.items()))


def chains_by_graphs(s0: int, i0: int, p) -> Dict[Tuple[int, ...], object]:
    """The law of the chain (I_0, I_1, ...) by summing over all random graphs.

    Each of the C(n, 2) pairs of the n = s0 + i0 people is an edge with
    probability p. The cases of generation t are the people at graph
    distance t from the i0 initial cases, so the chain is the list of the
    sizes of the breadth-first layers. Use only for n <= 6.
    """
    n = s0 + i0
    pairs = list(combinations(range(n), 2))
    out: Dict[Tuple[int, ...], object] = {}
    for mask in range(1 << len(pairs)):
        adj = [[] for _ in range(n)]
        k = 0
        for b, (u, v) in enumerate(pairs):
            if mask >> b & 1:
                adj[u].append(v)
                adj[v].append(u)
                k += 1
        w = p ** k * (1 - p) ** (len(pairs) - k)
        seen = set(range(i0))
        layer = list(range(i0))
        chain = [i0]
        while layer:
            new = []
            for u in layer:
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        new.append(v)
            chain.append(len(new))
            layer = new
        key = tuple(chain)
        out[key] = out.get(key, 0 * p) + w
    return out
test_reed_frost_model.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reed-frost-model/. The authors are listed in prov/PA1DQR.jsonl.

import random
from fractions import Fraction as F

from biostoch import chi2_sf
from reed_frost_model import (
    chain_probability,
    chains_by_graphs,
    final_size,
    final_size_distribution,
    infection_probability,
    simulate,
)


def test_household_of_three():
    # One case and two susceptibles, p = 1/5.
    p = F(1, 5)
    assert chain_probability([1, 0], 2, p) == F(16, 25)
    assert chain_probability([1, 1, 0], 2, p) == F(32, 125)
    assert chain_probability([1, 1, 1, 0], 2, p) == F(8, 125)
    assert chain_probability([1, 2, 0], 2, p) == F(1, 25)
    assert final_size_distribution(2, 1, p) == {0: F(16, 25), 1: F(32, 125), 2: F(13, 125)}


def test_chain_law_equals_random_graph_layers():
    for s0, i0, p in ((4, 1, F(1, 3)), (3, 2, F(2, 5)), (5, 1, F(1, 4))):
        by_graph = chains_by_graphs(s0, i0, p)
        assert sum(by_graph.values()) == 1
        for chain, w in by_graph.items():
            assert chain_probability(list(chain), s0, p) == w
        sizes = {}
        for chain, w in by_graph.items():
            k = sum(chain) - i0
            sizes[k] = sizes.get(k, 0) + w
        assert final_size_distribution(s0, i0, p) == dict(sorted(sizes.items()))


def test_greenwood_differs_only_when_two_cases_meet_one_susceptible():
    p = F(1, 5)
    assert infection_probability(p, 2) == F(9, 25)
    assert infection_probability(p, 2, greenwood=True) == p
    rf = final_size_distribution(4, 1, p)
    gw = final_size_distribution(4, 1, p, greenwood=True)
    assert rf[0] == gw[0] == F(256, 625)
    assert rf[1] == gw[1]
    assert rf[4] > gw[4]
    assert sum(rf.values()) == sum(gw.values()) == 1


def test_simulation_matches_exact_final_size_law():
    rng = random.Random(20261118)
    s0, p, n = 10, 0.15, 4000
    exact = final_size_distribution(s0, 1, p)
    counts = [0] * (s0 + 1)
    for _ in range(n):
        counts[final_size(simulate(rng, s0, 1, p))] += 1
    stat = sum((counts[k] - n * exact[k]) ** 2 / (n * exact[k]) for k in range(s0 + 1))
    assert chi2_sf(stat, s0) > 0.001


def test_path_invariants():
    rng = random.Random(5)
    path = simulate(rng, 30, 2, 0.08)
    assert path[0] == (30, 2) and path[-1][1] == 0
    for (s, i), (s2, i2) in zip(path, path[1:]):
        assert s2 == s - i2 and 0 <= i2 <= s


def test_large_population_follows_branching_and_final_size():
    # N = 1000 and p = R0 / N with R0 = 2: about 0.203 of the runs stay
    # minor, and a major outbreak infects about 0.797 of the population.
    rng = random.Random(11)
    N, runs = 1000, 2000
    sizes = [final_size(simulate(rng, N - 1, 1, 2.0 / N)) for _ in range(runs)]
    major = [x for x in sizes if x > 100]
    minor = 1 - len(major) / runs
    assert abs(minor - 0.203) < 0.04
    assert abs(sum(major) / len(major) / N - 0.797) < 0.02

References

  1. Abbey 1952, the account of the Reed-Frost theory and its comparison with data
  2. Hakan Andersson and Tom Britton, Stochastic Epidemic Models and Their Statistical Analysis, Lecture Notes in Statistics 151, Springer, 2000, Chapter 2 (the Reed-Frost model as the standard SIR model with a fixed infectious period) and Chapter 7 (epidemics and random graphs)
  3. M. E. J. Newman, Spread of epidemic disease on networks, Physical Review E 66(1), 2002, the mapping of an SIR epidemic to bond percolation, with the fixed infectious period as the case of independent edges

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/PA1DQR/text.yaml