Algorithmresearch
Data augmentation MCMC for epidemics
Also called O'Neill-Roberts data augmentation.
Infer infection rates from removal times by treating the unobserved infection times as latent variables updated by Metropolis-Hastings.
- Time
- Θ(M n² log n) worst · average · best
- Space
- Θ(M n) extra
- Where
- M = the number of iterations; N = the population size; n = the number of cases
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Philip D. O'Neill, Gareth O. Roberts, Gavin J. Gibson, Eric Renshaw, 1999
Data augmentation MCMC estimates the infection rate and the removal rate of the stochastic SIR model, the Markov form of the SIR epidemic and of the general epidemic model, from the times at which cases are removed, for example the dates of recovery, isolation or death. The infection times are not observed, and without them the likelihood has no closed form. The method adds them to the unknowns. Given all event times, the likelihood is simple, and and have gamma full conditionals, so a Gibbs step draws them exactly. Given the rates, a Metropolis-Hastings step moves one infection time at a time. The chain targets the joint posterior of the rates and the infection times, so it also gives the posterior of and of who was infected when.
In plain words
In an outbreak, health workers often record the day each sick person recovers or is isolated, but nobody sees the moment each person caught the disease. If we knew those moments, estimating how fast the disease spreads would be easy: count the infections and compare them with how much contact the sick had with the healthy.
So the method takes a guess at the hidden moments and improves it in a loop. With the current guess, it draws new values for the speed of spread and the speed of recovery. With these values, it picks one person and proposes a new moment of infection for that person. It keeps the proposal if it fits the model well, and it rejects every proposal that leaves somebody infected while nobody was sick. After many rounds, the values it visits show which speeds are plausible and how sure we can be.
The problem
Model. A closed population of people follows the Markov SIR model: each susceptible is infected at rate , and each infectious person is removed at rate . One person starts the epidemic. The epidemic is over.
Input. The removal times of the people who were ever infected, and . Priors and , independent, with a flat prior on the infection time of the first case. A number of iterations .
Output. A sample from a Markov chain whose invariant law is the joint posterior of , and the infection times given .
The complete-data likelihood. Let be the number infectious just before , let be the first case, and let
where runs over all people and for a person who is never infected. Then
if for all and for every , and if not.
The algorithm
DA-MCMC(r[1..n], N, a_β, b_β, a_γ, b_γ, M)- 1
i ← all infections in [min r - 1, min r), in the order of r; A ← A(i) - 2
for m ← 1 to M do - 3
β ← draw from Gamma(a_β + n - 1, rate b_β + A/N) - 4
γ ← draw from Gamma(a_γ + n, rate b_γ + Σ_j (r_j - i_j)) - 5
repeat n times: j ← uniform in {1, …, n} - 6
i′ ← i with i′_j ← r_j - E, where E ← draw from Exp(γ) - 7
if i′ is valid and log U < Σ log I′(i′_k-) - Σ log I(i_k-) - β (A(i′) - A(i)) / N then i ← i′, A ← A(i′) - 8
record (β, γ, i)
Line L1 gives a valid start: every case is infected before anybody is removed, so the first case is still infectious at every later infection. Line L6 is an independence proposal: it does not depend on the current , and it draws the infectious period of case from its law under the model. For this reason the factor cancels in the acceptance ratio of line L7, and only the infection term and the pressure remain. The change of comes from the pair terms that involve case , and the infection term comes from one sorted sweep over the event times, which also finds a proposal where somebody is infected while nobody is infectious. The implementation draws in the order: two gamma draws, then for each update the case, the exponential time and the uniform.
Example
An exact check. Take and two cases with removal times and , and the priors for both rates. If we integrate the rates out, the posterior of the infection times is proportional to . A grid of points gives the posterior means and , and the probability that case 2 was infected first. A run of 40000 iterations from seed 20261118 gives , and , where each is one standard error from 40 batch means. The test does the same with 30000 iterations.
A simulated outbreak. The implementation also simulates a labelled epidemic. With , , , so is above the epidemic threshold, and seed 3, one case at time 0 leads to cases, and the last removal is at time 5.689. The sampler gets only the 24 removal times. With the priors for both rates, seed 1, 1500 iterations and the first 300 discarded:
| quantity | true value | posterior mean | 95% credible interval |
|---|---|---|---|
| 2 | 2.163 | [1.188, 3.520] | |
| 1 | 1.060 | [0.601, 1.837] | |
| 2 | 2.139 | [1.128, 3.572] |
The intervals are wide, because 24 cases carry little information. With seed 7 the outbreak has 27 cases, and the posterior mean of is 2.73 with the interval [1.48, 4.75].
Correctness
The full proof is in proofs/correctness.md. The likelihood is the density of a path of a Markov chain: the product of the rates of the events that happen, for each infection after the first and for each removal, times of minus the integral of the total rate . Since and , this gives . As a function of and , times the priors is a product of two gamma kernels, so lines L3 and L4 are exact Gibbs draws. Lines L5 to L7 are a Metropolis-Hastings step for given the rates, with the proposal density . The proposal ratio cancels the factor , so the acceptance ratio is the expression in line L7, and an invalid proposal has and is rejected. Each step leaves the joint posterior invariant, and so does the sweep. The chain is irreducible on the valid vectors, because it can move any case earlier than all others, and from a state where all infections come before the first removal it can reach every such state.
Proof: The complete-data likelihood, the full conditionals and the invariance of the samplerfull
Setting. A closed population of people follows the Markov SIR model: when people are susceptible and are infectious, each susceptible is infected at rate , and each infectious person is removed at rate . The epidemic is complete. The people who were ever infected have the labels , known removal times and unknown infection times . The other people are never infected; we write for them. Let be the person with the earliest infection time, the initial case, and let be the number infectious just before . We call the vector valid if for all and for every . The priors are , , independent, and a flat prior on .
Claim 1 (the complete-data likelihood). For a valid , the density of the infection and removal times given , and is
with and . It is 0 for a vector that is not valid.
Proof. Between events the state is constant, and the labelled process is a Markov chain in which person is infected at rate while susceptible and removed at rate while infectious. The density of a path of a Markov chain with finitely many events is the product of the rates of the events that happen, times the exponential of minus the integral of the total rate of all possible events. The infections after the first one contribute each, the removals contribute each, and the total rate is . Its integral is , and , since person is infectious exactly on . If for some , the rate of that infection is 0, so the density is 0.
The function log_likelihood returns the logarithm of this expression. The test compares it with a sweep over the events that adds the log rate of each event and subtracts the integral of the total rate between events.
Claim 2 (the pair form of ). , where runs over all people. For the term equals , and each of the people who are never infected adds . So pressure_integral computes .
Proof. counts the pairs with infectious and susceptible at time . So is the sum over pairs of the length of the time when both hold, which is the length of . That length is , which equals , and it is when .
Claim 3 (the update of ). If only changes, changes by the change of pair_terms(j, ...).
Proof. By Claim 2, is a sum of terms indexed by pairs. The terms that depend on are those with as the infector (the pairs , including the terms ) and those with as the susceptible (the pairs ). pair_terms adds exactly these terms, and every other term is the same before and after the change.
Claim 4 (the infection term). log_infection_term returns for a vector with for all , or if some has .
Proof. The sweep visits the times in increasing order with a counter that starts at 0, adds 1 at each infection and subtracts 1 at each removal. Since every person is infectious exactly on , the counter just before an event at time equals , the number with processed so far. The first infection is that of and is skipped. At every later infection the code adds , or returns if the counter is 0. Event times are distinct with probability 1 under the proposal, which has a continuous density.
Claim 5 (the Gibbs steps, lines L3 and L4). Given , the posterior of is , the posterior of is , and the two are independent.
Proof. The joint posterior density is proportional to . As a function of and for a fixed valid , it is
a product of a gamma kernel in and a gamma kernel in . The code calls gammavariate with the shape and the scale .
Claim 6 (the Metropolis-Hastings step, lines L5 to L7). Given and , one update of leaves the conditional law invariant.
Proof. The update picks uniformly and proposes with , whatever the current . The proposal density is on . The Metropolis-Hastings ratio for moving from to is
In , the factor changes by , and is ; the two cancel. The factors and do not change. So the ratio is
which is log_ratio by Claims 3 and 4. If is not valid, and the ratio is 0, so the code rejects. The test , with uniform on , accepts with probability . This is the Metropolis-Hastings rule, so the kernel satisfies detailed balance with respect to , and a mixture over of such kernels does too.
Claim 7 (invariance of the whole sweep). One iteration of lines L3 to L7 leaves the joint posterior of invariant.
Proof. Lines L3 and L4 together draw from their joint conditional given (Claim 5), which leaves the joint posterior invariant, as every Gibbs step does. Each update of lines L5 to L7 changes only and leaves invariant (Claim 6), so it leaves the joint posterior invariant. A composition of kernels that leave a law invariant leaves it invariant.
Claim 8 (a valid start and irreducibility). Line L1 gives a valid vector, and the chain can move from any valid vector to any open set of valid vectors with positive probability.
Proof. Line L1 puts all infections in the interval before the first removal, in the order of the removal times. Each infection after the first finds the first case infectious, since nobody is removed before . So the vector is valid. For irreducibility, note that moving a case to a time earlier than every current infection time keeps the vector valid: becomes the first case and needs no infector, and is now infectious on a longer interval, so no other case loses its infector. The proposal has a positive density on , so such moves have positive probability. After such moves, all infections lie before , where every ordering is valid, and every vector of that kind can be reached from every other one by single moves. Since each kernel satisfies detailed balance, the moves can also be made in reverse with positive probability, so any valid vector can be reached from any other. The Gibbs steps have positive densities on .
Conclusion. The chain has the joint posterior as an invariant law and is irreducible with respect to it, so by the ergodic theorem for Markov chains the averages over the chain converge to the posterior expectations. The test with two cases checks this against the exact posterior of the infection times, where and are integrated out in closed form:
Complexity
One update of an infection time costs for the pair terms and for the sorted sweep. One iteration has updates and costs , so iterations cost . The people who are never infected enter only through the count , so the cost does not grow with . The chains of , and take space, and the working state takes . A balanced tree over the event times would make the infection term to update, but the pair terms of stay .
Properties
- Exact in the limit, not for finite runs. The invariant law is the exact posterior, with no approximation of the likelihood. The error of a finite run depends on how fast the chain mixes, and the successive values are correlated. Report the effective sample size, not the number of iterations.
- Conjugate rates. Gamma priors on the rates are conjugate for the complete-data likelihood, so the rates need no tuning and no rejection.
- No tuning of the proposal. The proposal for an infection time uses the current , so its scale follows the posterior. Its acceptance rate falls when the infection times are tightly fixed by the data, for example in a large outbreak with short infectious periods.
- Rates mix slowly when infection times do. given is sharply fixed by , and moves only by one infection time at a time. So and the infection times are strongly correlated in the chain.
- The posterior of comes for free. Each recorded pair gives a draw of , so its credible interval needs no extra work.
Variants and improvements
- Epidemics that are not over. If observation stops at a time , some cases are infected but not yet removed, and their number is unknown. Reversible jump moves add and remove such cases. O'Neill and Roberts gave this in the same paper. This page does not implement it.
- Other infectious periods. For a gamma or fixed infectious period, is replaced by the log density of each period, the rate loses its gamma conditional, and a random-walk step on it is used. The proposal for then draws from the period law.
- Block and joint moves. Moving several infection times at once, or moving together with all periods by a common scale factor, reduces the correlation between and .
- Non-centred parametrisations. Writing each period as with standard exponential makes and the less dependent in some data sets.
- Structured populations. Households, wards and networks add a term for each type of contact to . The same scheme of Gibbs steps for the rates and Metropolis-Hastings steps for the event times still applies.
- Other methods for the same data. Approximate Bayesian computation needs only a simulator, and particle filters, a kind of sequential Monte Carlo, give the likelihood of counts over time. Both avoid the latent event times. Approximate Bayesian computation gives an approximate posterior, and a particle filter gives a noisy estimate of the likelihood. The expectation-maximization algorithm uses the same missing-data view to find a maximum likelihood estimate.
When to use it
Use it when individual removal times are known, the number of cases is small to moderate, and a full Bayesian answer is needed, with the posterior of the rates, of and of the infection times. It is the standard tool for outbreaks in households, hospitals and farms, where the model has a known likelihood once the event times are known. For daily counts of a large epidemic, use a renewal method such as the Cori method, or a particle filter. For models without a tractable complete-data likelihood, use approximate Bayesian computation.
Pitfalls
- An invalid start. If some case is infected at a time when nobody is infectious, the likelihood is 0 and the acceptance ratio is undefined. Start from a valid vector, as line L1 does.
- Forgetting the zero-likelihood check. If case is the only infectious person when case is infected, a proposal that moves the infection of after the infection of makes the epidemic impossible. The sweep must return in this case, or the chain leaves the support.
- The first case. The first infection has no rate factor. Its time has a flat prior that is bounded above by but not below. The likelihood bounds it in practice, because an early first infection gives a long infectious period and a large , which the factor makes unlikely.
- The scale of . The rate in this page is . Some papers use , so their is this divided by , and the full conditional has rate .
- Short runs. Because and are correlated, a run of a few hundred iterations can look settled and still be far from the posterior. Run several chains from different starts and compare them.
- The model is assumed. The posterior is exact for the Markov SIR model with homogeneous mixing. If the true infectious period is far from exponential, or the population is structured, the rates are biased.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# 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)
epidemic_data_augmentation_mcmc.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/epidemic-data-augmentation-mcmc/. The authors are listed in prov/YHHCY9.jsonl.
"""Data augmentation MCMC for the Markov SIR epidemic with observed removals.
Model: N people, infection rate beta S I / N, removal rate gamma per case.
The epidemic is over, and the removal times r_1, ..., r_n of the n people
who were ever infected are known. Their infection times i_1, ..., i_n are
not. The earliest infection is the initial case; it has a flat prior on
(-inf, its removal time). The priors are beta ~ Gamma(a_beta, rate b_beta)
and gamma ~ Gamma(a_gamma, rate b_gamma).
The sampler keeps the infection times as extra unknowns. Given them, beta
and gamma have gamma full conditionals (Gibbs steps). Given beta and gamma,
one infection time at a time gets a Metropolis-Hastings step that proposes
r_j - Exp(gamma).
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import List, Sequence, Tuple
@dataclass
class Prior:
a_beta: float = 1.0
b_beta: float = 1.0 # rate
a_gamma: float = 1.0
b_gamma: float = 1.0 # rate
def pressure_integral(inf: Sequence[float], rem: Sequence[float], n_pop: int) -> float:
"""A = integral of S(t) I(t) dt, as a sum over pairs (case j, person k).
Case j can infect person k from i_j until min(r_j, i_k); a person who is
never infected has i_k = inf and adds r_j - i_j for every case j.
"""
n = len(inf)
total = 0.0
for j in range(n):
for k in range(n):
if k != j:
total += max(0.0, min(rem[j], inf[k]) - inf[j])
total += (n_pop - n) * (rem[j] - inf[j])
return total
def pair_terms(j: int, inf: Sequence[float], rem: Sequence[float], n_pop: int) -> float:
"""The terms of pressure_integral that involve case j, as infector or as
the person infected. A changes by the change of this sum when only i_j
moves, which costs O(n) in place of O(n^2)."""
n = len(inf)
total = (n_pop - n) * (rem[j] - inf[j])
for k in range(n):
if k != j:
total += max(0.0, min(rem[j], inf[k]) - inf[j])
total += max(0.0, min(rem[k], inf[j]) - inf[k])
return total
def log_infection_term(inf: Sequence[float], rem: Sequence[float]) -> float:
"""The sum of log I(i_j-) over all cases but the first, or -inf if some
case was infected while nobody was infectious. One sweep over the 2n
sorted event times, O(n log n)."""
events = sorted([(t, 1) for t in inf] + [(t, -1) for t in rem])
count, total, first = 0, 0.0, True
for _, kind in events:
if kind == 1:
if not first:
if count == 0:
return -math.inf
total += math.log(count)
first = False
count += kind
return total
def log_likelihood(inf, rem, n_pop: int, beta: float, gamma: float) -> float:
"""log of the density of the complete epidemic (infection and removal
times) given beta and gamma."""
if any(i >= r for i, r in zip(inf, rem)):
return -math.inf
li = log_infection_term(inf, rem)
if li == -math.inf:
return li
n = len(inf)
a = pressure_integral(inf, rem, n_pop)
d = sum(r - i for i, r in zip(inf, rem))
return ((n - 1) * math.log(beta / n_pop) + li - beta * a / n_pop
+ n * math.log(gamma) - gamma * d)
def initial_infection_times(rem: Sequence[float], gap: float = 1.0) -> List[float]:
"""A valid start: everyone infected before the first removal, in the order
of the removals, so each later case finds the earlier ones infectious."""
first = min(rem)
order = sorted(range(len(rem)), key=lambda j: rem[j])
inf = [0.0] * len(rem)
for rank, j in enumerate(order):
inf[j] = first - gap * (len(rem) - rank) / len(rem)
return inf
def run(rng, rem: Sequence[float], n_pop: int, prior: Prior, iterations: int,
updates_per_iteration: int | None = None) -> Tuple[List[float], List[float], List[List[float]]]:
"""The sampler. Returns the chains of beta, gamma and the infection times.
Draw order per iteration: rng.gammavariate for beta, rng.gammavariate for
gamma, then for each infection-time update rng.randrange (which case),
rng.expovariate (the proposal) and rng.random (the acceptance).
"""
n = len(rem)
if n < 1 or n > n_pop:
raise ValueError("need 1 <= n <= N")
k_updates = n if updates_per_iteration is None else updates_per_iteration
inf = initial_infection_times(rem) # @line L1
a = pressure_integral(inf, rem, n_pop)
li = log_infection_term(inf, rem)
betas, gammas, infs = [], [], []
for _ in range(iterations): # @line L2
d = sum(r - i for i, r in zip(inf, rem))
beta = rng.gammavariate(prior.a_beta + n - 1, 1.0 / (prior.b_beta + a / n_pop)) # @line L3
gamma = rng.gammavariate(prior.a_gamma + n, 1.0 / (prior.b_gamma + d)) # @line L4
for _ in range(k_updates):
j = rng.randrange(n) # @line L5
new = list(inf)
new[j] = rem[j] - rng.expovariate(gamma) # @line L6
u = rng.random()
li_new = log_infection_term(new, rem)
if li_new == -math.inf:
continue # the proposed epidemic is impossible: reject
a_new = a - pair_terms(j, inf, rem, n_pop) + pair_terms(j, new, rem, n_pop)
log_ratio = (li_new - li) - beta * (a_new - a) / n_pop
if math.log(1.0 - u) < log_ratio: # @line L7
inf, a, li = new, a_new, li_new
betas.append(beta) # @line L8
gammas.append(gamma)
infs.append(list(inf))
return betas, gammas, infs
def simulate_labeled(rng, n_pop: int, beta: float, gamma: float,
initial: int = 1) -> Tuple[List[float], List[float]]:
"""A complete labelled Markov SIR epidemic from `initial` cases at time 0.
Returns the infection and removal times of the people who were infected.
Draw order per event: rng.expovariate (the time), rng.random (the type),
then rng.randrange (which case is removed; the infected person is the
next label, since the labels of susceptibles are exchangeable).
"""
t = 0.0
inf = [0.0] * initial
rem = [math.inf] * initial
active = list(range(initial))
s = n_pop - initial
while active:
i = len(active)
a_inf = beta * s * i / n_pop
a0 = a_inf + gamma * i
t += rng.expovariate(a0)
if rng.random() * a0 < a_inf:
inf.append(t)
rem.append(math.inf)
active.append(len(inf) - 1)
s -= 1
else:
k = active.pop(rng.randrange(len(active)))
rem[k] = t
return inf, rem
test_epidemic_data_augmentation_mcmc.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/epidemic-data-augmentation-mcmc/. The authors are listed in prov/YHHCY9.jsonl.
import math
import random
from epidemic_data_augmentation_mcmc import (
Prior,
initial_infection_times,
log_infection_term,
log_likelihood,
pair_terms,
pressure_integral,
run,
simulate_labeled,
)
def event_log_likelihood(inf, rem, n_pop, beta, gamma):
"""The same density by a sweep over the events: the log rate of each
labelled event, minus the integral of the total rate between events."""
events = sorted([(t, "inf", j) for j, t in enumerate(inf)] + [(t, "rem", j) for j, t in enumerate(rem)])
s, i, last, total, started = n_pop, 0, None, 0.0, False
for t, kind, _ in events:
if started:
total -= (beta * s * i / n_pop + gamma * i) * (t - last)
if kind == "inf":
if started:
total += math.log(beta * i / n_pop) # rate beta S I / N, then 1/S for the label
started = True
s, i = s - 1, i + 1
else:
total += math.log(gamma) # rate gamma I, then 1/I for the label
i -= 1
last = t
return total
def test_likelihood_matches_event_sweep():
for seed in (3, 7, 9):
inf, rem = simulate_labeled(random.Random(seed), 30, 2.0, 1.0)
for beta, gamma in ((2.0, 1.0), (0.7, 1.9)):
got = log_likelihood(inf, rem, 30, beta, gamma)
want = event_log_likelihood(inf, rem, 30, beta, gamma)
assert abs(got - want) < 1e-8 * max(1.0, abs(want))
def test_pair_terms_give_the_change_of_the_integral():
inf, rem = simulate_labeled(random.Random(3), 30, 2.0, 1.0)
a = pressure_integral(inf, rem, 30)
for j in (0, 5, len(inf) - 1):
new = list(inf)
new[j] = rem[j] - 0.37
delta = pair_terms(j, new, rem, 30) - pair_terms(j, inf, rem, 30)
assert abs(a + delta - pressure_integral(new, rem, 30)) < 1e-9
def test_impossible_epidemics_have_zero_likelihood():
# Case 1 is infected at time 2, after case 0 was removed at time 1.
assert log_infection_term([0.0, 2.0], [1.0, 3.0]) == -math.inf
assert log_likelihood([0.0, 2.0], [1.0, 3.0], 5, 1.0, 1.0) == -math.inf
assert log_infection_term([0.0, 0.5], [1.0, 3.0]) == 0.0
start = initial_infection_times([4.0, 1.0, 2.5])
assert log_infection_term(start, [4.0, 1.0, 2.5]) > -math.inf
def exact_moments(rem, n_pop, prior, m=300):
"""E[r_1 - i_1], E[r_2 - i_2] and P(i_2 < i_1) for two cases, with beta
and gamma integrated out, by the midpoint rule on d = t / (1 - t)."""
n = len(rem)
def log_marg(inf):
li = log_infection_term(inf, rem)
if li == -math.inf:
return -math.inf
a = pressure_integral(inf, rem, n_pop)
d = sum(r - i for i, r in zip(inf, rem))
return (li - (prior.a_beta + n - 1) * math.log(prior.b_beta + a / n_pop)
- (prior.a_gamma + n) * math.log(prior.b_gamma + d))
tot = e1 = e2 = p = 0.0
for x in range(m):
t1 = (x + 0.5) / m
d1 = t1 / (1 - t1)
for y in range(m):
t2 = (y + 0.5) / m
d2 = t2 / (1 - t2)
lp = log_marg([rem[0] - d1, rem[1] - d2])
if lp == -math.inf:
continue
w = math.exp(lp) / ((1 - t1) * (1 - t2)) ** 2
tot += w
e1 += w * d1
e2 += w * d2
p += w * (rem[1] - d2 < rem[0] - d1)
return e1 / tot, e2 / tot, p / tot
def batch_means(xs, batches=40):
size = len(xs) // batches
means = [sum(xs[k * size:(k + 1) * size]) / size for k in range(batches)]
mu = sum(means) / batches
var = sum((v - mu) ** 2 for v in means) / (batches - 1)
return mu, math.sqrt(var / batches)
def test_chain_matches_exact_posterior_of_infection_times():
rem, n_pop = [1.0, 2.5], 3
prior = Prior(3.0, 2.0, 3.0, 2.0)
exact = exact_moments(rem, n_pop, prior)
_, _, infs = run(random.Random(20261118), rem, n_pop, prior, 30000)
stats = (
[rem[0] - x[0] for x in infs],
[rem[1] - x[1] for x in infs],
[1.0 if x[1] < x[0] else 0.0 for x in infs],
)
for xs, want in zip(stats, exact):
mu, se = batch_means(xs)
assert abs(mu - want) <= 4 * se + 3e-3
def test_parameters_are_recovered_from_a_simulated_epidemic():
inf, rem = simulate_labeled(random.Random(3), 30, 2.0, 1.0)
assert len(rem) == 24
betas, gammas, _ = run(random.Random(1), rem, 30, Prior(1.0, 1.0, 1.0, 1.0), 800)
betas, gammas = sorted(betas[200:]), sorted(gammas[200:])
k = len(betas)
assert betas[int(0.025 * k)] < 2.0 < betas[int(0.975 * k)]
assert gammas[int(0.025 * k)] < 1.0 < gammas[int(0.975 * k)]
History
Gibson and Renshaw (1998) used Markov chain Monte Carlo with the unobserved event times of stochastic compartmental models as extra unknowns. O'Neill and Roberts (1999) gave the scheme for the general stochastic epidemic with observed removal times: gamma full conditionals for the rates, Metropolis-Hastings moves for single infection times, and reversible jump moves for unknown numbers of cases. O'Neill (2002) wrote a tutorial account. The idea of data augmentation itself is older, from the work of Tanner and Wong on posterior computation with missing data. Later work extended the method to households, networks, hospital wards and farm outbreaks, and to non-centred and block updates that mix faster.
References
- O'Neill and Roberts 1999, the infection times as missing data, the gamma full conditionals of the rates, the Metropolis-Hastings moves of single infection times, and reversible jump moves for unknown numbers of cases
- Gibson and Renshaw 1998, Markov chain Monte Carlo with the unobserved event times of a compartmental model as extra unknowns
- O'Neill 2002, a worked account of the complete-data likelihood of the SIR model and of the data augmentation sampler
- Hakan Andersson and Tom Britton, Stochastic Epidemic Models and Their Statistical Analysis, Lecture Notes in Statistics 151, Springer, 2000, Chapter 2 (the standard SIR epidemic model) and the part on statistical inference for epidemic data
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YHHCY9 Edit this page History Report an error Markdown