Skip to content

Renewal model with negative-binomial reporting ​

The renewal equation expresses new infections as a function of past infections weighted by the generation interval, scaled by a time-varying reproduction number [1]. Mishra et al. [2] showed that this construction follows from an age-dependent branching process and pairs with a negative-binomial observation model to give a Bayesian hierarchical model for reported case counts.

This tutorial builds that model from two composed parts and fits it to the test-confirmed COVID-19 cases from South Korea that Mishra et al. [2] analysed. The parts are a Renewal infection process carrying an autoregressive latent process for , and a NegativeBinomialError observation model. The latent process is folded into the renewal model rather than supplied as a separate top-level component, because the reproduction number is the renewal model's own parameter process.

The model ​

is the discretised generation interval, the autoregressive damping, the innovation standard deviation, and the observation overdispersion.

Components ​

The latent process is a second-order autoregressive model on with a HierarchicalNormal innovation term, matching Mishra et al. [2]. Strong autocorrelation in the reproduction number is encoded by a first damping prior concentrated near one,   on , with a weaker second lag.

julia
using ComposableTuringIDModels, Distributions, Random, Turing, Mooncake
using ADTypes: AutoMooncake
Random.seed!(1234)

latent = AR(
    damp = [truncated(Normal(0.8, 0.05), 0, 1),
        truncated(Normal(0.1, 0.05), 0, 1)],
    init = [Normal(0.0, 0.2), Normal(0.0, 0.2)],
    ϵ_t = HierarchicalNormal(std = HalfNormal(0.1)))
AR
└─ ϵ_t: HierarchicalNormal

The infection process needs a discrete generation interval. Renewal takes a continuous distribution and discretises it with double interval censoring [9], using CensoredDistributions.jl. Following Mishra et al. [2] we use a serial interval as a proxy for the generation interval. Renewal is the only infection model that carries a generation interval, because it is the only one that uses one. It couples that interval to the latent process in its rt slot and a prior for the initial infections.

julia
renewal = Renewal(; generation_time = Gamma(6.5, 0.62),
    rt = latent, initialisation = Normal(log(1.0), 0.1))
renewal.gen_int
8-element Vector{Float64}:
 0.026663134095601098
 0.14059778064943768
 0.2502660305615845
 0.24789569560506872
 0.1731751163417783
 0.09635404000022221
 0.045734375752163825
 0.01931382699414364

The stored gen_int is a probability vector, the continuous serial interval binned into daily weights that sum to one. Double interval censoring is not the same as evaluating the continuous density at integer days. It accounts for both the primary and secondary events falling anywhere within their days [9]. The lag-0 bin is dropped and the weights renormalised over the days kept, so the discrete interval is a little shorter and a little tighter than the behind it.

julia
using Statistics
lags = 1:length(renewal.gen_int)
discrete_mean = sum(lags .* renewal.gen_int)
discrete_sd = sqrt(sum((lags .- discrete_mean) .^ 2 .* renewal.gen_int))
serial_interval = Gamma(6.5, 0.62)
(discrete = round.((discrete_mean, discrete_sd), digits = 2),
    continuous = round.((mean(serial_interval), std(serial_interval)), digits = 2))
(discrete = (3.97, 1.53), continuous = (4.03, 1.58))

The infection process in isolation ​

The renewal model is a model in its own right, so it can be exercised without an observation model. Pinning its reproduction-number process to a known trajectory isolates the contribution of the renewal equation. With the latent folded in, that means building a renewal model whose rt slot is a deterministic FixedIntercept latent, giving a constant , and fixing the initial-infections parameter. The same as_turing_model call that composes into the full model then runs the infection process standalone, returning its infections I_t and the internal latent draw Z_t.

julia
fixed_logR = log(1.4)
renewal_fixed = Renewal(; generation_time = renewal.gen_int,
    rt = FixedIntercept(fixed_logR), initialisation = Normal())
demo = fix(as_turing_model(renewal_fixed, 60), (init_incidence = 0.0,))()
(constant_Rt = round(exp(first(demo.Z_t)), digits = 2),
    grows = demo.I_t[end] > demo.I_t[1])
(constant_Rt = 1.4, grows = true)

A constant   grows incidence. A path that declined through zero would instead produce the textbook turn-over, with incidence growing, decelerating as  , and falling once  . Driving the renewal model with a richer fixed path means swapping the FixedIntercept latent for a deterministic latent of the desired shape.

Reported cases are overdispersed counts of the latent infections. The prior is placed on the cluster factor , which is roughly the coefficient of variation of the observation noise and so easier to reason about a priori.

julia
obs = NegativeBinomialError(cluster_factor = HalfNormal(0.1))

The renewal infection process already carries the latent process, so IDModel needs only it and the observation model.

julia
model = IDModel(renewal, obs)
IDModel
├─ infection: Renewal
│  └─ rt: AR
│     └─ ϵ_t: HierarchicalNormal
└─ observation: NegativeBinomialError

The composed model is also a prior simulator. Passing missing observations makes as_turing_model return generated quantities instead of conditioning on data: the reported cases generated_y_t, the latent infections I_t, and the latent process Z_t. Here we go straight to real data.

The data ​

Mishra et al. [2] fit this model to daily test-confirmed COVID-19 cases in South Korea over the first wave of 2020. The series is stored with the docs and read with CSV and DataFrames.

julia
using CSV, DataFrames
datapath = joinpath(pkgdir(ComposableTuringIDModels),
    "docs", "src", "tutorials", "data", "south_korea_data.csv")
south_korea = CSV.read(datapath, DataFrame)
first(south_korea, 5)
5×4 DataFrame
RowColumn1datecases_newdeaths_new
Int64DateInt64Int64
112019-12-3100
222020-01-0100
332020-01-0200
442020-01-0300
552020-01-0400

We fit the growth-and-decline window of the first wave, matching the span used by Mishra et al. [2], and take the reported cases over it as the observed series.

julia
tspan = (45, 80)
y_obs = south_korea.cases_new[first(tspan):last(tspan)]
n = length(y_obs)
(n = n, total_cases = sum(y_obs),
    from = south_korea.date[first(tspan)], to = south_korea.date[last(tspan)])
(n = 36, total_cases = 8537, from = Dates.Date("2020-02-13"), to = Dates.Date("2020-03-19"))

Fit ​

Conditioning on the observed counts and sampling with NUTS recovers the posterior. We draw two chains in parallel with MCMCThreads() so the posterior is well resolved and the cross-chain diagnostic is available. The slightly raised target acceptance rate keeps the sampler stable on the hierarchical innovation scale. We differentiate with Mooncake, the recommended backend for this package, described under Automatic differentiation backend.

julia
posterior = as_turing_model(model, y_obs, n)
chain = sample(
    posterior, NUTS(0.95; adtype = AutoMooncake(; config = nothing)),
    MCMCThreads(), 250, 2; progress = false)
┌ Info: Found initial step size
└   ϵ = 0.0015625
┌ Info: Found initial step size
└   ϵ = 0.003125

Sampling returns a chain whose parameter names are flat. Composition does not namespace by default, so a component's own parameter keeps its plain name however deeply it is nested, and damp and std below belong to the AR process folded into the renewal model. A few components deliberately prefix their children, and two components that would otherwise use the same name are separated by wrapping one in PrefixLatentModel or PrefixObservationModel. sample returns a FlexiChains chain, which summarystats summarises directly.

julia
using MCMCChains
summarystats(chain)
╭─FlexiSummary (9 statistics) ─────────────────────────────────────────────────╮
│   iter    collapsed                                                          │
│   chain   collapsed                                                          │
│ ↓ stat  = [mean, std, mcse, ess_bulk, ess_tail, rhat, q5, q50, q95]          │
│                                                                              │
│ Parameters (41) ── AbstractPPL.VarName                                       │
│  Float64  init[1], init[2], damp[1], damp[2], std, ϵ_t[1], ϵ_t[2], ϵ_t[3],   │
│           ϵ_t[4], ϵ_t[5], ϵ_t[6], ϵ_t[7], ϵ_t[8], ϵ_t[9], ϵ_t[10], ϵ_t[11],  │
│           ϵ_t[12], ϵ_t[13], ϵ_t[14], ϵ_t[15], ϵ_t[16], ϵ_t[17], ϵ_t[18],     │
│           ϵ_t[19], ϵ_t[20], ϵ_t[21], ϵ_t[22], ϵ_t[23], ϵ_t[24], ϵ_t[25],     │
│           ϵ_t[26], ϵ_t[27], ϵ_t[28], ϵ_t[29], ϵ_t[30], ϵ_t[31], ϵ_t[32],     │
│           ϵ_t[33], ϵ_t[34], init_incidence, cluster_factor                   │
│                                                                              │
│ Extras (14)                                                                  │
│  Float64  n_steps, is_accept, acceptance_rate, log_density,                  │
│           hamiltonian_energy, hamiltonian_energy_error,                      │
│           max_hamiltonian_energy_error, tree_depth, numerical_error,         │
│           step_size, nom_step_size, logprior, loglikelihood, logjoint        │
│                                                                              │
│ Summary                                                                      │
│          param     mean     std    mcse   ess_bulk  ess_tail    rhat  …      │
│        init[1]   0.0257  0.2122  0.0064  1127.1203  260.2998  0.9994  …      │
│        init[2]  -0.0072  0.1803  0.0073   613.9802  472.2365  0.9989  …      │
│        damp[1]   0.8174  0.0408  0.0038   118.6851  325.9957  1.0266  …      │
│        damp[2]   0.0839  0.0414  0.0049    70.2556   61.9606  0.9985  …      │
│            std   0.4204  0.0499  0.0051    98.2897  203.4907  1.0250  …      │
│         ϵ_t[1]   0.3760  0.8998  0.1385    42.0012   70.9344  1.0063  …      │
│         ϵ_t[2]   0.9485  0.8838  0.1840    23.9348  188.9333  1.0774  …      │
│         ϵ_t[3]   1.2520  0.8868  0.1199    54.9980  108.8407  1.0018  …      │
│         ϵ_t[4]   1.1970  0.9340  0.1173    63.8992  104.6240  1.0438  …      │
│         ϵ_t[5]   2.5528  0.7403  0.0801    88.5621  111.6289  1.0025  …      │
│         ϵ_t[6]   1.6549  0.6610  0.0588   126.9814  215.9505  1.0019  …      │
│         ϵ_t[7]   0.7893  0.6104  0.1430    17.8223  211.5053  1.0670  …      │
│         ϵ_t[8]   0.6839  0.5212  0.0528    96.5198  140.6222  1.0214  …      │
│         ϵ_t[9]  -0.6517  0.5136  0.0560    85.8979  182.0035  1.0191  …      │
│        ϵ_t[10]  -2.3124  0.4824  0.0445   120.7622  253.5835  1.0072  …      │
│        ϵ_t[11]  -1.6958  0.4784  0.0396   153.5102  150.8036  1.0044  …      │
│        ϵ_t[12]   0.5766  0.4429  0.0529    90.3528   47.5231  1.0401  …      │
│        ϵ_t[13]   1.1463  0.3504  0.0386    79.6640  193.2512  1.0165  …      │
│        ϵ_t[14]   0.0166  0.3842  0.0320   173.9208  104.5048  1.0167  …      │
│        ϵ_t[15]   1.2486  0.3907  0.0347   141.7452  135.5449  0.9981  …      │
│        ϵ_t[16]  -1.1828  0.3848  0.0276   209.3220  191.0530  1.0117  …      │
│        ϵ_t[17]  -0.3875  0.3410  0.0216   246.0633  155.3413  1.0203  …      │
│        ϵ_t[18]  -0.8059  0.3453  0.0221   241.6166  193.5563  1.0092  …      │
│        ϵ_t[19]  -0.6720  0.3813  0.0297   194.4426  137.4645  1.0154  …      │
│        ϵ_t[20]  -0.5140  0.3353  0.0221   307.4188  141.8251  1.0074  …      │
│        ϵ_t[21]   0.2107  0.3666  0.0246   260.4060  188.4453  1.0299  …      │
│        ϵ_t[22]  -0.0604  0.3106  0.0248   207.7334  107.5730  1.0087  …      │
│        ϵ_t[23]  -0.4894  0.3245  0.0197   299.4400  158.1384  1.0308  …      │
│        ϵ_t[24]  -0.9227  0.3685  0.0249   254.3136  295.1699  1.0465  …      │
│        ϵ_t[25]  -1.3718  0.4161  0.0359   149.9473  104.5374  1.0137  …      │
│        ϵ_t[26]   1.0578  0.4039  0.0438    96.0333  105.0417  1.0168  …      │
│        ϵ_t[27]  -1.1121  0.4450  0.0438   120.4770  102.4235  1.0141  …      │
│        ϵ_t[28]   0.0166  0.3868  0.0264   224.1182  189.8803  1.0268  …      │
│        ϵ_t[29]   0.1505  0.4356  0.0376   171.9979   96.0942  1.0036  …      │
│        ϵ_t[30]  -0.3144  0.4423  0.0300   227.9932  160.6568  1.0028  …      │
│        ϵ_t[31]   0.2058  0.4355  0.0286   232.7008  230.2669  1.0109  …      │
│        ϵ_t[32]   0.6076  0.4240  0.0251   302.4153  176.0429  1.0063  …      │
│        ϵ_t[33]   0.6193  0.4405  0.0254   302.3751  319.2985  0.9998  …      │
│        ϵ_t[34]   1.3062  0.4167  0.0272   243.3134  154.4263  1.0020  …      │
│   init_incide…  -0.0406  0.1008  0.0052   367.9318  397.1099  1.0027  …      │
│   cluster_fac…   0.0842  0.0614  0.0177    14.9480   49.4424  1.0668  …      │
╰──────────────────────────────────────────────────────────────────────────────╯

Prior versus posterior ​

Sampling the same model with Prior, ignoring the observations, gives a prior draw over the same parameters. Overlaying it on the posterior shows which parameters moved. We load a Makie backend and PairPlots.jl. The FlexiChains PairPlots extension turns a chain subset to a few keys with chain[[...]] into a PairPlots.Series, so prior and posterior overlay on one corner plot.

julia
using CairoMakie, PairPlots

prior_chain = sample(posterior, Prior(), 1000; progress = false)
pp_keys = [@varname(damp), @varname(std),
    @varname(cluster_factor), @varname(init_incidence)]
pairplot(
    PairPlots.Series(chain[pp_keys]; label = "posterior"),
    PairPlots.Series(prior_chain[pp_keys]; label = "prior"))

The innovation scale (std) is sharply updated away from its prior, so the data are informative about how much moves. The autoregressive damping (damp), the cluster factor and the initial infections stay closer to their priors on this short window.

Posterior trajectories ​

The reproduction number   is a generated quantity rather than a sampled parameter. generated_observables re-runs the fitted model over the chain to recover the latent and infection trajectories per draw. The reported counts are scored element-wise, so their posterior predictive distribution comes from predict on the same model with the observations set to missing.

A couple of small helpers reduce the per-draw trajectories to credible bands and draw a median line with 50% and 95% ribbons.

Stack the per-draw into an band, draw the posterior-predictive from the unconditioned model, and plot both against the observed series.

julia
gens = vec(generated_observables(posterior, y_obs, chain).generated)
Rt = credible_bands(reduce(hcat, (exp.(g.Z_t) for g in gens)))

pred = predict(as_turing_model(model, fill(missing, n), n), chain)
yt = predictive_bands(pred, n)

fig = Figure(; size = (760, 620))
ax1 = Axis(fig[1, 1]; ylabel = "Reproduction number Rₜ")
ci_ribbon!(ax1, 1:size(Rt, 1), Rt; color = :purple, label = "posterior median")
hlines!(ax1, [1.0]; color = :grey, linestyle = :dash)
axislegend(ax1; position = :rt)
ax2 = Axis(fig[2, 1]; xlabel = "Day", ylabel = "Reported cases")
ci_ribbon!(ax2, 1:size(yt, 1), yt; color = :teal,
    label = "posterior predictive")
scatter!(ax2, 1:n, y_obs; color = :black, markersize = 7, label = "observed")
axislegend(ax2; position = :lt)
fig

The posterior-predictive band tracks the observed South Korean series closely. The path recovers the first-wave turn-over, with an early rise well above one, a fall through   as the wave peaks, and a decline below one as cases drop.

Forecasting the next weeks ​

The same fitted model forecasts out of sample in one call. The latent AR process is non-centred, so forecast carries each posterior draw forward and then draws the future reported cases. It holds the fitted parameters and the in-sample path fixed, and continues the process over the horizon with fresh prior innovations.

julia
h = 14
fc = forecast(model, y_obs, chain, h)
round.(quantile(Float64.(vec(fc[@varname(y_t[n + h])])), [0.05, 0.5, 0.95]),
    digits = 1)
3-element Vector{Float64}:
     5.0
   276.0
 44392.3

The returned chain carries the predicted over    .

julia
# Multi-level CI band quantiles: 90%, 60%, 30% + median
FC_CI_QS = [0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95]

# Draw three nested CI ribbons with the median line
function multi_ci_ribbon!(ax, ts, bands; color, label)
    keep = findall(!ismissing, view(bands, :, 4))
    x, b = ts[keep], Float64.(bands[keep, :])
    # 90% CI (cols 1, 7)
    band!(ax, x, b[:, 1], b[:, 7]; color = (color, 0.1))
    # 60% CI (cols 2, 6)
    band!(ax, x, b[:, 2], b[:, 6]; color = (color, 0.25))
    # 30% CI (cols 3, 5)
    band!(ax, x, b[:, 3], b[:, 5]; color = (color, 0.5))
    # median (col 4)
    lines!(ax, x, b[:, 4]; color = color, linewidth = 2, label = label)
end

# Multi-level credible bands for the forecast
fc_bands = credible_bands(reduce(vcat,
    (permutedims(vec(fc[@varname(y_t[i])])) for i in (n + 1):(n + h)));
    qs = FC_CI_QS)

# Sample 100 random forecast trajectories
n_draws = length(vec(fc[@varname(y_t[n + 1])]))
ntraj = min(100, n_draws)
sample_idx = rand(1:n_draws, ntraj)
trajectories = reduce(hcat,
    [[vec(fc[@varname(y_t[i])])[idx] for i in (n + 1):(n + h)] for idx in sample_idx])

fig_fc = Figure(; size = (760, 360))
axf = Axis(fig_fc[1, 1]; xlabel = "Day", ylabel = "Reported cases",
    yscale = log10)
scatter!(axf, 1:n, y_obs; color = :black, markersize = 7, label = "observed")
# Faint individual forecast trajectories
for idx in 1:ntraj
    lines!(axf, (n + 1):(n + h), max.(trajectories[:, idx], 1);
        color = (:teal, 0.08), linewidth = 0.5)
end
# Multi-level CI bands (offset to keep log10 scale safe at zero)
multi_ci_ribbon!(axf, (n + 1):(n + h), max.(fc_bands, 1); color = :teal,
    label = "forecast")
vlines!(axf, [n + 0.5]; color = :grey, linestyle = :dash)
axislegend(axf; position = :lt)
fig_fc

Swap a component ​

The parts share one interface, so an alternative observation assumption is a one-line change. Swapping the negative-binomial reporting for a PoissonError leaves the renewal infection process and its latent process untouched.

julia
using ComposableTuringIDModels: swap
poisson_model = swap(
    err -> err isa NegativeBinomialError ? PoissonError() : err, model)
IDModel
├─ infection: Renewal
│  └─ rt: AR
│     └─ ϵ_t: HierarchicalNormal
└─ observation: PoissonError

swap walks the observation chain, replaces every component matching the predicate and rebuilds each wrapper around its replacement. See Inspecting and updating an observation chain for the general form, which also targets a single stream of a Split.

References ​

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

  2. S. Mishra, T. Berah, T. A. Mellan, H. J. Unwin, M. A. Vollmer, K. V. Parag, A. Gandy, S. Flaxman and S. Bhatt. On the derivation of the renewal equation from an age-dependent branching process: an epidemic modelling perspective, arXiv preprint arXiv:2006.16487 (2020).

  3. K. Charniga, S. W. Park, A. R. Akhmetzhanov, A. Cori, J. Dushoff, S. Funk and others. Best practices for estimating and reporting epidemiological delay distributions of infectious diseases. PLoS Computational Biology 20, e1012520 (2024).