Algorithm Search⌘K

Algorithmadvanced

Cori method for time-varying reproduction number

Also called EpiEstim method, Rt estimation.

Estimate R_t over a sliding window with a conjugate gamma posterior from a Poisson renewal model of daily incidence.

Time
Θ(T s) worst · average · best
Space
Θ(T) extra
Where
T = the number of days of incidence; s = the number of days in the generation interval distribution
Properties
deterministicexactonlineiterative
Origin
Anne Cori, Neil M. Ferguson, Christophe Fraser, Simon Cauchemez, 2013

The Cori method estimates how the reproduction number RtR_t of an epidemic changes over time from a series of daily case counts. It assumes the renewal equation: the expected number of new cases on day tt is RtR_t times the total infectiousness Λt\Lambda_t, the past cases weighted by the generation interval. It takes RtR_t as constant over a window of τ\tau days that ends on day tt, puts a gamma prior on it, and gets a gamma posterior in closed form, because the gamma law is the conjugate prior of the Poisson rate. Sliding the window over the series gives an estimate and a credible interval for every day, at a cost that is linear in the length of the series.

In plain words

Each sick person passes the disease on to some others over the next few days. On any day, you can add up how much "infecting power" is still active from the people who fell ill before. If ten new cases appear on a day with an infecting power worth only eight cases, then each case is passing the disease on to a bit more than one other person, and the epidemic grows.

One day gives a noisy answer, so the method uses a week at a time and assumes the true value stays the same over the week. It starts from a rough guess, then updates the guess with the counts of the week. The more cases there are, the narrower the range of likely values. Then it moves the week forward by one day and does it again.

The problem

Input. Daily incidence I1,…,ITI_1, \ldots, I_T (counts of new infections, or of new symptom onsets as a proxy). A generation interval distribution w1,…,wsw_1, \ldots, w_{s} with wu≥0w_u \ge 0, ∑uwu=1\sum_u w_u = 1, and w0=0w_0 = 0. A window length τ≥1\tau \ge 1. The shape a>0a > 0 and the scale b>0b > 0 of a gamma prior on RR.

Model. Given the earlier counts, ItI_t is Poisson(RtΛtR_t \Lambda_t), with Λt=∑u=1swuIt−u\Lambda_t = \sum_{u=1}^{s} w_u I_{t-u}, and RtR_t is constant over each window.

Output. For each window {t−τ+1,…,t}\{t - \tau + 1, \ldots, t\}, the posterior law of RR: its shape AtA_t and rate BtB_t, its mean, standard deviation and coefficient of variation, and chosen quantiles.

The algorithm

  1. CORI-RT(I[1..T], w, τ, a, b)
  2. 1for t ← 1 to T do Λ[t] ← Σ_{u=1}^{min(t-1, s)} w[u] I[t - u]
  3. 2for t ← τ + 1 to T do ▷ window t - τ + 1 .. t, starting on day 2 or later
  4. 3A ← a + Σ_{u=t-τ+1}^{t} I[u]
  5. 4B ← 1/b + Σ_{u=t-τ+1}^{t} Λ[u]
  6. 5mean ← A / B, sd ← √A / B
  7. 6quantiles ← quantiles of Gamma(shape A, rate B)
  8. 7output (t, A, B, mean, sd, quantiles)

Lines L3 and L4 use prefix sums of II and Λ\Lambda, so each window costs O(1)O(1) besides the quantiles. The implementation finds a quantile by bisection on the gamma distribution function, which it evaluates through the chi-squared tail: if RR is gamma with shape AA and rate BB, then 2BR2BR is chi-squared with 2A2A degrees of freedom. The prior in the example below has a=1a = 1 and b=5b = 5, a mean of 5 and a standard deviation of 5. That is a broad prior, and it is the value this page uses, not a property of the method.

Example

Take w1=0.2w_1 = 0.2, w2=0.5w_2 = 0.5, w3=0.3w_3 = 0.3 and the counts

day 1 2 3 4 5 6 7 8 9 10 11 12 13
ItI_t 10 4 8 9 11 14 15 21 24 16 18 15 13
Λt\Lambda_t 0 2.0 5.8 6.6 7.0 9.1 11.0 13.3 15.9 19.8 21.5 18.8 16.8

For example, Λ5=0.2×9+0.5×8+0.3×4=7.0\Lambda_5 = 0.2 \times 9 + 0.5 \times 8 + 0.3 \times 4 = 7.0. With windows of τ=4\tau = 4 days and the prior a=1a = 1, b=5b = 5, the first window is days 2 to 5. There A=1+(4+8+9+11)=33A = 1 + (4 + 8 + 9 + 11) = 33 and B=0.2+(2.0+5.8+6.6+7.0)=21.6B = 0.2 + (2.0 + 5.8 + 6.6 + 7.0) = 21.6, so the posterior mean is 33/21.6=1.52833 / 21.6 = 1.528, the standard deviation is 33/21.6=0.266\sqrt{33}/21.6 = 0.266 and the 95% credible interval is [1.052,2.091][1.052, 2.091]. The other windows give:

window AA BB mean 2.5% median 97.5%
2 to 5 33 21.6 1.528 1.052 1.512 2.091
4 to 7 50 33.9 1.475 1.095 1.465 1.911
6 to 9 75 49.5 1.515 1.192 1.508 1.877
8 to 11 80 70.7 1.132 0.897 1.127 1.393
10 to 13 63 77.1 0.817 0.628 0.813 1.031

The estimate falls below 1 in the last window, as the counts start to decline after day 9.

A step change. The implementation also simulates the Poisson renewal model. With a generation interval of mean 3.99 days spread over 8 days, a seed of 20 cases a day for 5 days, Rt=1.8R_t = 1.8 for 25 days and then Rt=0.7R_t = 0.7, seed 20261118 and weekly windows, the estimate for the window that ends on day 30 is 1.7901.790 with the interval [1.737,1.844][1.737, 1.844], and for the window that ends on day 55 it is 0.7450.745 with [0.693,0.799][0.693, 0.799]. The window that ends on day 35 straddles the change and gives 0.9560.956. So a window estimate lags a sudden change by up to τ\tau days.

Correctness

The full proof is in proofs/correctness.md. Because w0=0w_0 = 0, Λu\Lambda_u depends only on the counts before day uu. So by the chain rule, the probability of the counts in the window, given the earlier counts, is the product of Poisson(RΛuR \Lambda_u) masses. As a function of RR, it is proportional to R∑Iue−R∑ΛuR^{\sum I_u} e^{-R \sum \Lambda_u}. Multiplying by the gamma prior density Ra−1e−R/bR^{a-1} e^{-R/b} gives RA−1e−BRR^{A - 1} e^{-BR}, a gamma density with shape AA and rate BB. Lines L3 and L4 compute these two numbers with prefix sums, line L5 uses the gamma mean A/BA/B and variance A/B2A/B^2, and line L6 inverts the gamma distribution function, which is continuous and strictly increasing, by bisection.

Proof: The window likelihood, the gamma posterior and its summariesfull

Setting. Days are 1,…,T1, \ldots, T, with incidence I1,…,ITI_1, \ldots, I_T. The weights w1,…,wsmax⁡w_1, \ldots, w_{s_{\max}} are non-negative, and w0=0w_0 = 0. Cases before day 1 are taken as 0, so Λt=∑s=1min⁡(t−1,smax⁡)wsIt−s\Lambda_t = \sum_{s=1}^{\min(t - 1, s_{\max})} w_s I_{t-s}. Fix a window W={s0,…,t}W = \{s_0, \ldots, t\} of τ\tau days with s0≥2s_0 \ge 2. The model is: given I1,…,Iu−1I_1, \ldots, I_{u-1}, the count IuI_u is Poisson(RuΛuR_u \Lambda_u), and Ru=RR_u = R for every u∈Wu \in W. The days before s0s_0 have their own reproduction numbers, which do not involve RR. The prior on RR is a gamma law with shape a>0a > 0 and scale b>0b > 0, with density π(R)∝Ra−1e−R/b\pi(R) \propto R^{a - 1} e^{-R/b} on R>0R > 0.

Claim 1 (line L1). The list lam holds Λ1,…,ΛT\Lambda_1, \ldots, \Lambda_T.

Proof. For the day with index tt (0-based, day t+1t + 1), the loop adds wsIw_s I for the day ss steps before, for s=1,…,min⁡(t,smax⁡)s = 1, \ldots, \min(t, s_{\max}). These are exactly the terms of Λt+1\Lambda_{t+1} whose day is 1 or later; the terms for earlier days are 0 by the convention. The check w0=0w_0 = 0 makes sure that IuI_u never enters its own Λu\Lambda_u. □\square

Claim 2 (the window likelihood). As a function of RR,

P(Is0,…,It∣I1,…,Is0−1,R)=∏u∈W(RΛu)Iue−RΛuIu!∝R∑u∈WIuexp⁡(−R∑u∈WΛu).P(I_{s_0}, \ldots, I_t \mid I_1, \ldots, I_{s_0 - 1}, R) = \prod_{u \in W} \frac{(R \Lambda_u)^{I_u} e^{-R \Lambda_u}}{I_u!} \propto R^{\sum_{u \in W} I_u} \exp\Big(-R \sum_{u \in W} \Lambda_u\Big).

Proof. By the chain rule, the joint probability of the window counts given the earlier counts is the product over u∈Wu \in W of P(Iu∣I1,…,Iu−1,R)P(I_u \mid I_1, \ldots, I_{u-1}, R). Each factor is the Poisson(RΛuR \Lambda_u) mass at IuI_u, and Λu\Lambda_u is a fixed number given I1,…,Iu−1I_1, \ldots, I_{u-1}, because w0=0w_0 = 0. The factors ΛuIu/Iu!\Lambda_u^{I_u} / I_u! do not depend on RR. If Λu=0\Lambda_u = 0 the model forces Iu=0I_u = 0, and the factor is 1 for every RR, which agrees with the formula. □\square

Claim 3 (the posterior). The posterior of RR given I1,…,ItI_1, \ldots, I_t is the gamma law with shape A=a+∑u∈WIuA = a + \sum_{u \in W} I_u and rate B=1/b+∑u∈WΛuB = 1/b + \sum_{u \in W} \Lambda_u.

Proof. The probability of the days before s0s_0 does not depend on RR, by the setting. So by Bayes' theorem, the posterior density is proportional to the prior times the window likelihood of Claim 2:

Ra−1e−R/b⋅R∑Iue−R∑Λu=RA−1e−BR.R^{a - 1} e^{-R / b} \cdot R^{\sum I_u} e^{-R \sum \Lambda_u} = R^{A - 1} e^{-B R}.

Since A≥a>0A \ge a > 0 and B≥1/b>0B \ge 1/b > 0, this is integrable on (0,∞)(0, \infty), with integral Γ(A)/BA\Gamma(A) / B^A, and the normalized density is the gamma density with shape AA and rate BB. This is the conjugate update of a gamma prior by Poisson counts. □\square

Claim 4 (lines L2 to L4). For each tt from first_day+τ−1\text{first\_day} + \tau - 1 to TT, the code sets s=t−τ+1s = t - \tau + 1 and computes AA and BB of Claim 3 for the window {s,…,t}\{s, \ldots, t\}.

Proof. The prefix sums satisfy cI[k]=∑u=1kIuc_I[k] = \sum_{u=1}^{k} I_u and cΛ[k]=∑u=1kΛuc_\Lambda[k] = \sum_{u=1}^{k} \Lambda_u, by induction on kk, since each step adds the next term. So cI[t]−cI[s−1]=∑u=stIuc_I[t] - c_I[s - 1] = \sum_{u=s}^{t} I_u, and the same for Λ\Lambda. The loop starts at t=first_day+τ−1t = \text{first\_day} + \tau - 1, so s≥first_day≥2s \ge \text{first\_day} \ge 2 for every window, and the window has τ\tau days. □\square

Claim 5 (line L5). The mean is A/BA / B, the standard deviation is A/B\sqrt A / B, and the coefficient of variation is 1/A1 / \sqrt A.

Proof. For a gamma law with shape AA and rate BB, E[R]=∫0∞R⋅BAΓ(A)RA−1e−BR dR=BAΓ(A)⋅Γ(A+1)BA+1=ABE[R] = \int_0^\infty R \cdot \frac{B^A}{\Gamma(A)} R^{A-1} e^{-BR}\, dR = \frac{B^A}{\Gamma(A)} \cdot \frac{\Gamma(A+1)}{B^{A+1}} = \frac{A}{B}, and in the same way E[R2]=A(A+1)/B2E[R^2] = A(A+1)/B^2, so the variance is A/B2A / B^2. The ratio of the standard deviation to the mean is 1/A1/\sqrt A. □\square

Claim 6 (line L6). gamma_quantile(p, A, B) returns the pp-quantile of the posterior to within the tolerance.

Proof. If RR has the gamma law with shape AA and rate BB, then X=2BRX = 2BR has density proportional to xA−1e−x/2x^{A-1} e^{-x/2}, which is the chi-squared law with 2A2A degrees of freedom. So P(R≤x)=1−P(X>2Bx)P(R \le x) = 1 - P(X > 2Bx), which is what gamma_cdf computes with chi2_sf. This function FF is continuous and strictly increasing on (0,∞)(0, \infty), with F(0)=0F(0) = 0 and F(x)→1F(x) \to 1. The first loop doubles hi until F(hi)≥pF(\text{hi}) \ge p, which happens after finitely many steps. Then the invariant F(lo)<p≤F(hi)F(\text{lo}) < p \le F(\text{hi}) holds, since F(0)=0<pF(0) = 0 < p. Each bisection step keeps it, as it moves lo up only when F(mid)<pF(\text{mid}) < p and moves hi down otherwise. So the unique x∗x^* with F(x∗)=pF(x^*) = p stays in [lo,hi][\text{lo}, \text{hi}], and the returned midpoint is within the final interval length of x∗x^*. □\square

Conclusion. Each WindowEstimate holds the exact gamma posterior of RR for its window under the model, and its mean, standard deviation, coefficient of variation and quantiles. The test of simulation-based calibration checks Claim 3 as a whole: when RR is drawn from the prior and the data from the model, the posterior distribution function at the true RR is uniform.

Complexity

Line L1 costs Θ(Ts)\Theta(T s) arithmetic operations, where ss is the length of the generation interval. A fast convolution would make it O(Tlog⁡T)O(T \log T), which only helps when ss is large. The prefix sums take Θ(T)\Theta(T), and each window takes O(1)O(1) for AA, BB, the mean and the standard deviation. Each quantile takes a fixed number of bisection steps for a given tolerance, each with one evaluation of the incomplete gamma function. So the total is Θ(Ts)\Theta(T s) plus a cost per quantile that does not depend on TT. The extra space is Θ(T)\Theta(T) for Λ\Lambda and the prefix sums. When a new day of data arrives, one more Λ\Lambda value and one more window cost O(s)O(s).

Properties

  • Exact under the model. The posterior is exact, not an approximation, for the Poisson renewal model with RR constant on the window. Simulation-based calibration in the tests confirms it: with RR drawn from the prior, the posterior distribution function at the true RR is uniform.
  • Scale of the counts. If every count is multiplied by a constant reporting fraction, Λ\Lambda scales in the same way, so the posterior mean barely moves, but the interval shrinks or widens with the count.
  • Precision from the count. The coefficient of variation of the posterior is 1/A1/\sqrt{A}, so it depends only on the number of cases in the window, plus aa. About 100 cases in a window give a coefficient of variation near 0.1.
  • Uses only the past. The estimate for day tt uses counts up to day tt. It estimates the instantaneous reproduction number, not the case reproduction number, which needs future data.

Variants and improvements

  • Uncertainty in the generation interval. Draw many plausible interval distributions, compute the posterior for each, and pool the samples. The EpiEstim package offers this, and Thompson et al. extended it.
  • Imported cases. Cases infected elsewhere count in Λ\Lambda, because they can infect others, but not in the window sum of II, because local transmission did not cause them. Counting them as local makes RtR_t too high early in an outbreak.
  • Wallinga and Teunis. A related method estimates the case reproduction number from the likelihood that each case infected each later one. It needs future data, so recent values are revised.
  • Smooth priors and state-space models. In place of independent windows, let log⁡Rt\log R_t follow a random walk, and use a particle filter or sequential Monte Carlo for the filtered law of RtR_t. This also allows observation models with reporting delays and negative binomial noise.
  • Other window rules. Non-overlapping windows, or windows set at the times of known changes, such as the start of a lockdown.

When to use it

Use it for quick, transparent estimates of RtR_t from a clean daily series of infections or symptom onsets, when the generation interval is known from other studies. It has no tuning beyond the window, the prior and ww, and it runs in a fraction of a second on a series of years. Do not use it on raw counts by report date when the delay from infection to report is long or changing; model the delay first, or use a method with an explicit observation model (Gostic et al.).

Pitfalls

  • Wrong interval distribution. The estimate depends on ww: for the same growth rate, a longer interval gives a larger RR (see the generation interval). The serial interval is often used in place of the generation interval because it is easier to observe. Its mean is about the same, but a larger spread changes RtR_t when it is far from 1.
  • The first entry of ww. It must be 0. A case cannot infect on the day of its own infection, and a positive w0w_0 would put ItI_t inside its own Λt\Lambda_t. EpiEstim rejects such a distribution.
  • Reporting delays. Counts by date of report describe infections some days earlier. An estimate from them refers to that earlier time, and it is smeared by the spread of the delay. Right truncation, the missing recent cases that are not reported yet, makes the latest estimates too low.
  • The start of an epidemic. When Λ\Lambda is small, the prior has a large weight, and the estimate is unreliable. Check the coefficient of variation 1/A1/\sqrt{A} before reading the estimate.
  • Window lag. The estimate for the window that ends on day tt describes the whole window. A sudden change shows up in full only τ\tau days later, as in the step change example.
  • Changes in testing. If the fraction of infections that are counted changes over the window, the counts change for reasons other than transmission, and RtR_t moves with them.

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)
cori_rt_estimation.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cori-rt-estimation/. The authors are listed in prov/FC6CRV.jsonl.
"""The Cori method: a gamma posterior for R_t over sliding windows.

Model: I_t given the past is Poisson(R Lambda_t), with the total
infectiousness Lambda_t = sum over s >= 1 of w[s] I_(t-s), and R constant
over each window of tau days. With a gamma prior of shape a and scale b on R,
the posterior over the window that ends on day t is a gamma law with

    shape A = a + (sum of I_s over the window),
    rate  B = 1 / b + (sum of Lambda_s over the window).

Days are numbered 1 to T; incidence[0] is day 1. w[0] must be 0, and w[s] is
the weight of an infector infected s days earlier.
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from typing import List, Sequence, Tuple

from biostoch import chi2_sf, poisson


@dataclass
class WindowEstimate:
    t_start: int  # first day of the window (1-based)
    t_end: int  # last day of the window
    shape: float  # A
    rate: float  # B
    mean: float
    sd: float
    cv: float
    quantiles: Tuple[float, ...]


def total_infectiousness(incidence: Sequence[float], w: Sequence[float]) -> List[float]:
    """Lambda_t for t = 1 .. T, with the cases before day 1 taken as 0."""
    if w and w[0] != 0:
        raise ValueError("w[0] must be 0: no infection on the day of one's own infection")
    T = len(incidence)
    lam = [0.0] * T
    for t in range(T):
        acc = 0.0
        for s in range(1, min(t, len(w) - 1) + 1):
            acc += w[s] * incidence[t - s]
        lam[t] = acc
    return lam


def gamma_cdf(x: float, shape: float, rate: float) -> float:
    """P(X <= x) for X ~ Gamma(shape, rate), as 1 - chi2_sf(2 rate x, 2 shape)."""
    if x <= 0:
        return 0.0
    return 1.0 - chi2_sf(2.0 * rate * x, 2.0 * shape)


def gamma_quantile(p: float, shape: float, rate: float, tol: float = 1e-12) -> float:
    """The p-quantile of Gamma(shape, rate) by bisection on gamma_cdf."""
    if not 0.0 < p < 1.0:
        raise ValueError("need 0 < p < 1")
    lo, hi = 0.0, (shape + 10.0 * math.sqrt(shape) + 10.0) / rate
    while gamma_cdf(hi, shape, rate) < p:
        hi *= 2.0
    while hi - lo > tol * max(1.0, hi):
        mid = 0.5 * (lo + hi)
        if gamma_cdf(mid, shape, rate) < p:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def estimate(incidence: Sequence[float], w: Sequence[float], tau: int = 7,
             a: float = 1.0, b: float = 5.0,
             probs: Sequence[float] = (0.025, 0.5, 0.975),
             first_day: int = 2) -> List[WindowEstimate]:
    """Posterior summaries of R for every window of tau days inside first_day .. T.

    Windows start on first_day or later, so that Lambda uses at least one
    past day. a and b are the shape and the scale of the gamma prior.
    """
    if tau < 1 or a <= 0 or b <= 0:
        raise ValueError("need tau >= 1, a > 0 and b > 0")
    T = len(incidence)
    lam = total_infectiousness(incidence, w)  # @line L1
    ci = [0.0] * (T + 1)  # prefix sums of I and Lambda
    cl = [0.0] * (T + 1)
    for t in range(T):
        ci[t + 1] = ci[t] + incidence[t]
        cl[t + 1] = cl[t] + lam[t]
    out = []
    for t in range(first_day + tau - 1, T + 1):  # @line L2
        s = t - tau + 1
        A = a + ci[t] - ci[s - 1]  # @line L3
        B = 1.0 / b + cl[t] - cl[s - 1]  # @line L4
        mean, sd = A / B, math.sqrt(A) / B  # @line L5
        qs = tuple(gamma_quantile(p, A, B) for p in probs)  # @line L6
        out.append(WindowEstimate(s, t, A, B, mean, sd, 1.0 / math.sqrt(A), qs))  # @line L7
    return out


def simulate(rng, seed: Sequence[int], r_path: Sequence[float], w: Sequence[float]) -> List[int]:
    """Incidence from the Poisson renewal model.

    seed gives the first days. Day len(seed) + k + 1 gets
    Poisson(r_path[k] Lambda), one biostoch.poisson draw per day, in order.
    """
    inc = list(seed)
    for r in r_path:
        t = len(inc)
        lam = sum(w[s] * inc[t - s] for s in range(1, min(t, len(w) - 1) + 1))
        inc.append(poisson(rng, r * lam))
    return inc
test_cori_rt_estimation.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cori-rt-estimation/. The authors are listed in prov/FC6CRV.jsonl.

import math
import random

from biostoch import chi2_sf
from cori_rt_estimation import estimate, gamma_cdf, gamma_quantile, simulate, total_infectiousness

W = [0, 0.2, 0.5, 0.3]
INC = [10, 4, 8, 9, 11, 14, 15, 21, 24, 16, 18, 15, 13]


def test_total_infectiousness_by_hand():
    lam = total_infectiousness(INC, W)
    assert lam[:5] == [0.0, 2.0, 5.8, 6.6, 7.0]
    # Day 6: 0.2 * 11 + 0.5 * 9 + 0.3 * 8
    assert abs(lam[5] - 9.1) < 1e-12


def test_window_posterior_by_hand():
    first = estimate(INC, W, tau=4, a=1.0, b=5.0)[0]
    assert (first.t_start, first.t_end) == (2, 5)
    assert first.shape == 1 + 4 + 8 + 9 + 11
    assert abs(first.rate - (0.2 + 2.0 + 5.8 + 6.6 + 7.0)) < 1e-12
    assert abs(first.mean - 33 / 21.6) < 1e-12
    assert abs(first.cv - 1 / math.sqrt(33)) < 1e-12


def test_posterior_matches_grid_integration():
    a, b, tau = 1.0, 5.0, 4
    lam = total_infectiousness(INC, W)
    est = estimate(INC, W, tau=tau, a=a, b=b, probs=(0.025, 0.5, 0.975))
    for e in (est[0], est[-1]):
        days = range(e.t_start - 1, e.t_end)

        def log_post(r):
            v = (a - 1) * math.log(r) - r / b
            for d in days:
                v += INC[d] * math.log(r * lam[d]) - r * lam[d]
            return v

        n, top = 40000, 6.0
        h = top / n
        grid = [(k + 0.5) * h for k in range(n)]
        lp = [log_post(r) for r in grid]
        m = max(lp)
        dens = [math.exp(x - m) for x in lp]
        z = sum(dens)
        mean = sum(r * d for r, d in zip(grid, dens)) / z
        assert abs(mean - e.mean) < 1e-6
        acc, qi, probs, found = 0.0, 0, (0.025, 0.5, 0.975), []
        for r, d in zip(grid, dens):
            acc += d / z
            while qi < 3 and acc >= probs[qi]:
                found.append(r)
                qi += 1
        for q_grid, q in zip(found, e.quantiles):
            assert abs(q_grid - q) < 2e-3


def test_gamma_quantile():
    for p in (0.025, 0.5, 0.9):
        assert abs(gamma_quantile(p, 1.0, 2.0) + math.log(1 - p) / 2.0) < 1e-9
    q = gamma_quantile(0.975, 50.0, 10.0)
    assert abs(gamma_cdf(q, 50.0, 10.0) - 0.975) < 1e-9


def test_no_cases_gives_the_prior():
    e = estimate([0] * 10, W, tau=7, a=2.0, b=3.0)[0]
    assert e.shape == 2.0 and abs(e.rate - 1 / 3) < 1e-12


def test_simulation_based_calibration():
    # R from the prior, a fixed seed on days 1 to 5, and the window of days
    # 6 to 12. The posterior CDF at the true R must then be Uniform(0, 1).
    rng = random.Random(20261118)
    a, b, runs, bins = 2.0, 0.75, 1000, 10
    seed = [3, 5, 4, 6, 5]
    counts = [0] * bins
    for _ in range(runs):
        r = rng.gammavariate(a, b)
        inc = simulate(rng, seed, [r] * 7, W)
        (e,) = estimate(inc, W, tau=7, a=a, b=b, probs=(), first_day=6)
        u = gamma_cdf(r, e.shape, e.rate)
        counts[min(bins - 1, int(u * bins))] += 1
    stat = sum((c - runs / bins) ** 2 / (runs / bins) for c in counts)
    assert chi2_sf(stat, bins - 1) > 0.001


def test_step_change_is_recovered():
    rng = random.Random(20261118)
    w = [0, 0.05, 0.15, 0.25, 0.2, 0.15, 0.1, 0.06, 0.04]
    inc = simulate(rng, [20] * 5, [1.8] * 25 + [0.7] * 25, w)
    est = {e.t_end: e for e in estimate(inc, w, tau=7)}
    lo, _, hi = est[30].quantiles
    assert lo < 1.8 < hi
    lo, _, hi = est[55].quantiles
    assert lo < 0.7 < hi
    # A window that straddles the change gives a value in between.
    assert 0.7 < est[35].mean < 1.8

History

Fraser (2007) defined the instantaneous reproduction number through the renewal equation and showed how to estimate it from incidence. Cori, Ferguson, Fraser and Cauchemez (2013) turned this into a simple Bayesian method with a gamma posterior over sliding windows, and they published it with the R package EpiEstim. The method came into wide use for real-time tracking of epidemics, and later work added the uncertainty in the serial interval, imported cases (Thompson et al.) and studies of its biases (Gostic et al.).

References

  1. Cori et al. 2013, the Poisson renewal likelihood over a window, the gamma posterior, and the EpiEstim software
  2. Christophe Fraser, Estimating individual and household reproduction numbers in an emerging epidemic, PLoS ONE 2(8), e758, 2007, the instantaneous reproduction number and its estimation from the renewal equation
  3. EpiEstim reference manual, make_config, the window settings, with weekly sliding windows in the example, and the rule that the first entry of the serial interval distribution must be 0
  4. Gostic et al. 2020, the effects of reporting delays, of the choice of the interval distribution and of the window length on estimates of R_t
  5. Thompson et al. 2019, imported cases and the uncertainty in the serial interval

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