Real-time nowcasting: right-truncation vs the reporting triangle
In real time the most recent days of a surveillance series are incomplete. A case with reference day
This package corrects right-truncation two ways, and this case study fits and compares both on the same simulated data. RightTruncate is the marginal correction. It keeps only each reference day's observed-so-far total and scales the expected count by the reporting-delay CDF, the EpiNow2-style CDF-scaling nowcast. ReportTriangle is the joint correction. It keeps the full reference-day × reporting-delay triangle and scores it cell by cell, the epinowcast-style nowcast. The two share one reporting-delay kernel, so the triangle's observed row-sums are exactly the observed-so-far totals the marginal correction conditions on. Both leave the renewal infection process and its latent
The two corrections
The infection pipeline produces
Summing the joint model's observed cells over
The renewal model
Both corrections wrap the same composed renewal model as the renewal case study, an autoregressive Renewal infection process observed with a NegativeBinomialError.
using ComposableTuringIDModels, Distributions, Random, Turing, Mooncake
using ADTypes: AutoMooncake
using CSV, DataFrames
Random.seed!(20240625)
adt = AutoMooncake(; config = nothing)
latent = AR(
damp = [truncated(Normal(0.8, 0.05), 0, 1)],
init = [Normal(0.0, 0.25)],
ϵ_t = HierarchicalNormal(std = HalfNormal(0.1)))
renewal = Renewal(; generation_time = Gamma(1.4, 1 / 0.38),
rt = latent, initialisation = Normal(log(1.0), 1.0))
error = NegativeBinomialError(cluster_factor = HalfNormal(0.1))Simulate a reporting triangle
We take the fully-reported Italy confirmed-case series as the eventual totals, split each day's total across reporting delays with the delay PMF, then mask the cells not yet reported at ReportingPMF discretises the reporting delay with the same CensoredDistributions.jl path the rest of the package uses.
datapath = joinpath(pkgdir(ComposableTuringIDModels),
"docs", "src", "case-studies", "data", "italy_data.csv")
italy = CSV.read(datapath, DataFrame)
n = 45
eventual = italy.confirm[1:n] # eventual (complete) totals
reporting_delay = LogNormal(1.6, 0.5) # mean ≈ 5.6 days
delay_pmf = ReportingPMF(reporting_delay; D = 10)
pmf = delay_pmf.pmf # delays 0 … Dmax
Dmax = length(pmf) - 1Split each reference day's eventual total across delays with a multinomial draw, then keep only the cells reported by
full_triangle = reduce(vcat,
(permutedims(rand(Multinomial(eventual[t], pmf))) for t in 1:n))
mask = [t + d <= n for t in 1:n, d in 0:Dmax]
reported_triangle = full_triangle .* mask
observed_so_far = vec(sum(reported_triangle, dims = 2))
(complete_tail = eventual[(end - 4):end],
truncated_tail = observed_so_far[(end - 4):end])(complete_tail = [4782, 4668, 4585, 4805, 4316], truncated_tail = [2245, 1249, 432, 58, 0])The recent days are visibly thinned, the most recent day showing only a fraction of its eventual count.
Visualise the data
The reporting triangle is the native data object. Plotting it with AlgebraOfGraphics, the not-yet-reported cells blanked, shows the staircase of missing counts in the recent corner.
using AlgebraOfGraphics, CairoMakie, DataFrames
tri_df = DataFrame(
reference = repeat(1:n, outer = Dmax + 1),
delay = repeat(0:Dmax, inner = n),
count = vec(full_triangle),
reported = vec(mask))
tri_df.shown = ifelse.(tri_df.reported, Float64.(tri_df.count), NaN)
draw(data(tri_df) *
mapping(:reference, :delay, :shown => "Reported cases") * visual(Heatmap);
axis = (xlabel = "Reference day", ylabel = "Reporting delay (days)"))
The same truncation reads as a shortfall in the tail when the observed-so-far row-sums are drawn against the eventual totals.
comp_df = DataFrame(
reference = repeat(1:n, 2),
count = vcat(eventual, observed_so_far),
series = repeat(["eventual total", "observed so far"], inner = n))
draw(data(comp_df) * mapping(:reference, :count, color = :series) *
visual(Lines); axis = (xlabel = "Reference day", ylabel = "Cases"))
Four fits
We fit the plain renewal model four ways with NUTS, drawing two chains with 1000 warmup iterations each so the cross-chain RightTruncate applies the marginal correction to the same observed-so-far totals. ReportTriangle applies the joint correction to the reporting triangle, built through the shared define_y_t hook. As a reference we also fit the plain model to the complete (untruncated) series, what the analyst would eventually see.
The four fits are independent, but each already asks MCMCThreads() for two threads, one per chain. Running all four at once would ask for eight, oversubscribing a machine with fewer and holding four posteriors' worth of sampler state in memory at once for no benefit. Instead we cap how many fits run concurrently at half the available threads, so the concurrency matches the two-chains-per-fit budget exactly: one fit at a time on a two-thread machine (the sequential order this page always ran in), two at a time on four threads, and so on.
naive_model = IDModel(renewal, error)
naive_post = as_turing_model(naive_model, observed_so_far, n)
rt_obs = RightTruncate(error, ReportingCDF(reporting_delay; D = 10))
rt_model = IDModel(renewal, rt_obs)
rt_post = as_turing_model(rt_model, observed_so_far, n)
tri_obs = ReportTriangle(error, delay_pmf)
tri_data = define_y_t(tri_obs, reported_triangle, eventual)
tri_model = IDModel(renewal, tri_obs)
tri_post = as_turing_model(tri_model, tri_data, n)
complete_post = as_turing_model(naive_model, eventual, n)
nuts_fit(post) = sample(
post, NUTS(1000, 0.95; adtype = adt), MCMCThreads(), 250, 2;
progress = false)
nconcurrent = max(1, Threads.nthreads() ÷ 2)
naive_chain, rt_chain, tri_chain, complete_chain = asyncmap(
nuts_fit, (naive_post, rt_post, tri_post, complete_post);
ntasks = nconcurrent)┌ Info: Found initial step size
└ ϵ = 0.003125
┌ Info: Found initial step size
└ ϵ = 0.025
┌ Info: Found initial step size
└ ϵ = 0.05
┌ Info: Found initial step size
└ ϵ = 0.0125
┌ Info: Found initial step size
└ ϵ = 0.0015625
┌ Info: Found initial step size
└ ϵ = 0.00625
┌ Info: Found initial step size
└ ϵ = 0.0015625
┌ Info: Found initial step size
└ ϵ = 0.00625
┌ Warning: There were 4 divergent transitions. Consider reparameterising your model or using a smaller step size. For adaptive samplers such as NUTS and HMCDA, consider increasing `target_accept`.
└ @ Turing.Inference ~/.julia/packages/Turing/WteH7/src/mcmc/hmc.jl:483
┌ Warning: There were 4 divergent transitions. Consider reparameterising your model or using a smaller step size. For adaptive samplers such as NUTS and HMCDA, consider increasing `target_accept`.
└ @ Turing.Inference ~/.julia/packages/Turing/WteH7/src/mcmc/hmc.jl:483Recent Rt
generated_observables. Averaging it over the most recent window shows the bias and its removal. Right-truncation biases the naive recent
using Statistics
function recent_Rt(post, chain; window = 7)
gens = vec(generated_observables(post, nothing, chain).generated)
Rt_mean = mean(exp.(g.Z_t) for g in gens)
round(mean(Rt_mean[(end - window + 1):end]), digits = 2)
end
(complete = recent_Rt(complete_post, complete_chain),
naive = recent_Rt(naive_post, naive_chain),
right_truncate = recent_Rt(rt_post, rt_chain),
report_triangle = recent_Rt(tri_post, tri_chain))(complete = 0.91, naive = 0.3, right_truncate = 0.9, report_triangle = 0.89)Posterior prediction, nowcast, and Rt
Three views of the fits share the reference-day axis with the recent window shaded. The RightTruncate model's posterior-predictive observed-so-far, recovered with predict on the same model with the observations set to missing, against the data it was fit to.
ts = 1:n
Rt_complete = gen_bands(complete_post, complete_chain, g -> exp.(g.Z_t))
Rt_naive = gen_bands(naive_post, naive_chain, g -> exp.(g.Z_t))
Rt_rt = gen_bands(rt_post, rt_chain, g -> exp.(g.Z_t))
Rt_tri = gen_bands(tri_post, tri_chain, g -> exp.(g.Z_t))
now_rt = gen_bands(rt_post, rt_chain, g -> g.I_t)
now_tri = gen_bands(tri_post, tri_chain, g -> g.I_t)
rt_pred = predict(as_turing_model(rt_model, fill(missing, n), n), rt_chain)
yt = predictive_bands(rt_pred, n)
fig = Figure(; size = (780, 820))
ax1 = Axis(fig[1, 1]; ylabel = "Reproduction number Rₜ")
vspan!(ax1, n - 6, n; color = (:grey, 0.15))
ci_ribbon!(ax1, ts, Rt_complete; color = :black, label = "complete (reference)")
ci_ribbon!(ax1, ts, Rt_naive; color = :crimson, label = "naive")
ci_ribbon!(ax1, ts, Rt_rt; color = :seagreen, label = "right-truncate")
ci_ribbon!(ax1, ts, Rt_tri; color = :steelblue, label = "report-triangle")
hlines!(ax1, [1.0]; color = :grey, linestyle = :dash)
axislegend(ax1; position = :lb, nbanks = 2)
ax2 = Axis(fig[2, 1]; ylabel = "Eventual cases (nowcast)")
vspan!(ax2, n - 6, n; color = (:grey, 0.15))
ci_ribbon!(ax2, ts, now_rt; color = :seagreen, label = "right-truncate")
ci_ribbon!(ax2, ts, now_tri; color = :steelblue, label = "report-triangle")
lines!(ax2, ts, Float64.(eventual); color = :black, linewidth = 2,
label = "true eventual")
scatter!(ax2, ts, observed_so_far; color = :grey, markersize = 6,
label = "observed so far")
axislegend(ax2; position = :lt)
ax3 = Axis(fig[3, 1]; xlabel = "Reference day", ylabel = "Observed-so-far")
vspan!(ax3, n - 6, n; color = (:grey, 0.15))
ci_ribbon!(ax3, ts, yt; color = :teal, label = "posterior predictive")
scatter!(ax3, ts, observed_so_far; color = :black, markersize = 6,
label = "observed")
axislegend(ax3; position = :lt)
fig
In the shaded recent window the naive RightTruncate fit reproduces the observed-so-far series it saw.
Shared parameters
Neither correction touches the renewal process, so both recover the same shared parameters, the autoregressive damping damp_AR[1]), the innovation scale std), the observation overdispersion (cluster_factor) and the initial infections (init_incidence). sample returns a FlexiChains chain that summarystats summarises directly, giving point estimates and their uncertainty alongside the effective sample size and
using MCMCChains
summarystats(tri_chain)╭─FlexiSummary (9 statistics) ─────────────────────────────────────────────────╮
│ iter collapsed │
│ chain collapsed │
│ ↓ stat = [mean, std, mcse, ess_bulk, ess_tail, rhat, q5, q50, q95] │
│ │
│ Parameters (50) ── AbstractPPL.VarName │
│ Float64 ar_init[1], damp_AR, ρ, 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], ϵ_t[35], ϵ_t[36], ϵ_t[37], ϵ_t[38], ϵ_t[39], ϵ_t[40], │
│ ϵ_t[41], ϵ_t[42], ϵ_t[43], ϵ_t[44], 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 … │
│ ar_init[1] 0.0919 0.2602 0.0263 99.1310 126.8899 1.0035 … │
│ damp_AR 0.7900 0.0476 0.0108 20.4259 44.6280 1.0105 … │
│ ρ 0.7900 0.0476 0.0108 20.4259 44.6280 1.0105 … │
│ std 0.3291 0.0338 0.0086 15.7029 20.4563 1.0793 … │
│ ϵ_t[1] 3.0153 0.5885 0.0589 98.3482 134.9532 1.0200 … │
│ ϵ_t[2] -0.1311 0.6368 0.0685 87.1879 127.7628 0.9993 … │
│ ϵ_t[3] 1.1671 0.4932 0.0518 90.2375 199.1499 1.0106 … │
│ ϵ_t[4] -0.4033 0.4735 0.0520 87.6409 153.5334 1.0013 … │
│ ϵ_t[5] -0.3220 0.4301 0.0478 80.6811 113.3806 1.0174 … │
│ ϵ_t[6] 2.8678 0.4400 0.0637 48.0791 156.0051 1.0111 … │
│ ϵ_t[7] -0.5215 0.3271 0.0556 36.2296 81.5464 1.0315 … │
│ ϵ_t[8] -0.2652 0.3056 0.0335 85.2024 199.6885 1.0014 … │
│ ϵ_t[9] 2.2269 0.3165 0.0652 23.8721 38.4347 1.0692 … │
│ ϵ_t[10] -1.8054 0.3029 0.0593 27.2506 58.8478 1.0030 … │
│ ϵ_t[11] 0.6534 0.2240 0.0331 45.6194 98.1323 1.0299 … │
│ ϵ_t[12] 0.5470 0.2192 0.0289 59.5481 82.9511 1.0002 … │
│ ϵ_t[13] 0.6771 0.2100 0.0366 33.4651 40.7808 1.0211 … │
│ ϵ_t[14] -0.1293 0.1764 0.0197 80.8594 187.2595 0.9996 … │
│ ϵ_t[15] 1.2583 0.2025 0.0353 33.1925 37.8476 1.0116 … │
│ ϵ_t[16] 0.3208 0.1889 0.0289 43.4020 65.0994 1.0091 … │
│ ϵ_t[17] 0.3136 0.1616 0.0299 29.4454 90.3665 1.0033 … │
│ ϵ_t[18] -2.0427 0.2598 0.0582 20.5393 72.8724 1.0108 … │
│ ϵ_t[19] 2.4847 0.2751 0.0656 17.7195 27.7461 1.0375 … │
│ ϵ_t[20] 0.2545 0.1495 0.0269 31.0831 103.8299 1.0110 … │
│ ϵ_t[21] -0.3032 0.1230 0.0218 33.7226 48.7690 1.0043 … │
│ ϵ_t[22] 0.8223 0.1351 0.0290 22.3892 29.3791 1.0328 … │
│ ϵ_t[23] -0.7935 0.1454 0.0277 29.7165 67.2278 1.0141 … │
│ ϵ_t[24] 0.9578 0.1277 0.0279 21.4814 25.4864 1.0920 … │
│ ϵ_t[25] -0.4913 0.1191 0.0229 28.7131 69.3231 1.0265 … │
│ ϵ_t[26] 0.4625 0.0912 0.0149 41.3684 49.2421 1.0235 … │
│ ϵ_t[27] 0.6559 0.1063 0.0211 25.5734 28.6550 1.0254 … │
│ ϵ_t[28] 0.2445 0.0926 0.0185 25.4168 69.0830 1.0310 … │
│ ϵ_t[29] 0.1665 0.0927 0.0175 28.4141 81.4463 1.0003 … │
│ ϵ_t[30] -0.6079 0.1010 0.0195 27.8091 63.9545 1.0057 … │
│ ϵ_t[31] -0.5269 0.0872 0.0179 25.6128 38.7202 1.0737 … │
│ ϵ_t[32] 0.2373 0.0735 0.0092 62.1145 140.3206 1.0149 … │
│ ϵ_t[33] -0.0326 0.0670 0.0076 82.8953 91.9421 1.0116 … │
│ ϵ_t[34] 0.4942 0.0747 0.0129 32.8386 68.4927 1.0117 … │
│ ϵ_t[35] -0.1103 0.0604 0.0065 86.1345 109.9235 1.0026 … │
│ ϵ_t[36] -0.0022 0.0622 0.0091 47.3744 68.6465 0.9990 … │
│ ϵ_t[37] -0.4237 0.0813 0.0149 32.0154 52.8946 1.0287 … │
│ ϵ_t[38] -0.8486 0.1126 0.0229 24.0969 48.8632 1.0240 … │
│ ϵ_t[39] -0.0078 0.0918 0.0128 50.4631 157.4050 0.9993 … │
│ ϵ_t[40] 0.5271 0.1136 0.0214 29.3729 83.3769 1.0319 … │
│ ϵ_t[41] -0.0769 0.1101 0.0106 107.9889 133.9434 1.0072 … │
│ ϵ_t[42] -0.1590 0.1744 0.0174 100.9652 191.3923 0.9988 … │
│ ϵ_t[43] 0.0711 0.4140 0.0488 73.4530 89.9468 1.0090 … │
│ ϵ_t[44] -0.1031 1.0326 0.1018 99.7062 107.2118 1.0016 … │
│ init_incide… 2.9364 0.1871 0.0197 91.7984 239.5260 1.0199 … │
│ cluster_fac… 0.0105 0.0058 0.0005 105.7910 78.9852 0.9983 … │
╰──────────────────────────────────────────────────────────────────────────────╯Prior versus posterior
Sampling the reporting-triangle model with Prior and overlaying it on the posterior with PairPlots.jl confirms the joint correction still identifies the shared parameters from the thinned triangle.
using PairPlots
prior_chain = sample(tri_post, Prior(), 1000; progress = false)
pp_keys = [@varname(damp_AR), @varname(std),
@varname(cluster_factor), @varname(init_incidence)]
pairplot(
PairPlots.Series(tri_chain[pp_keys]; label = "posterior"),
PairPlots.Series(prior_chain[pp_keys]; label = "prior"))
References
- S. Abbott, J. Hellewell, R. N. Thompson, K. Sherratt, H. P. Gibbs, N. I. Bosse, J. D. Munday, S. Meakin, E. L. Doughty, J. Y. Chun and others. Estimating the time-varying reproduction number of SARS-CoV-2 using national and subnational case counts. Wellcome Open Research 5, 112 (2020).