Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
Origin
Philip D. O'Neill, Gareth O. Roberts, Gavin J. Gibson, Eric Renshaw, 1999

Data augmentation MCMC estimates the infection rate β\beta and the removal rate γ\gamma 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 β\beta and γ\gamma 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 R0=β/γR_0 = \beta/\gamma 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 NN people follows the Markov SIR model: each susceptible is infected at rate βI/N\beta I/N, and each infectious person is removed at rate γ\gamma. One person starts the epidemic. The epidemic is over.

Input. The removal times r1,…,rnr_1, \ldots, r_n of the n≥1n \ge 1 people who were ever infected, and NN. Priors β∼Gamma⁡(aβ,rate bβ)\beta \sim \operatorname{Gamma}(a_\beta, \text{rate } b_\beta) and γ∼Gamma⁡(aγ,rate bγ)\gamma \sim \operatorname{Gamma}(a_\gamma, \text{rate } b_\gamma), independent, with a flat prior on the infection time of the first case. A number of iterations MM.

Output. A sample (β(m),γ(m),i(m))m=1M(\beta^{(m)}, \gamma^{(m)}, \mathbf i^{(m)})_{m=1}^{M} from a Markov chain whose invariant law is the joint posterior of β\beta, γ\gamma and the infection times i=(i1,…,in)\mathbf i = (i_1, \ldots, i_n) given r\mathbf r.

The complete-data likelihood. Let I(t−)I(t-) be the number infectious just before tt, let κ\kappa be the first case, and let

A=∫S(t)I(t) dt=∑j=1n∑k≠j(min⁡(rj,ik)−min⁡(ij,ik)),D=∑j=1n(rj−ij),A = \int S(t) I(t)\, dt = \sum_{j=1}^{n} \sum_{k \ne j} \big(\min(r_j, i_k) - \min(i_j, i_k)\big), \qquad D = \sum_{j=1}^{n} (r_j - i_j),

where kk runs over all NN people and ik=∞i_k = \infty for a person who is never infected. Then

L(β,γ;i,r)=(βN)n−1∏j≠κI(ij−) γn e−βA/N−γDL(\beta, \gamma; \mathbf i, \mathbf r) = \Big(\frac{\beta}{N}\Big)^{n-1} \prod_{j \ne \kappa} I(i_j-)\ \gamma^n\, e^{-\beta A/N - \gamma D}

if ij<rji_j < r_j for all jj and I(ij−)≥1I(i_j-) \ge 1 for every j≠κj \ne \kappa, and L=0L = 0 if not.

The algorithm

  1. DA-MCMC(r[1..n], N, a_β, b_β, a_γ, b_γ, M)
  2. 1i ← all infections in [min r - 1, min r), in the order of r; A ← A(i)
  3. 2for m ← 1 to M do
  4. 3β ← draw from Gamma(a_β + n - 1, rate b_β + A/N)
  5. 4γ ← draw from Gamma(a_γ + n, rate b_γ + Σ_j (r_j - i_j))
  6. 5repeat n times: j ← uniform in {1, …, n}
  7. 6i′ ← i with i′_j ← r_j - E, where E ← draw from Exp(γ)
  8. 7if 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′)
  9. 8record (β, γ, 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 iji_j, and it draws the infectious period of case jj from its law under the model. For this reason the factor γne−γD\gamma^n e^{-\gamma D} cancels in the acceptance ratio of line L7, and only the infection term and the pressure AA remain. The change of AA comes from the O(n)O(n) pair terms that involve case jj, and the infection term comes from one sorted sweep over the 2n2n 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 N=3N = 3 and two cases with removal times r1=1r_1 = 1 and r2=2.5r_2 = 2.5, and the priors Gamma⁡(3,rate 2)\operatorname{Gamma}(3, \text{rate } 2) for both rates. If we integrate the rates out, the posterior of the infection times is proportional to ∏j≠κI(ij−) (bβ+A/N)−(aβ+n−1)(bγ+D)−(aγ+n)\prod_{j \ne \kappa} I(i_j-)\,(b_\beta + A/N)^{-(a_\beta + n - 1)}(b_\gamma + D)^{-(a_\gamma + n)}. A grid of 500×500500 \times 500 points gives the posterior means E[r1−i1]=0.6937E[r_1 - i_1] = 0.6937 and E[r2−i2]=2.1937E[r_2 - i_2] = 2.1937, and the probability 0.49990.4999 that case 2 was infected first. A run of 40000 iterations from seed 20261118 gives 0.6967±0.00720.6967 \pm 0.0072, 2.1953±0.01192.1953 \pm 0.0119 and 0.4968±0.00560.4968 \pm 0.0056, where each ±\pm 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 N=30N = 30, β=2\beta = 2, γ=1\gamma = 1, so R0=2R_0 = 2 is above the epidemic threshold, and seed 3, one case at time 0 leads to n=24n = 24 cases, and the last removal is at time 5.689. The sampler gets only the 24 removal times. With the priors Gamma⁡(1,rate 1)\operatorname{Gamma}(1, \text{rate } 1) for both rates, seed 1, 1500 iterations and the first 300 discarded:

quantity true value posterior mean 95% credible interval
β\beta 2 2.163 [1.188, 3.520]
γ\gamma 1 1.060 [0.601, 1.837]
R0=β/γR_0 = \beta/\gamma 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 R0R_0 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, βI(ij−)/N\beta I(i_j-)/N for each infection after the first and γ\gamma for each removal, times exp⁡\exp of minus the integral of the total rate βSI/N+γI\beta S I/N + \gamma I. Since ∫I dt=D\int I\, dt = D and ∫SI dt=A\int S I\, dt = A, this gives LL. As a function of β\beta and γ\gamma, LL 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 i\mathbf i given the rates, with the proposal density γe−γ(rj−ij′)\gamma e^{-\gamma(r_j - i_j')}. The proposal ratio cancels the factor e−γDe^{-\gamma D}, so the acceptance ratio is the expression in line L7, and an invalid proposal has L=0L = 0 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 NN people follows the Markov SIR model: when SS people are susceptible and II are infectious, each susceptible is infected at rate βI/N\beta I / N, and each infectious person is removed at rate γ\gamma. The epidemic is complete. The n≥1n \ge 1 people who were ever infected have the labels 1,…,n1, \ldots, n, known removal times r1,…,rnr_1, \ldots, r_n and unknown infection times i1,…,ini_1, \ldots, i_n. The other N−nN - n people are never infected; we write ik=∞i_k = \infty for them. Let κ\kappa be the person with the earliest infection time, the initial case, and let I(t−)I(t-) be the number infectious just before tt. We call the vector i=(i1,…,in)\mathbf i = (i_1, \ldots, i_n) valid if ij<rji_j < r_j for all jj and I(ij−)≥1I(i_j-) \ge 1 for every j≠κj \ne \kappa. The priors are β∼Gamma⁡(aβ,rate bβ)\beta \sim \operatorname{Gamma}(a_\beta, \text{rate } b_\beta), γ∼Gamma⁡(aγ,rate bγ)\gamma \sim \operatorname{Gamma}(a_\gamma, \text{rate } b_\gamma), independent, and a flat prior on iκi_\kappa.

Claim 1 (the complete-data likelihood). For a valid i\mathbf i, the density of the infection and removal times given β\beta, γ\gamma and iκi_\kappa is

L(β,γ;i)=(βN)n−1∏j≠κI(ij−) γnexp⁡(−βNA−γD),L(\beta, \gamma; \mathbf i) = \Big(\frac{\beta}{N}\Big)^{n-1} \prod_{j \ne \kappa} I(i_j-)\ \gamma^n \exp\Big(-\frac{\beta}{N} A - \gamma D\Big),

with A=∫S(t)I(t) dtA = \int S(t) I(t)\, dt and D=∑j(rj−ij)D = \sum_j (r_j - i_j). 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 kk is infected at rate βI/N\beta I / N while susceptible and removed at rate γ\gamma 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 n−1n - 1 infections after the first one contribute βI(ij−)/N\beta I(i_j-) / N each, the nn removals contribute γ\gamma each, and the total rate is βNS(t)I(t)+γI(t)\frac{\beta}{N} S(t) I(t) + \gamma I(t). Its integral is βNA+γ∫I(t) dt\frac{\beta}{N} A + \gamma \int I(t)\, dt, and ∫I(t) dt=∑j(rj−ij)=D\int I(t)\, dt = \sum_j (r_j - i_j) = D, since person jj is infectious exactly on [ij,rj)[i_j, r_j). If I(ij−)=0I(i_j-) = 0 for some j≠κj \ne \kappa, the rate of that infection is 0, so the density is 0. □\square

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 AA). A=∑j=1n∑k≠j(min⁡(rj,ik)−min⁡(ij,ik))A = \sum_{j=1}^{n} \sum_{k \ne j} \big(\min(r_j, i_k) - \min(i_j, i_k)\big), where kk runs over all NN people. For k≤nk \le n the term equals max⁡(0,min⁡(rj,ik)−ij)\max(0, \min(r_j, i_k) - i_j), and each of the N−nN - n people who are never infected adds rj−ijr_j - i_j. So pressure_integral computes AA.

Proof. S(t)I(t)S(t) I(t) counts the pairs (j,k)(j, k) with jj infectious and kk susceptible at time tt. So AA is the sum over pairs of the length of the time when both hold, which is the length of [ij,rj)∩(−∞,ik)[i_j, r_j) \cap (-\infty, i_k). That length is max⁡(0,min⁡(rj,ik)−ij)\max(0, \min(r_j, i_k) - i_j), which equals min⁡(rj,ik)−min⁡(ij,ik)\min(r_j, i_k) - \min(i_j, i_k), and it is rj−ijr_j - i_j when ik=∞i_k = \infty. □\square

Claim 3 (the update of AA). If only iji_j changes, AA changes by the change of pair_terms(j, ...).

Proof. By Claim 2, AA is a sum of terms indexed by pairs. The terms that depend on iji_j are those with jj as the infector (the pairs (j,k)(j, k), including the N−nN - n terms rj−ijr_j - i_j) and those with jj as the susceptible (the pairs (k,j)(k, j)). pair_terms adds exactly these terms, and every other term is the same before and after the change. □\square

Claim 4 (the infection term). log_infection_term returns ∑j≠κlog⁡I(ij−)\sum_{j \ne \kappa} \log I(i_j-) for a vector with ij<rji_j < r_j for all jj, or −∞-\infty if some j≠κj \ne \kappa has I(ij−)=0I(i_j-) = 0.

Proof. The sweep visits the 2n2n 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 [ij,rj)[i_j, r_j), the counter just before an event at time tt equals I(t−)I(t-), the number with ik<t≤rki_k < t \le r_k processed so far. The first infection is that of κ\kappa and is skipped. At every later infection the code adds log⁡I(ij−)\log I(i_j-), or returns −∞-\infty if the counter is 0. Event times are distinct with probability 1 under the proposal, which has a continuous density. □\square

Claim 5 (the Gibbs steps, lines L3 and L4). Given i\mathbf i, the posterior of β\beta is Gamma⁡(aβ+n−1,rate bβ+A/N)\operatorname{Gamma}(a_\beta + n - 1, \text{rate } b_\beta + A/N), the posterior of γ\gamma is Gamma⁡(aγ+n,rate bγ+D)\operatorname{Gamma}(a_\gamma + n, \text{rate } b_\gamma + D), and the two are independent.

Proof. The joint posterior density is proportional to L(β,γ;i) π(β) π(γ)L(\beta, \gamma; \mathbf i)\, \pi(\beta)\, \pi(\gamma). As a function of β\beta and γ\gamma for a fixed valid i\mathbf i, it is

βaβ−1+n−1e−β(bβ+A/N)⋅γaγ−1+ne−γ(bγ+D),\beta^{a_\beta - 1 + n - 1} e^{-\beta (b_\beta + A/N)} \cdot \gamma^{a_\gamma - 1 + n} e^{-\gamma (b_\gamma + D)},

a product of a gamma kernel in β\beta and a gamma kernel in γ\gamma. The code calls gammavariate with the shape and the scale 1/rate1/\text{rate}. □\square

Claim 6 (the Metropolis-Hastings step, lines L5 to L7). Given β\beta and γ\gamma, one update of iji_j leaves the conditional law p(i∣β,γ)∝L(β,γ;i)p(\mathbf i \mid \beta, \gamma) \propto L(\beta, \gamma; \mathbf i) invariant.

Proof. The update picks jj uniformly and proposes ij′=rj−Ei_j' = r_j - E with E∼Exp⁡(γ)E \sim \operatorname{Exp}(\gamma), whatever the current iji_j. The proposal density is q(ij′)=γe−γ(rj−ij′)q(i_j') = \gamma e^{-\gamma (r_j - i_j')} on (−∞,rj)(-\infty, r_j). The Metropolis-Hastings ratio for moving from i\mathbf i to i′\mathbf i' is

L(i′) q(ij)L(i) q(ij′).\frac{L(\mathbf i')\, q(i_j)}{L(\mathbf i)\, q(i_j')}.

In LL, the factor e−γDe^{-\gamma D} changes by e−γ[(rj−ij′)−(rj−ij)]e^{-\gamma[(r_j - i_j') - (r_j - i_j)]}, and q(ij)/q(ij′)q(i_j)/q(i_j') is e−γ[(rj−ij)−(rj−ij′)]e^{-\gamma[(r_j - i_j) - (r_j - i_j')]}; the two cancel. The factors (β/N)n−1(\beta/N)^{n-1} and γn\gamma^n do not change. So the ratio is

exp⁡(∑k≠κ′log⁡I′(ik′−)−∑k≠κlog⁡I(ik−)−βN(A′−A)),\exp\Big(\sum_{k \ne \kappa'} \log I'(i_k'-) - \sum_{k \ne \kappa} \log I(i_k-) - \frac{\beta}{N}(A' - A)\Big),

which is log_ratio by Claims 3 and 4. If i′\mathbf i' is not valid, L(i′)=0L(\mathbf i') = 0 and the ratio is 0, so the code rejects. The test log⁡(1−u)<log_ratio\log(1 - u) < \text{log\_ratio}, with uu uniform on [0,1)[0, 1), accepts with probability min⁡(1,elog_ratio)\min(1, e^{\text{log\_ratio}}). This is the Metropolis-Hastings rule, so the kernel satisfies detailed balance with respect to p(i∣β,γ)p(\mathbf i \mid \beta, \gamma), and a mixture over jj of such kernels does too. □\square

Claim 7 (invariance of the whole sweep). One iteration of lines L3 to L7 leaves the joint posterior of (β,γ,i)(\beta, \gamma, \mathbf i) invariant.

Proof. Lines L3 and L4 together draw (β,γ)(\beta, \gamma) from their joint conditional given i\mathbf i (Claim 5), which leaves the joint posterior invariant, as every Gibbs step does. Each update of lines L5 to L7 changes only i\mathbf i and leaves p(i∣β,γ)p(\mathbf i \mid \beta, \gamma) invariant (Claim 6), so it leaves the joint posterior invariant. A composition of kernels that leave a law invariant leaves it invariant. □\square

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 [rmin⁡−1,rmin⁡)[r_{\min} - 1, r_{\min}) 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 rmin⁡r_{\min}. So the vector is valid. For irreducibility, note that moving a case jj to a time earlier than every current infection time keeps the vector valid: jj becomes the first case and needs no infector, and jj is now infectious on a longer interval, so no other case loses its infector. The proposal has a positive density on (−∞,rj)(-\infty, r_j), so such moves have positive probability. After nn such moves, all infections lie before rmin⁡r_{\min}, 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 (0,∞)2(0, \infty)^2. □\square

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 β\beta and γ\gamma are integrated out in closed form:

p(i∣r)∝∏j≠κI(ij−) (bβ+A/N)−(aβ+n−1)(bγ+D)−(aγ+n).p(\mathbf i \mid \mathbf r) \propto \prod_{j \ne \kappa} I(i_j-)\ \big(b_\beta + A/N\big)^{-(a_\beta + n - 1)} \big(b_\gamma + D\big)^{-(a_\gamma + n)}.

Complexity

One update of an infection time costs O(n)O(n) for the pair terms and O(nlog⁡n)O(n \log n) for the sorted sweep. One iteration has nn updates and costs Θ(n2log⁡n)\Theta(n^2 \log n), so MM iterations cost Θ(Mn2log⁡n)\Theta(M n^2 \log n). The N−nN - n people who are never infected enter only through the count N−nN - n, so the cost does not grow with NN. The chains of β\beta, γ\gamma and i\mathbf i take Θ(Mn)\Theta(M n) space, and the working state takes Θ(n)\Theta(n). A balanced tree over the event times would make the infection term O(log⁡n)O(\log n) to update, but the pair terms of AA stay O(n)O(n).

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 γ\gamma, 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. γ\gamma given i\mathbf i is sharply fixed by DD, and DD moves only by one infection time at a time. So γ\gamma and the infection times are strongly correlated in the chain.
  • The posterior of R0R_0 comes for free. Each recorded pair gives a draw of β/γ\beta/\gamma, so its credible interval needs no extra work.

Variants and improvements

  • Epidemics that are not over. If observation stops at a time TT, 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, DD is replaced by the log density of each period, the rate γ\gamma loses its gamma conditional, and a random-walk step on it is used. The proposal for iji_j then draws from the period law.
  • Block and joint moves. Moving several infection times at once, or moving γ\gamma together with all periods by a common scale factor, reduces the correlation between γ\gamma and i\mathbf i.
  • Non-centred parametrisations. Writing each period as Ej/γE_j/\gamma with EjE_j standard exponential makes γ\gamma and the EjE_j less dependent in some data sets.
  • Structured populations. Households, wards and networks add a term for each type of contact to AA. 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 R0R_0 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 jj is the only infectious person when case kk is infected, a proposal that moves the infection of jj after the infection of kk makes the epidemic impossible. The sweep must return −∞-\infty 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 rκr_\kappa but not below. The likelihood bounds it in practice, because an early first infection gives a long infectious period and a large DD, which the factor e−γDe^{-\gamma D} makes unlikely.
  • The scale of β\beta. The rate in this page is βSI/N\beta S I/N. Some papers use βSI\beta S I, so their β\beta is this β\beta divided by NN, and the full conditional has rate bβ+Ab_\beta + A.
  • Short runs. Because γ\gamma and DD 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.

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)
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

  1. 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
  2. Gibson and Renshaw 1998, Markov chain Monte Carlo with the unobserved event times of a compartmental model as extra unknowns
  3. O'Neill 2002, a worked account of the complete-data likelihood of the SIR model and of the data augmentation sampler
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example