Conjugate gamma–Poisson estimation of the instantaneous reproduction number
Introduction
This page is for readers who want the instantaneous reproduction number pressure and one to window_sums give the posterior of every window, and one call covers thousands of simulated outbreaks held as strata.
Conjugate updates are one way to fit these models. The operators are ordinary differentiable Julia functions, so any fitting approach works with them, including particle filters, optimisation and MCMC with Turing.jl or a similar package. For Bayesian fitting we recommend Wren.jl.
The page first estimates
It assumes you have read Three towns, step by step and The reproduction number from a run, which introduces the pressure.
Packages used
using ComposableRecurrences
using ComposableRecurrences: Primary, Recent, Transform, pressure,
window_sums
using Distributions: Gamma, Poisson, mean, quantile, rate, shape, var
using Random, Statistics
using CairoMakie, AlgebraOfGraphics, DataFramesMeta
CairoMakie.activate!(type = "png", px_per_unit = 2)Model
Let
where
The posterior mean is the ratio of the two parameters.
Why the posterior is gamma
Given the incidence before day
which is the kernel of a gamma density in
When the posterior is exact
The posterior is exact under four conditions.
Each count is Poisson given the earlier counts, with mean
. The generation interval
is known and has no mass at lag 0. The incidence is observed completely and without delay on every day up to
, including the days before day 1. is constant within the window, and its prior distribution is gamma.
The likelihood conditions on the incidence before the window and assumes nothing about how that incidence arose. The joint likelihood of all days is the product of the window likelihoods. With independent priors, the
The posterior is not exact in the following cases.
When the generation interval is uncertain, the posterior is a mixture of gamma distributions over the distribution of
. Cases are reported with a delay or with a probability below one.
then depends on infections that are not observed. The most recent counts are incomplete.
is then too small in the last windows, and the posterior is biased downwards. The incidence before day 1 is not known.
is then too small on the first days, and the posterior is biased upwards.
Computation
The computation has three steps, each one function call. pressure(renewal, incidence; history) returns renewal is the Recurrence with kernel history holds the incidence before day 1. window_sums(x, starts, stops) returns the sum of x over each window. The posterior parameters are then
where
# Windows of `width` days that end on each day of `days` in turn.
function sliding(width, days)
stops = (first(days) + width - 1):last(days)
return (starts = stops .- (width - 1), stops = stops)
end
# Windows of `width` days that follow one another over `days`.
function consecutive(width, days)
starts = first(days):width:(last(days) - width + 1)
return (starts = starts, stops = starts .+ (width - 1))
end
# The sums of the counts `y` and of the multipliers `E` over each window.
function window_totals(y, E, w)
return (
cases = window_sums(y, w.starts, w.stops),
pressure = window_sums(E, w.starts, w.stops),
)
end
# The gamma posterior of each window, from a gamma prior and the totals.
function gamma_posterior(prior, totals)
return Gamma.(
shape(prior) .+ totals.cases,
1 ./ (rate(prior) .+ totals.pressure)
)
endDistributions.Gamma takes a shape and a scale, so the second argument is
# The mean and central 95% interval of each posterior, one for each day.
function summarise(posterior, days; series = "Posterior")
return DataFrame(
day = collect(days), mean = mean.(posterior),
lower = quantile.(posterior, 0.025),
upper = quantile.(posterior, 0.975), series = series
)
end
# A table with its floating point columns rounded to two digits.
function rounded(df)
cols = names(df, AbstractFloat)
return transform(df, cols .=> ByRow(x -> round(x; digits = 2)) .=> cols)
end
# A line and a band by day for each series, with `truth` dashed in black.
function plot_posterior(df, truth; col = nothing, kwargs...)
order = sorter(unique(df.series))
by = col === nothing ? mapping(color = :series => order => "") :
mapping(color = :series => order => "", col = col => order)
estimate = data(df) * by * (
mapping(:day, :lower, :upper) * visual(Band, alpha = 0.3) +
mapping(:day, :mean) * visual(Lines, linewidth = 2)
)
reference = data(truth) * mapping(:day, :R) *
visual(Lines, color = :black, linestyle = :dash)
axis = (; xlabel = "Day", ylabel = "Reproduction number", kwargs...)
return draw(
estimate + reference; axis, legend = (show = false,),
figure = (size = (640, 300),)
)
endCheck on simulated data
Simulation
The simulation draws from the model of the first section. Each count is the Poisson quantile at a uniform draw
where Transform modifier that reads TimeVarying parameter.
poisson_count(v, u) = float(quantile(Poisson(v), u))
per_day(u::AbstractVector) = TimeVarying(u)
per_day(u::AbstractMatrix) = TimeVarying(PerStratum(u))
# A modifier that replaces each value by a count drawn from it with `u`.
counts(u; draw = poisson_count) = Transform(draw, per_day(u))The generation interval has
gi = [0.05, 0.2, 0.3, 0.25, 0.12, 0.08]
L = length(gi)
T = 70
R = [t <= 28 ? 1.6 : t <= 49 ? 0.8 : 1.2 for t in 1:T]
seed = fill(10.0, L)
u = rand(Xoshiro(1), T)
renewal = Recurrence(gi; modifiers = (counts(u),))
incidence = renewal(R; history = seed)
truth = DataFrame(day = 1:T, R = R)
@chain DataFrame(day = 1:T, incidence = incidence) begin
data(_) * mapping(:day, :incidence) * visual(Scatter, color = :black)
draw(
_; axis = (xlabel = "Day", ylabel = "Incidence"),
figure = (size = (640, 300),)
)
endIncidence grows, falls after day 28 and grows again after day 49, following the three levels of
Posterior against the simulating values
The windows are the ten weeks of the run, so pressure reads the kernel of renewal and ignores its modifiers.
prior = Gamma(1, 5)
weeks = consecutive(7, 1:T)
Λ = pressure(renewal, incidence; history = seed)
posterior = gamma_posterior(prior, window_totals(incidence, Λ, weeks))
weekly = summarise(posterior, weeks.stops)
weekly.R = R[weeks.stops]
weekly.covered = weekly.lower .<= weekly.R .<= weekly.upper
rounded(weekly[:, [:day, :R, :mean, :lower, :upper]])| Row | day | R | mean | lower | upper |
|---|---|---|---|---|---|
| Int64 | Float64 | Float64 | Float64 | Float64 | |
| 1 | 7 | 1.6 | 1.34 | 1.09 | 1.61 |
| 2 | 14 | 1.6 | 1.51 | 1.34 | 1.69 |
| 3 | 21 | 1.6 | 1.69 | 1.57 | 1.81 |
| 4 | 28 | 1.6 | 1.7 | 1.63 | 1.77 |
| 5 | 35 | 0.8 | 0.79 | 0.75 | 0.82 |
| 6 | 42 | 0.8 | 0.79 | 0.75 | 0.83 |
| 7 | 49 | 0.8 | 0.78 | 0.73 | 0.84 |
| 8 | 56 | 1.2 | 1.18 | 1.1 | 1.25 |
| 9 | 63 | 1.2 | 1.17 | 1.11 | 1.24 |
| 10 | 70 | 1.2 | 1.21 | 1.15 | 1.26 |
Each row is one week, labelled by its last day, with the posterior mean and the 2.5% and 97.5% posterior quantiles.
week_of_day = repeat(1:length(posterior); inner = 7)
plot_posterior(summarise(posterior[week_of_day], 1:T), truth)The line is the posterior mean, the band the central 95% posterior interval and the dashed line the simulating
Calibration
Before using the estimate on data, you can check the whole set-up by simulation. Draw
If the posterior is exact, the share is 0.95. The replicates are the strata of one recurrence, so one call simulates 2000 runs of 10 days and one call returns their pressures.
# Whether the central interval of each posterior contains `value`.
function covers(posterior, value; level = 0.95)
lower = quantile.(posterior, (1 - level) / 2)
upper = quantile.(posterior, (1 + level) / 2)
return lower .<= value .<= upper
end
n = 2000
rng = Xoshiro(2)
R_drawn = rand(rng, prior, n)
replicates = Recurrence(gi; modifiers = (counts(rand(rng, n, 10)),))
seeds = repeat(seed', n)
runs = replicates(repeat(R_drawn, 1, 10); history = seeds)
Λ_runs = pressure(replicates, runs; history = seeds)
whole = (starts = [1], stops = [10])
fits = vec(gamma_posterior(prior, window_totals(runs, Λ_runs, whole)))
coverage = mean(covers(fits, R_drawn))
standard_error = sqrt(coverage * (1 - coverage) / n)
round.((coverage, standard_error); digits = 3)(0.952, 0.005)The first number is the share of replicates whose interval contains the drawn
Variations with a gamma posterior
Real data rarely match the model of the first section exactly. The posterior stays gamma whenever the mean of each explained count window_totals.
Window width
The width of the window trades noise against delay. A short window follows changes in
widths = (3, 7, 14)
by_width = map(widths) do k
w = sliding(k, 1:T)
fit = gamma_posterior(prior, window_totals(incidence, Λ, w))
summarise(fit, w.stops; series = "$k days")
end
plot_posterior(reduce(vcat, by_width), truth; col = :series)The 14-day windows lag behind each change in
interval_width(df) = mean(df.upper .- df.lower)
round.(interval_width.(by_width); digits = 2)(0.29, 0.18, 0.11)and the share of windows whose interval contains the simulating
share_covered(df) = mean(df.lower .<= R[df.day] .<= df.upper)
round.(share_covered.(by_width); digits = 2)(0.82, 0.75, 0.53)Wider windows give narrower intervals and cover the simulating value less often, since more of them contain a change.
Sliding windows and the joint posterior
A window of
Each posterior is exact for the model in which
Strata, pooled and coupled
Data often come by region. Each region can have its own
The posterior of each region's
The pressure under a coupling
With strata
Both are exact.
region_names = ["Region 1", "Region 2", "Region 3"]
region_seeds = [2.0, 5.0, 20.0] .* ones(1, L)
U = rand(Xoshiro(3), 3, T)
regions = Recurrence(gi; modifiers = (counts(U),))
by_region = regions(repeat(R', 3); history = region_seeds)
Λ_regions = pressure(regions, by_region; history = region_seeds)
totals = window_totals(by_region, Λ_regions, weeks)
separate = gamma_posterior(prior, totals)
# The totals of a set of strata added over the strata.
pool(totals) = map(x -> vec(sum(x; dims = 1)), totals)
pooled = gamma_posterior(prior, pool(totals))
strata_fits = [
summarise(fit[week_of_day], 1:T; series = name) for (fit, name) in
zip((eachrow(separate)..., pooled), (region_names..., "Pooled"))
]
plot_posterior(reduce(vcat, strata_fits), truth; col = :series)The interval narrows as the number of cases grows, and the pooled interval is the narrowest. The mean width of the 95% interval in the three regions and pooled is
round.(interval_width.(strata_fits); digits = 2)4-element Vector{Float64}:
0.31
0.23
0.12
0.1from these total numbers of infections in each region:
Int.(vec(sum(by_region; dims = 2)))3-element Vector{Int64}:
4962
10202
29313With a coupling, the same two calls apply, since pressure applies the coupling of the recurrence it is given. In the next run region 1 receives 10% of its pressure from region 2, and region 3 receives 20% of its pressure from region 2. The reproduction numbers are constant at 0.7, 1.3 and 1.0, and there is one window of 70 days.
K = [0.9 0.1 0.0; 0.0 1.0 0.0; 0.0 0.2 0.8]
R_regions = [0.7, 1.3, 1.0]
coupled = Recurrence(gi; coupling = K, modifiers = (counts(U),))
mixed = coupled(repeat(R_regions, 1, T); history = region_seeds)
all_days = (starts = [1], stops = [T])
# The posterior of each stratum's `R` over one window, as rows of a table.
function one_window(operator, y; history, label)
Λ = pressure(operator, y; history)
fit = vec(gamma_posterior(prior, window_totals(y, Λ, all_days)))
df = summarise(fit, region_names; series = label)
return rename(df, :day => :region)
end
coupling_table = vcat(
one_window(coupled, mixed; history = region_seeds, label = "With K"),
one_window(
Recurrence(gi), mixed; history = region_seeds, label = "Without K"
)
)
rounded(coupling_table)| Row | region | mean | lower | upper | series |
|---|---|---|---|---|---|
| String | Float64 | Float64 | Float64 | String | |
| 1 | Region 1 | 0.71 | 0.69 | 0.74 | With K |
| 2 | Region 2 | 1.31 | 1.3 | 1.33 | With K |
| 3 | Region 3 | 0.99 | 0.97 | 1.01 | With K |
| 4 | Region 1 | 1.31 | 1.26 | 1.36 | Without K |
| 5 | Region 2 | 1.31 | 1.3 | 1.33 | Without K |
| 6 | Region 3 | 1.3 | 1.27 | 1.32 | Without K |
With the coupling, the posterior means are close to the simulating values. Without it, the infections that regions 1 and 3 receive from region 2 are attributed to their own transmission, and both estimates are near 1.3.
The gamma posterior requires that Recurrence does. A separate
A generation interval that changes over time
The generation interval can change during an outbreak, for example as isolation shortens it. It can depend on the day of the new infection, TimeVarying kernel holds one column of Primary() the second.
The two pressures
In the next run the generation interval shortens from a mean of 3.4 days to a mean of 2.5 days for infections from day 29. The estimate with the changing kernel is set against one that keeps the first kernel throughout.
short = [0.25, 0.35, 0.2, 0.12, 0.05, 0.03]
G = reduce(hcat, (t <= 28 ? gi : short for t in 1:T))
changing = Recurrence(TimeVarying(G); modifiers = (counts(u),))
shortened = changing(R; history = seed)
week = sliding(7, 1:T)
gi_fits = map(
(changing, Recurrence(gi)), ("g by day", "g fixed at its first value")
) do operator, label
Λ_g = pressure(operator, shortened; history = seed)
fit = gamma_posterior(prior, window_totals(shortened, Λ_g, week))
summarise(fit, week.stops; series = label)
end
plot_posterior(reduce(vcat, gi_fits), truth; col = :series)The fixed kernel is too long after day 28, which moves the estimate away from 1: down while incidence falls and up while it grows. The posterior means for the weeks that end on days 49 and 70 are, for the two kernels,
at_days(df, days) = round.(df.mean[indexin(days, df.day)]; digits = 2)
at_days.(gi_fits, Ref([49, 70]))([0.78, 1.21], [0.7, 1.31])against simulating values of 0.8 and 1.2.
A cohort kernel needs a column for the day of every infector, including those in the history. The history is therefore placed on days 1 to
G_cohort = reduce(hcat, (t <= L + 28 ? gi : short for t in 1:(L + T)))
u_cohort = vcat(zeros(L), u)
cohorts = Recurrence(
TimeVarying(G_cohort, Primary()); modifiers = (counts(u_cohort),)
)
R_cohort = vcat(ones(L), R)
by_cohort = cohorts(R_cohort; history = seed, start = L + 1)
Λ_cohort = pressure(cohorts, by_cohort; history = seed, start = L + 1)
cohort_fit = gamma_posterior(
prior, window_totals(by_cohort, Λ_cohort, weeks)
)
cohort_table = summarise(cohort_fit, weeks.stops)
cohort_table.R = R[weeks.stops]
rounded(cohort_table[:, [:day, :R, :mean, :lower, :upper]])| Row | day | R | mean | lower | upper |
|---|---|---|---|---|---|
| Int64 | Float64 | Float64 | Float64 | Float64 | |
| 1 | 7 | 1.6 | 1.34 | 1.09 | 1.61 |
| 2 | 14 | 1.6 | 1.51 | 1.34 | 1.69 |
| 3 | 21 | 1.6 | 1.69 | 1.57 | 1.81 |
| 4 | 28 | 1.6 | 1.7 | 1.63 | 1.77 |
| 5 | 35 | 0.8 | 0.79 | 0.76 | 0.82 |
| 6 | 42 | 0.8 | 0.79 | 0.75 | 0.83 |
| 7 | 49 | 0.8 | 0.78 | 0.73 | 0.84 |
| 8 | 56 | 1.2 | 1.18 | 1.1 | 1.26 |
| 9 | 63 | 1.2 | 1.18 | 1.11 | 1.24 |
| 10 | 70 | 1.2 | 1.21 | 1.16 | 1.26 |
The window indices count from the first day of the run, so weeks applies unchanged.
Imported cases
Cases infected outside the population add to the pressure but are not caused by it. Counting them as local overstates
The model with imports
The model places no distribution on
In the simulation the imports are a Transform(+, ι) after the count, so they are added to the local cases and enter the pressure of later days. Here 15 cases a day are imported on days 29 to 49.
ι = [29 <= t <= 49 ? 15.0 : 0.0 for t in 1:T]
imports = Transform(+, TimeVarying(ι))
open_population = Recurrence(gi; modifiers = (counts(u), imports))
all_cases = open_population(R; history = seed)
Λ_open = pressure(open_population, all_cases; history = seed)
import_fits = map(
(all_cases .- ι, all_cases), ("Local cases", "All cases")
) do y, label
fit = gamma_posterior(prior, window_totals(y, Λ_open, weeks))
summarise(fit[week_of_day], 1:T; series = label)
end
plot_posterior(reduce(vcat, import_fits), truth; col = :series)Over days 29 to 49 the mean of the three weekly posterior means is, for local cases and for all cases,
mean_over(df, days) = round(mean(df.mean[days]); digits = 2)
mean_over.(import_fits, Ref(29:49))(0.79, 0.85)against a simulating value of 0.8. Counting the imports as local attributes them to transmission and raises the estimate.
A known multiplier of the pressure
A known multiplier
The model with a multiplier
Depletion has mean
In the simulation Recent parameter, which reads the sum of the earlier counts. For the estimate, the gain of a Convolution on lags 1 to
N = 5000.0
susceptible_share = 1 - Recent(L + T) / N
depleting = Recurrence(
gi; modifiers = (Transform(*, susceptible_share), counts(u))
)
outbreak = depleting(fill(1.8, T); history = seed)
earlier = Convolution(ones(L + T); lags = 1:(L + T))
m = 1 .- earlier(outbreak; history = seed) ./ N
exposure = Convolution(gi; lags = 1:L)(outbreak; gain = m, history = seed)
Λ_outbreak = pressure(depleting, outbreak; history = seed)
days = 1:49
depletion_fits = map(
(exposure, Λ_outbreak), ("E = m Λ", "E = Λ")
) do E, label
fit = gamma_posterior(prior, window_totals(outbreak, E, weeks))
summarise(fit[week_of_day[days]], days; series = label)
end
plot_posterior(
reduce(vcat, depletion_fits), DataFrame(day = days, R = 1.8);
col = :series
)With
Case reproduction number
The case reproduction number of day
Its mean, variance and quantiles
where the second form holds for consecutive windows and
and its quantiles follow from draws of the
forward = Convolution(gi; lags = 1:L)'
indicator = [a <= t <= b for (a, b) in zip(weeks.starts, weeks.stops), t in 1:T]
c = forward(float.(indicator))
case_days = 1:(T - L)
case_mean = (c' * mean.(posterior))[case_days]
draws = reduce(hcat, rand.(Xoshiro(4), posterior, 4000))'
case_draws = (c' * draws)[case_days, :]
case = DataFrame(
day = case_days, mean = case_mean,
lower = quantile.(eachrow(case_draws), 0.025),
upper = quantile.(eachrow(case_draws), 0.975), series = "Case"
)
case_truth = DataFrame(day = case_days, R = forward(R)[case_days])
plot_posterior(case, case_truth)The dashed line is the forward sum of the simulating
Variations without a gamma posterior
In each of the following the mean of a count is not
With a reporting delay or a reporting probability, the infections are latent.
With a reproduction number for each infecting stratum under a coupling, the mean is a sum over several unknowns.
With depletion by a hazard, the mean is not linear in
. A prior that links the
of different windows, such as a random walk on . The joint prior is then not a product of gamma densities. An unknown generation interval.
These need another fitting approach. Particle filtering of a renewal model with LowLevelParticleFilters.jl estimates a model with the first and third of these.
Next steps
The gamma posterior assumes Poisson counts. Real counts often vary more than that, and the intervals above are then too narrow. Overdispersed counts widens them with the same two window totals.
References
C. Fraser. Estimating individual and household reproduction numbers in an emerging epidemic. PLoS ONE 2, e758 (2007).
A. Cori, N. M. Ferguson, C. Fraser and S. Cauchemez. A new framework and software to estimate time-varying reproduction numbers during epidemics. American Journal of Epidemiology 178, 1505–1512 (2013).
J. Wallinga and P. Teunis. Different epidemic curves for severe acute respiratory syndrome reveal similar impacts of control measures. American Journal of Epidemiology 160, 509–516 (2004).
R. N. Thompson, J. E. Stockwin, R. D. van Gaalen, J. A. Polonsky, Z. N. Kamvar, P. A. Demarsh, E. Dahlqwist, S. Li, E. Miguel, T. Jombart, J. Lessler, S. Cauchemez and A. Cori. Improved inference of time-varying reproduction numbers during infectious disease outbreaks. Epidemics 29, 100356 (2019).