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
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Anne Cori, Neil M. Ferguson, Christophe Fraser, Simon Cauchemez, 2013
The Cori method estimates how the reproduction number 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 is times the total infectiousness , the past cases weighted by the generation interval. It takes as constant over a window of days that ends on day , 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 (counts of new infections, or of new symptom onsets as a proxy). A generation interval distribution with , , and . A window length . The shape and the scale of a gamma prior on .
Model. Given the earlier counts, is Poisson(), with , and is constant over each window.
Output. For each window , the posterior law of : its shape and rate , its mean, standard deviation and coefficient of variation, and chosen quantiles.
The algorithm
CORI-RT(I[1..T], w, τ, a, b)- 1
for t ← 1 to T do Λ[t] ← Σ_{u=1}^{min(t-1, s)} w[u] I[t - u] - 2
for t ← τ + 1 to T do ▷ window t - τ + 1 .. t, starting on day 2 or later - 3
A ← a + Σ_{u=t-τ+1}^{t} I[u] - 4
B ← 1/b + Σ_{u=t-τ+1}^{t} Λ[u] - 5
mean ← A / B, sd ← √A / B - 6
quantiles ← quantiles of Gamma(shape A, rate B) - 7
output (t, A, B, mean, sd, quantiles)
Lines L3 and L4 use prefix sums of and , so each window costs besides the quantiles. The implementation finds a quantile by bisection on the gamma distribution function, which it evaluates through the chi-squared tail: if is gamma with shape and rate , then is chi-squared with degrees of freedom. The prior in the example below has and , 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 , , and the counts
| day | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 10 | 4 | 8 | 9 | 11 | 14 | 15 | 21 | 24 | 16 | 18 | 15 | 13 | |
| 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, . With windows of days and the prior , , the first window is days 2 to 5. There and , so the posterior mean is , the standard deviation is and the 95% credible interval is . The other windows give:
| window | 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, for 25 days and then , seed 20261118 and weekly windows, the estimate for the window that ends on day 30 is with the interval , and for the window that ends on day 55 it is with . The window that ends on day 35 straddles the change and gives . So a window estimate lags a sudden change by up to days.
Correctness
The full proof is in proofs/correctness.md. Because , depends only on the counts before day . So by the chain rule, the probability of the counts in the window, given the earlier counts, is the product of Poisson() masses. As a function of , it is proportional to . Multiplying by the gamma prior density gives , a gamma density with shape and rate . Lines L3 and L4 compute these two numbers with prefix sums, line L5 uses the gamma mean and variance , 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 , with incidence . The weights are non-negative, and . Cases before day 1 are taken as 0, so . Fix a window of days with . The model is: given , the count is Poisson(), and for every . The days before have their own reproduction numbers, which do not involve . The prior on is a gamma law with shape and scale , with density on .
Claim 1 (line L1). The list lam holds .
Proof. For the day with index (0-based, day ), the loop adds for the day steps before, for . These are exactly the terms of whose day is 1 or later; the terms for earlier days are 0 by the convention. The check makes sure that never enters its own .
Claim 2 (the window likelihood). As a function of ,
Proof. By the chain rule, the joint probability of the window counts given the earlier counts is the product over of . Each factor is the Poisson() mass at , and is a fixed number given , because . The factors do not depend on . If the model forces , and the factor is 1 for every , which agrees with the formula.
Claim 3 (the posterior). The posterior of given is the gamma law with shape and rate .
Proof. The probability of the days before does not depend on , by the setting. So by Bayes' theorem, the posterior density is proportional to the prior times the window likelihood of Claim 2:
Since and , this is integrable on , with integral , and the normalized density is the gamma density with shape and rate . This is the conjugate update of a gamma prior by Poisson counts.
Claim 4 (lines L2 to L4). For each from to , the code sets and computes and of Claim 3 for the window .
Proof. The prefix sums satisfy and , by induction on , since each step adds the next term. So , and the same for . The loop starts at , so for every window, and the window has days.
Claim 5 (line L5). The mean is , the standard deviation is , and the coefficient of variation is .
Proof. For a gamma law with shape and rate , , and in the same way , so the variance is . The ratio of the standard deviation to the mean is .
Claim 6 (line L6). gamma_quantile(p, A, B) returns the -quantile of the posterior to within the tolerance.
Proof. If has the gamma law with shape and rate , then has density proportional to , which is the chi-squared law with degrees of freedom. So , which is what gamma_cdf computes with chi2_sf. This function is continuous and strictly increasing on , with and . The first loop doubles hi until , which happens after finitely many steps. Then the invariant holds, since . Each bisection step keeps it, as it moves lo up only when and moves hi down otherwise. So the unique with stays in , and the returned midpoint is within the final interval length of .
Conclusion. Each WindowEstimate holds the exact gamma posterior of 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 is drawn from the prior and the data from the model, the posterior distribution function at the true is uniform.
Complexity
Line L1 costs arithmetic operations, where is the length of the generation interval. A fast convolution would make it , which only helps when is large. The prefix sums take , and each window takes for , , 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 plus a cost per quantile that does not depend on . The extra space is for and the prefix sums. When a new day of data arrives, one more value and one more window cost .
Properties
- Exact under the model. The posterior is exact, not an approximation, for the Poisson renewal model with constant on the window. Simulation-based calibration in the tests confirms it: with drawn from the prior, the posterior distribution function at the true is uniform.
- Scale of the counts. If every count is multiplied by a constant reporting fraction, 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 , so it depends only on the number of cases in the window, plus . About 100 cases in a window give a coefficient of variation near 0.1.
- Uses only the past. The estimate for day uses counts up to day . 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 , because they can infect others, but not in the window sum of , because local transmission did not cause them. Counting them as local makes 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 follow a random walk, and use a particle filter or sequential Monte Carlo for the filtered law of . 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 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 , 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 : for the same growth rate, a longer interval gives a larger (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 when it is far from 1.
- The first entry of . It must be 0. A case cannot infect on the day of its own infection, and a positive would put inside its own . 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 is small, the prior has a large weight, and the estimate is unreliable. Check the coefficient of variation before reading the estimate.
- Window lag. The estimate for the window that ends on day describes the whole window. A sudden change shows up in full only 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 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.
# 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
- Cori et al. 2013, the Poisson renewal likelihood over a window, the gamma posterior, and the EpiEstim software
- 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
- 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
- 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
- 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.
| 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 FC6CRV Edit this page History Report an error Markdown