Skip to content

Conjugate gamma–Poisson estimation of the instantaneous reproduction number ​

Introduction ​

This page estimates the instantaneous reproduction number over windows of days from daily counts of new infections. The counts are simulated and treated as observed in full, except in the section on imported cases, which splits them into local and imported infections. Under a Poisson renewal model with a gamma prior, the posterior of each window is a gamma distribution whose parameters are two sums: of the counts and of the infection pressure []. One call to pressure and one to window_sums therefore give the exact posterior of every window, with no sampler, and one call covers thousands of simulated outbreaks held as strata. The last sections follow [], who show that this posterior is too narrow when counts are overdispersed, and compute their corrected intervals with the same two calls.

The page computes, in order:

  • the gamma posterior of for each week of a simulated outbreak, checked against the simulating values and by its coverage over 2000 replicates;

  • the posteriors for windows of 3, 7 and 14 days;

  • separate and pooled posteriors for three regions, with and without the coupling between them;

  • posteriors under a generation interval that changes by day of infection or by day of the infector's infection;

  • posteriors from local cases and from all cases when some cases are imported;

  • the reproduction number in a fully susceptible population, from a pressure scaled by the susceptible share;

  • the case reproduction number, a weighted sum of the window posteriors;

  • the coverage of the Poisson interval for negative binomial counts, and an exact beta prime posterior for counts whose dispersion is proportional to the pressure;

  • the quasi-Poisson interval and the interval for counts of constant dispersion of [].

Packages used ​

julia
using ComposableRecurrences
using ComposableRecurrences: Primary, Recent, Transform, pressure,
    window_sums
using Distributions: BetaPrime, Gamma, NegativeBinomial, Poisson, logpdf,
    mean, quantile, rate, shape, var
using Random, Statistics
using CairoMakie, AlgebraOfGraphics, DataFramesMeta

CairoMakie.activate!(type = "png", px_per_unit = 2)

Model ​

Let be the number of new infections on day and the probability that the generation interval is days, for  . Incidence follows a renewal equation [] with Poisson counts,

where is the infection pressure on day and the instantaneous reproduction number. The reproduction number is constant over a window of days  , so   for  , with prior distribution

where is the shape and the rate. Given the incidence before day , the pressure is a known number. The likelihood of the counts in the window, each conditional on the counts before it, is then

which is the kernel of a gamma density in . The posterior distribution is therefore

This is the estimator of [], who parameterise the gamma distribution by its shape and its scale . The posterior mean is the ratio of the two parameters. The posterior coefficient of variation is  , which depends on the data only through the number of cases in the window.

Conditions for exactness ​

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 of windows that share no day are therefore independent in the posterior. Windows that overlap each have an exact posterior under their own model, and these posteriors do not form one joint distribution.

The posterior is not exact in the following cases.

  • The generation interval is uncertain: the posterior is then 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 too small in the last windows, and the posterior is biased downwards.

  • The incidence before day 1 is not known: is 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 for every day, where renewal is the Recurrence with kernel and 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 are the counts that the model explains and the multiplier of in their mean. In the model above   and  . The functions below take and as arguments, so each later variation supplies its own. A set of windows is a named tuple of first and last days.

julia
# 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)
    )
end

Distributions.Gamma takes a shape and a scale, so the second argument is . Two more functions tabulate and draw a set of posterior distributions.

julia
# 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),)
    )
end

Check on simulated data ​

Simulation ​

The simulation draws from the model of the first section. A Poisson count with mean is the quantile function of the Poisson distribution at a uniform draw ,

where is the quantile function. The uniform draws are made first, and the recurrence is deterministic given them. The count is a Transform modifier that reads as a TimeVarying parameter.

julia
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   lags and a mean of 3.4 days. The simulation runs for   days from 10 infections on each of the 6 days before day 1. is 1.6 on days 1 to 28, 0.8 on days 29 to 49 and 1.2 on days 50 to 70.

julia
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),)
    )
end

The run has a total of

julia
Int(sum(incidence))
11547

infections.

Posterior against the simulating values ​

The windows are the ten weeks of the run, so is constant within each window as the model assumes. The prior has mean 5 and standard deviation 5, which is   and  , the prior of []. pressure reads the kernel of renewal and ignores its modifiers.

julia
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]])
10×5 DataFrame
RowdayRmeanlowerupper
Int64Float64Float64Float64Float64
171.61.341.091.61
2141.61.511.341.69
3211.61.691.571.81
4281.61.71.631.77
5350.80.790.750.82
6420.80.790.750.83
7490.80.780.730.84
8561.21.181.11.25
9631.21.171.111.24
10701.21.211.151.26

Each row is one week, labelled by its last day, with the posterior mean and the 2.5% and 97.5% posterior quantiles. The number of weeks in which the interval contains the simulating value is

julia
sum(weekly.covered)
9

out of 10.

julia
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 ​

If is drawn from the prior and the data from the model, a 95% posterior interval contains the drawn with probability 0.95. This holds only if the posterior is exact, so it tests the computation. The test uses 2000 replicates of a 10-day run with one window, each replicate with its own from the prior,

The replicates are the strata of one recurrence, so one call simulates them and one call returns their pressures.

julia
# 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 proportion of replicates whose interval contains the drawn , and the second its binomial standard error.

Variations with a gamma posterior ​

The derivation of the first section uses one property of the model. The mean of each explained count is , where is fixed by the earlier counts and by known quantities. Any model with this property has the posterior   . Each variation below states its and and passes them to window_totals.

Window width ​

A window of days that ends on day is    , and its posterior is

Each posterior is exact for the model in which is constant over that window. Sliding windows overlap, so the posteriors of different days are not jointly a posterior distribution.

julia
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 mean width of the 95% interval over the windows of each width is

julia
interval_width(df) = mean(df.upper .- df.lower)
round.(interval_width.(by_width); digits = 2)
(0.29, 0.18, 0.11)

A window that contains a change in estimates a value between the two levels. The proportion of windows whose interval contains the simulating of their last day is

julia
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.

Strata, pooled and coupled ​

With strata   and a coupling , the pressure on stratum mixes the strata,

is fixed by the earlier counts of all strata, so the posterior of each is gamma with   and  . The likelihood is a product over strata, so the are independent in the posterior. If the strata share one reproduction number , its posterior adds the totals over strata,

Both are exact. Three regions with no coupling, the identity, share the above and start from 2, 5 and 20 infections a day.

julia
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 mean width of the 95% interval in the three regions and pooled is

julia
round.(interval_width.(strata_fits); digits = 2)
4-element Vector{Float64}:
 0.31
 0.23
 0.12
 0.1

The interval narrows as the number of cases grows, and the pooled interval is the narrowest. The regions have these numbers of infections in total:

julia
Int.(vec(sum(by_region; dims = 2)))
3-element Vector{Int64}:
  4962
 10202
 29313

With 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.

julia
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)
6×5 DataFrame
Rowregionmeanlowerupperseries
StringFloat64Float64Float64String
1Region 10.710.690.74With K
2Region 21.311.31.33With K
3Region 30.990.971.01With K
4Region 11.311.261.36Without K
5Region 21.311.31.33Without K
6Region 31.31.271.32Without 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 multiplies the pressure that stratum receives, as the gain of a Recurrence does. If instead each infecting stratum has its own , the mean is , a sum over several unknowns, and the likelihood is not a product of gamma kernels.

A generation interval that changes over time ​

The generation interval can depend on the day of the new infection, , or on the day the infector was infected,  :

Both are fixed by the earlier counts when every   is known, so the posterior is gamma with either pressure. A TimeVarying kernel holds one column of for each day and gives the first form, and with Primary() the second. 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.

julia
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 posterior means for the weeks that end on days 49 and 70 are, for the two kernels,

julia
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. 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.

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 of the kernel's calendar, and the run starts on day  .

julia
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]])
10×5 DataFrame
RowdayRmeanlowerupper
Int64Float64Float64Float64Float64
171.61.341.091.61
2141.61.511.341.69
3211.61.691.571.81
4281.61.71.631.77
5350.80.790.760.82
6420.80.790.750.83
7490.80.780.730.84
8561.21.181.11.26
9631.21.181.111.24
10701.21.211.161.26

The window indices count from the first day of the run, so weeks applies unchanged.

Imported cases ​

Let be the number of cases on day that were infected outside the population, and the number infected inside it. Both add to the pressure, and only the local cases are explained by it:

The posterior is gamma with   and  , and it is exact when each case is known to be local or imported. The model places no distribution on . This is the treatment of imported cases of []. 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.

julia
ι = [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,

julia
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 ​

Let multiply the pressure, where is fixed by the earlier counts and by known quantities:

The posterior of is gamma with   and  . The given here is the share of a population of not yet infected, so is the reproduction number in a fully susceptible population. The same holds for any known , such as the effect of a vaccination programme with known coverage and efficacy. In the simulation is a Recent parameter, which reads the sum of the earlier counts. For the estimate, the gain of a Convolution on lags 1 to multiplies the pressure by . is 1.8 on every day and  .

julia
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   the posterior is that of the simulating value 1.8. With   it is that of the effective reproduction number  , which falls as the population is depleted. The figure stops at day 49, after which the run has one more infection.

The multiplier must not depend on . The hazard form of a Depletion has mean  , which is not proportional to , and its posterior is not gamma.

Case reproduction number ​

The case reproduction number of day is the expected number of infections caused by one infection on day [, ]. It is the instantaneous reproduction number summed forward over the generation interval,

where the second form holds for consecutive windows and is the share of the generation interval from day that falls in window . The of consecutive windows are independent gamma variables, so is a weighted sum of independent gamma variables with different rates. That sum is gamma only when one window has all the weight. Its mean and variance are in closed form,

and its quantiles follow from draws of the . The weights are the forward sum, the transpose of the convolution with , applied to the indicator of each window. needs up to day  , so it is defined up to day  .

julia
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]
case_sd = sqrt.((c .^ 2)' * var.(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 . The largest difference between the closed-form standard deviation and that of the 4000 draws is

julia
round(maximum(abs, std(case_draws; dims = 2) .- case_sd); digits = 4)
0.0033

Variations without a gamma posterior ​

In each of the following the mean of a count is not times a quantity fixed by the earlier counts.

  • A reporting delay or a reporting probability: the infections are latent.

  • A reproduction number for each infecting stratum under a coupling: the mean is a sum over several unknowns.

  • 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 not a product of gamma densities.

  • An unknown generation interval.

The page A particle filter and SMC² for a renewal model estimates a model with the first, third and fourth of these.

Count distributions other than the Poisson ​

The gamma posterior is specific to the Poisson distribution. One negative binomial model with known dispersion has a closed-form posterior in another family, the beta prime distribution. A second has a finite mixture of gamma distributions, and a third has no closed form. No model with unknown dispersion has one. This section derives each statement and measures what the Poisson assumption costs when counts are overdispersed.

What the Poisson assumption costs ​

Let   be the conditional mean of and its conditional variance. [] show that the Poisson model understates the standard error of the estimate of by the factor

whatever the form of the relationship between and . A nominal 95% interval then has coverage   , with the standard normal distribution function. They derive this for the maximum likelihood estimate and report that the gamma posterior behaves alike unless incidence is very low. They also note that the conjugate approach is difficult to extend, and fit quasi-Poisson and negative binomial models by maximum likelihood. A quasi-Poisson model specifies a mean and a variance and no distribution, so it has no posterior.

Dispersion proportional to the pressure ​

Let the count be negative binomial with mean and size , with known:

This is the count when each unit of pressure causes a Poisson number of infections whose rate is gamma distributed with mean and shape . With the whole generation interval on one lag it is the branching process with negative binomial offspring that [] call the generation model. The probability does not depend on , so the likelihood of a window is

the kernel of a beta density in . A beta prior on is a beta prime prior on   , and the posterior is in the same family:

[] give this posterior for that model, as a beta distribution for  . The derivation above shows that it holds for any known generation interval when the size is proportional to the pressure. The posterior uses the two window totals of the gamma posterior, and it tends to    as  . Its variance is that of the gamma posterior multiplied by approximately  , the ratio of this model.

julia
# The posterior of each window for counts whose size is `κ` times the
# pressure, from the totals and the parameters of the limiting gamma prior.
function beta_prime_posterior(prior, totals, κ)
    return κ .* BetaPrime.(
        shape(prior) .+ totals.cases,
        κ .* (rate(prior) .+ totals.pressure)
    )
end

# A count with mean `v` and size `κ v / R`, drawn at the uniform `u`.
function nb_count(κ, R)
    return function (v, u)
        v > 0 || return 0.0
        count = NegativeBinomial(κ * v / R, κ / (κ + R))
        return float(quantile(count, u))
    end
end

The test simulates 2000 replicates of 21 days with   and  , so  , from 20 infections a day. Each replicate has one window, days 8 to 21.

julia
κ, R_over = 0.5, 1.5
draw = nb_count(κ, R_over)
dispersed = Recurrence(
    gi; modifiers = (counts(rand(Xoshiro(5), n, 21); draw),)
)
seeds_over = fill(20.0, n, L)
over = dispersed(fill(R_over, n, 21); history = seeds_over)
Λ_over = pressure(dispersed, over; history = seeds_over)
fortnight = (starts = [8], stops = [21])
totals_over = window_totals(over, Λ_over, fortnight)
as_poisson = vec(gamma_posterior(prior, totals_over))
exact = vec(beta_prime_posterior(prior, totals_over, κ))
coverages = (
    poisson = mean(covers(as_poisson, R_over)),
    beta_prime = mean(covers(exact, R_over)),
)
round.(values(coverages); digits = 3)
(0.677, 0.951)

The first number is the proportion of replicates in which the 95% interval of the gamma posterior contains 1.5, and the second that of the beta prime posterior. The binomial standard errors are 0.010 and 0.005. The coverage that [] predict for   is    . The median ratio of the widths of the two intervals is

julia
interval(d) = quantile(d, 0.975) - quantile(d, 0.025)
round(median(interval.(exact) ./ interval.(as_poisson)); digits = 2)
2.0

against  . The beta prime posterior is checked against the model directly for the first replicate. The log posterior density less the log likelihood and the log prior density is the same at every , to the difference shown.

julia
window = 8:21
log_likelihood(r) = sum(
    logpdf(NegativeBinomial(κ * λ, κ / (κ + r)), y)
        for (λ, y) in zip(Λ_over[1, window], over[1, window])
)
prior_over = κ * BetaPrime(shape(prior), κ * rate(prior))
grid = 0.5:0.25:3
gap = logpdf.(exact[1], grid) .- log_likelihood.(grid) .-
    logpdf.(prior_over, grid)
maximum(abs, gap .- first(gap))
7.958078640513122e-13

Other negative binomial models ​

If the size is proportional to the mean, with known, the variance is   with a ratio that does not depend on . This is the model that [] call NegBin-L. Its likelihood is

with   . The double product is a polynomial in with non-negative coefficients and degree . With a gamma prior the posterior is therefore a finite mixture of the distributions    over . It is exact, and it is not a gamma distribution: the number of components grows with the number of cases in the window.

If the size is a constant , the model that [] call NegBin-Q, the likelihood is

Each day contributes a factor with its own , and no prior family is closed under multiplication by these factors unless is constant.

With an unknown dispersion, the posterior of is a mixture of the posteriors above over the posterior of the dispersion, which has no closed form in any of the three models. The negative binomial distribution also arises within the Poisson model: the predictive distribution of a count, with integrated over its gamma posterior, is negative binomial. That is a property of the gamma posterior and does not make the model overdispersed, since the counts remain Poisson given .

Intervals that allow for overdispersion ​

[] replace the Poisson interval by two intervals that hold when counts are overdispersed. Both are computed below from the same window sums, on 2000 replicates of 21 days with one window, days 8 to 21. Each interval is a Wald interval, the estimate plus or minus 1.96 standard errors.

Quasi-Poisson ​

A quasi-Poisson model keeps the mean   and sets the variance to . The estimate of is the Poisson maximum likelihood estimate, and its standard error is the Poisson one multiplied by :

where is the number of days in the window and the Pearson estimate of the dispersion []. The replicates are those of the beta prime posterior above, with  .

julia
# The Poisson maximum likelihood estimate of each window and its
# standard error.
function poisson_fit(y, E, w)
    totals = window_totals(y, E, w)
    estimate = totals.cases ./ totals.pressure
    return (; estimate, se = estimate ./ sqrt.(totals.cases))
end

# The Pearson estimate of the dispersion in each window, for counts `y`
# with mean `estimate` times `E`.
function pearson_dispersion(y, E, estimate, w)
    μ = estimate .* E
    days = w.stops .- w.starts .+ 1
    return window_sums((y .- μ) .^ 2 ./ μ, w.starts, w.stops) ./ (days' .- 1)
end

# The share of Wald intervals, `estimate ± 1.96 se`, that contain `value`.
function wald_coverage(estimate, se, value)
    return mean(abs.(estimate .- value) .<= 1.96 .* se)
end

The mean of the estimated dispersions over the replicates is

julia
poisson_over = poisson_fit(over, Λ_over, fortnight)
ϕ_over = pearson_dispersion(over, Λ_over, poisson_over.estimate, fortnight)
round(mean(ϕ_over); digits = 2)
4.03

and the coverage of the Poisson and quasi-Poisson intervals is

julia
quasi = (
    poisson = wald_coverage(poisson_over.estimate, poisson_over.se, R_over),
    quasi_poisson = wald_coverage(
        poisson_over.estimate, poisson_over.se .* sqrt.(ϕ_over), R_over
    ),
)
round.(values(quasi); digits = 3)
(0.674, 0.928)

The Poisson coverage is close to the 0.673 that the formula of [] gives for  . The quasi-Poisson coverage is below 0.95 because is estimated from the 14 days of each window.

Constant dispersion ​

If each count is negative binomial with mean and a constant size , the variance is  , the model NegBin-Q of the previous section. Its maximum likelihood estimate has no closed form. When the overdispersion is strong, [] approximate it by the mean of the daily ratios, each day weighted equally:

The ratios are the counts divided by the pressure, and their mean over each window is one call to window_sums. The test uses   and   with known, from 20 infections a day.

julia
# A count with mean `v` and constant size `ψ`, drawn at the uniform `u`.
function constant_size_count(ψ)
    return function (v, u)
        v > 0 || return 0.0
        return float(quantile(NegativeBinomial(ψ, ψ / (ψ + v)), u))
    end
end

# The mean of the daily ratios `y ./ E` in each window and its approximate
# standard error for counts of size `ψ`.
function ratio_fit(y, E, w, ψ)
    days = (w.stops .- w.starts .+ 1)'
    estimate = window_sums(y ./ E, w.starts, w.stops) ./ days
    return (; estimate, se = estimate ./ sqrt.(ψ .* days))
end

The coverage of the Poisson interval and of the interval from the daily ratios is

julia
ψ, R_q = 2.0, 1.5
constant = Recurrence(
    gi; modifiers = (
        counts(rand(Xoshiro(6), n, 21); draw = constant_size_count(ψ)),
    )
)
y_q = constant(fill(R_q, n, 21); history = seeds_over)
Λ_q = pressure(constant, y_q; history = seeds_over)
poisson_q = poisson_fit(y_q, Λ_q, fortnight)
ratio_q = ratio_fit(y_q, Λ_q, fortnight, ψ)
constant_coverage = (
    poisson = wald_coverage(poisson_q.estimate, poisson_q.se, R_q),
    ratio = wald_coverage(ratio_q.estimate, ratio_q.se, R_q),
)
round.(values(constant_coverage); digits = 3)
(0.156, 0.932)

The median ratio of the two standard errors is

julia
round(median(ratio_q.se ./ poisson_q.se); digits = 1)
7.9

With strong overdispersion the variance is close to , so each daily ratio has a variance close to whatever the pressure. The ratio estimate therefore weights each day equally, where the Poisson estimate weights each day by its pressure.

References ​

  1. C. Fraser. Estimating individual and household reproduction numbers in an emerging epidemic. PLoS ONE 2, e758 (2007).

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

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

  4. B. Němcová, I. H. Goldstein, J. Sebastian, V. M. Minin and J. Bracher. Unjustified Poisson assumptions lead to overconfident estimates of the effective reproductive number. Epidemiology and Infection 154, e79 (2026).

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

  6. K. D. Johnson, M. Beiglböck, M. Eder, A. Grass, J. Hermisson, G. Pammer, J. Polechová, D. Toneian and B. Wölfl. Disease momentum: Estimating the reproduction number in the presence of superspreading. Infectious Disease Modelling 6, 706–728 (2021).

  7. P. McCullagh and J. A. Nelder. Generalized Linear Models. 2 Edition (Springer US, 1989).