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 tutorial 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 tutorial, 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", "tutorials", "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"))
Three fits
We fit the plain renewal model three ways with NUTS, drawing four 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.
naive_model = IDModel(renewal, error)
naive_post = as_turing_model(naive_model, observed_so_far, n)
naive_chain = sample(
naive_post, NUTS(1000, 0.95; adtype = adt), MCMCThreads(), 250, 4;
progress = false)
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)
rt_chain = sample(
rt_post, NUTS(1000, 0.95; adtype = adt), MCMCThreads(), 250, 4;
progress = false)
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)
tri_chain = sample(
tri_post, NUTS(1000, 0.95; adtype = adt), MCMCThreads(), 250, 4;
progress = false)┌ Info: Found initial step size
└ ϵ = 0.025
┌ Info: Found initial step size
└ ϵ = 0.00625
┌ Info: Found initial step size
└ ϵ = 0.025
┌ Info: Found initial step size
└ ϵ = 0.0125
┌ 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/4sXd9/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/4sXd9/src/mcmc/hmc.jl:483
┌ Info: Found initial step size
└ ϵ = 0.003125
┌ Info: Found initial step size
└ ϵ = 0.00625
┌ Info: Found initial step size
└ ϵ = 0.025
┌ Info: Found initial step size
└ ϵ = 0.025
┌ Warning: There were 2 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/4sXd9/src/mcmc/hmc.jl:483
┌ Warning: There were 6 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/4sXd9/src/mcmc/hmc.jl:483
┌ Warning: There were 8 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/4sXd9/src/mcmc/hmc.jl:483
┌ Info: Found initial step size
└ ϵ = 0.0125
┌ Info: Found initial step size
└ ϵ = 0.0125
┌ Info: Found initial step size
└ ϵ = 0.0125
┌ Info: Found initial step size
└ ϵ = 0.0125As a reference we also fit the plain model to the complete (untruncated) series, what the analyst would eventually see.
complete_post = as_turing_model(naive_model, eventual, n)
complete_chain = sample(
complete_post, NUTS(1000, 0.95; adtype = adt), MCMCThreads(), 250, 4;
progress = false)┌ Info: Found initial step size
└ ϵ = 0.0125
┌ Info: Found initial step size
└ ϵ = 0.00625
┌ Info: Found initial step size
└ ϵ = 0.00078125
┌ Info: Found initial step size
└ ϵ = 0.003125
┌ Warning: There were 1 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/4sXd9/src/mcmc/hmc.jl:483
┌ Warning: There were 1 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/4sXd9/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.88)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[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 init[1], damp, ρ, 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 … │
│ init[1] 0.0879 0.2656 0.0183 211.8951 253.8102 1.0007 … │
│ damp 0.7861 0.0432 0.0078 28.4030 45.8175 1.0581 … │
│ ρ 0.7861 0.0432 0.0078 28.4030 45.8175 1.0581 … │
│ std 0.3271 0.0306 0.0048 40.7853 85.5830 1.0466 … │
│ ϵ_t[1] 2.9438 0.6322 0.0525 144.9493 260.3099 0.9999 … │
│ ϵ_t[2] -0.0724 0.5508 0.0469 139.6060 274.4868 1.0135 … │
│ ϵ_t[3] 1.1419 0.4946 0.0402 152.1407 211.1976 0.9991 … │
│ ϵ_t[4] -0.3008 0.4387 0.0363 146.7092 308.2991 1.0098 … │
│ ϵ_t[5] -0.3753 0.3911 0.0280 196.3288 335.1441 1.0047 … │
│ ϵ_t[6] 2.8919 0.3849 0.0313 154.6851 218.9697 1.0000 … │
│ ϵ_t[7] -0.5183 0.3402 0.0413 67.4381 149.8256 1.0142 … │
│ ϵ_t[8] -0.2336 0.3048 0.0343 79.4190 168.6441 1.0409 … │
│ ϵ_t[9] 2.2655 0.3177 0.0405 61.5549 184.2943 1.0071 … │
│ ϵ_t[10] -1.8490 0.3036 0.0393 60.7456 109.8691 1.0453 … │
│ ϵ_t[11] 0.6962 0.2229 0.0207 117.3111 267.1974 1.0007 … │
│ ϵ_t[12] 0.5492 0.2120 0.0206 105.7847 207.0501 1.0041 … │
│ ϵ_t[13] 0.6823 0.2168 0.0261 70.3811 165.3166 1.0036 … │
│ ϵ_t[14] -0.1135 0.1987 0.0228 76.7927 208.6676 1.0220 … │
│ ϵ_t[15] 1.2658 0.1981 0.0237 71.7805 164.3190 1.0049 … │
│ ϵ_t[16] 0.3321 0.1752 0.0290 28.0747 75.8288 1.0766 … │
│ ϵ_t[17] 0.3150 0.1575 0.0195 68.7770 86.5687 1.0012 … │
│ ϵ_t[18] -2.0318 0.2275 0.0286 62.9531 99.3042 1.0336 … │
│ ϵ_t[19] 2.4809 0.2475 0.0343 51.5778 94.6131 1.0242 … │
│ ϵ_t[20] 0.2770 0.1405 0.0225 32.7163 109.4017 1.0457 … │
│ ϵ_t[21] -0.3114 0.1210 0.0137 77.3035 146.5997 1.0163 … │
│ ϵ_t[22] 0.8452 0.1305 0.0173 56.8232 127.8126 1.0025 … │
│ ϵ_t[23] -0.7995 0.1323 0.0165 64.0265 164.1360 1.0221 … │
│ ϵ_t[24] 0.9632 0.1174 0.0152 59.4417 147.1908 1.0042 … │
│ ϵ_t[25] -0.4838 0.1022 0.0112 82.0860 154.9212 1.0184 … │
│ ϵ_t[26] 0.4679 0.0914 0.0103 78.5941 195.0563 1.0032 … │
│ ϵ_t[27] 0.6596 0.1060 0.0131 68.5530 171.5044 0.9998 … │
│ ϵ_t[28] 0.2535 0.0900 0.0112 65.8927 124.3162 1.0193 … │
│ ϵ_t[29] 0.1726 0.0908 0.0124 53.8343 116.1523 1.0275 … │
│ ϵ_t[30] -0.6053 0.0942 0.0109 76.9746 104.1003 1.0228 … │
│ ϵ_t[31] -0.5316 0.0833 0.0103 64.8936 185.4487 1.0121 … │
│ ϵ_t[32] 0.2391 0.0643 0.0054 137.8995 328.1250 1.0076 … │
│ ϵ_t[33] -0.0297 0.0609 0.0050 147.9421 327.9993 1.0124 … │
│ ϵ_t[34] 0.4992 0.0755 0.0080 88.6567 238.3976 1.0053 … │
│ ϵ_t[35] -0.1179 0.0677 0.0054 158.7254 231.6484 1.0059 … │
│ ϵ_t[36] 0.0003 0.0636 0.0050 162.1097 216.6683 1.0004 … │
│ ϵ_t[37] -0.4223 0.0781 0.0072 118.3233 214.1209 1.0081 … │
│ ϵ_t[38] -0.8492 0.1062 0.0135 62.9164 169.9956 0.9994 … │
│ ϵ_t[39] -0.0138 0.0936 0.0104 80.9046 213.4548 1.0095 … │
│ ϵ_t[40] 0.5289 0.1153 0.0134 73.8496 192.0139 1.0109 … │
│ ϵ_t[41] -0.0896 0.1251 0.0124 106.6910 210.0980 1.0076 … │
│ ϵ_t[42] -0.1372 0.1839 0.0170 117.9064 235.6158 1.0119 … │
│ ϵ_t[43] 0.0501 0.4151 0.0309 183.1239 274.4100 1.0049 … │
│ ϵ_t[44] -0.2542 1.0119 0.0689 216.5451 363.8361 1.0074 … │
│ init_incide… 2.9581 0.2089 0.0178 141.0999 207.1034 1.0019 … │
│ cluster_fac… 0.0099 0.0063 0.0004 199.3007 235.9550 1.0080 … │
╰──────────────────────────────────────────────────────────────────────────────╯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), @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).