Skip to content

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 is only counted after a reporting delay, so on day we have seen a fraction of the cases that will eventually be attributed to recent days. Fitting a renewal model to this right-truncated tail without correction produces the familiar artefact of real-time estimation, an apparent late down-turn in that is really the not-yet-reported counts [ DocumenterCitations.CitationSiteNode("abbott2020estimating-cite-5")

].

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 untouched, and both keep the model's as the eventual total, so the nowcast is just read back out.

The two corrections ​

The infection pipeline produces  , the expected eventual total for reference day . Write for the reporting-delay PMF (delay  ) and     for its CDF. A reference day of age    has reported a fraction   of its eventual total.

Summing the joint model's observed cells over recovers the marginal mean    , so the two are consistent by construction. A naive fit drops the delay factor (equivalently  ).

The renewal model ​

Both corrections wrap the same composed renewal model as the renewal tutorial, an autoregressive process folded into a Renewal infection process observed with a NegativeBinomialError.

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

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

Split each reference day's eventual total across delays with a multinomial draw, then keep only the cells reported by   (  ). The observed-so-far total per reference day is the row-sum of the reported cells, the marginal the CDF-scaling correction sees.

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

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

julia
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 diagnostic is available, differentiating with Mooncake (see Automatic differentiation backend). The naive fit treats the truncated totals as complete, and motivates the problem. 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.

julia
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.0125
┌ Info: Found initial step size
└   ϵ = 0.025
┌ Info: Found initial step size
└   ϵ = 0.00625
┌ 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/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: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:483
┌ Warning: There were 16 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
┌ Info: Found initial step size
└   ϵ = 0.00625
┌ Info: Found initial step size
└   ϵ = 0.025
┌ Info: Found initial step size
└   ϵ = 0.003125
┌ Info: Found initial step size
└   ϵ = 0.025
┌ 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.0125

As a reference we also fit the plain model to the complete (untruncated) series, what the analyst would eventually see.

julia
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.00078125
┌ Info: Found initial step size
└   ϵ = 0.00625
┌ Info: Found initial step size
└   ϵ = 0.003125
┌ Warning: There were 3 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 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/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:483

Recent Rt ​

  is a generated quantity, recovered per draw by re-running the fitted model over the chain with generated_observables. Averaging it over the most recent window shows the bias and its removal. Right-truncation biases the naive recent downward, so the naive value sits below the two corrections, which lift it back up towards the complete-data reference. The exact numbers carry Monte Carlo noise on this short run, but the direction is the robust, repeatable signal.

julia
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 panel plots the bands of all four fits. The nowcast panel plots the reconstructed eventual totals   for the two corrections against the true eventual totals and the truncated observed-so-far. The posterior prediction panel plots 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.

julia
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 (crimson) dips below the complete-data reference (black), while the two corrections lift the recent back up off that spurious decline. The nowcast panel shows the same story on the count scale, the corrections lifting the reconstructed eventual totals above the truncated observed-so-far towards the true eventual line. The posterior-predictive panel confirms the 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 .

julia
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.0841  0.2400  0.0192  157.9039  348.2921  1.0021  …       │
│        damp_AR   0.7954  0.0428  0.0084   25.9870   41.1770  1.0296  …       │
│              ρ   0.7954  0.0428  0.0084   25.9870   41.1770  1.0296  …       │
│            std   0.3325  0.0316  0.0049   39.4750   45.8880  1.0564  …       │
│         ϵ_t[1]   3.0005  0.6173  0.0545  128.4958  199.7329  1.0136  …       │
│         ϵ_t[2]  -0.1097  0.5704  0.0558  102.4513  197.5941  1.0153  …       │
│         ϵ_t[3]   1.1065  0.4865  0.0482  101.6632  270.2576  1.0056  …       │
│         ϵ_t[4]  -0.3635  0.4647  0.0468   99.9039  270.1515  1.0022  …       │
│         ϵ_t[5]  -0.3972  0.4016  0.0335  144.4761  303.8000  1.0002  …       │
│         ϵ_t[6]   2.8639  0.4126  0.0411  101.2626  264.1184  1.0112  …       │
│         ϵ_t[7]  -0.5724  0.3189  0.0315  102.2170  274.7664  1.0106  …       │
│         ϵ_t[8]  -0.2301  0.3116  0.0384   66.2349  124.3346  1.0097  …       │
│         ϵ_t[9]   2.2036  0.2963  0.0341   75.7272  137.3298  1.0171  …       │
│        ϵ_t[10]  -1.8450  0.2919  0.0411   51.3119  145.6887  1.0079  …       │
│        ϵ_t[11]   0.6624  0.2254  0.0255   78.4856  249.4621  1.0231  …       │
│        ϵ_t[12]   0.5351  0.2164  0.0245   77.6560  172.4875  1.0017  …       │
│        ϵ_t[13]   0.6475  0.2011  0.0191  114.8348  176.9072  1.0072  …       │
│        ϵ_t[14]  -0.1225  0.1860  0.0230   65.8383  125.9414  1.0034  …       │
│        ϵ_t[15]   1.2282  0.1896  0.0189  101.6503  271.7656  1.0149  …       │
│        ϵ_t[16]   0.3055  0.1676  0.0223   57.7204  149.7004  1.0056  …       │
│        ϵ_t[17]   0.2890  0.1485  0.0189   62.2044  129.7409  1.0127  …       │
│        ϵ_t[18]  -2.0248  0.2268  0.0389   37.5158   71.2036  1.0361  …       │
│        ϵ_t[19]   2.4520  0.2469  0.0361   47.4681   68.8137  1.0693  …       │
│        ϵ_t[20]   0.2518  0.1324  0.0177   60.6644   72.7294  1.0026  …       │
│        ϵ_t[21]  -0.3179  0.1267  0.0207   39.0234   58.8971  1.0170  …       │
│        ϵ_t[22]   0.8089  0.1212  0.0156   60.6501  127.3428  1.0065  …       │
│        ϵ_t[23]  -0.8011  0.1287  0.0222   37.6195   40.0426  1.0170  …       │
│        ϵ_t[24]   0.9467  0.1164  0.0161   52.3204   83.4425  1.0509  …       │
│        ϵ_t[25]  -0.4915  0.1025  0.0176   35.4680  113.8537  1.0368  …       │
│        ϵ_t[26]   0.4536  0.0899  0.0110   67.8989  151.1485  1.0039  …       │
│        ϵ_t[27]   0.6373  0.0999  0.0116   73.7823  150.7005  1.0199  …       │
│        ϵ_t[28]   0.2456  0.0924  0.0123   60.0432   75.0574  1.0025  …       │
│        ϵ_t[29]   0.1511  0.0867  0.0113   59.1474  149.3624  1.0191  …       │
│        ϵ_t[30]  -0.6072  0.1000  0.0147   53.9473   77.4919  1.0227  …       │
│        ϵ_t[31]  -0.5228  0.0774  0.0091   75.0725  180.2953  1.0172  …       │
│        ϵ_t[32]   0.2302  0.0615  0.0054  127.6859  207.2173  1.0033  …       │
│        ϵ_t[33]  -0.0262  0.0644  0.0067   91.7291  148.2691  1.0257  …       │
│        ϵ_t[34]   0.4874  0.0743  0.0082   82.4253  176.6919  0.9993  …       │
│        ϵ_t[35]  -0.1153  0.0629  0.0049  163.0868  259.7377  1.0015  …       │
│        ϵ_t[36]  -0.0024  0.0625  0.0054  135.6431  184.3125  1.0029  …       │
│        ϵ_t[37]  -0.4191  0.0824  0.0086  102.4336  106.8316  1.0072  …       │
│        ϵ_t[38]  -0.8398  0.1078  0.0147   54.4917  118.3120  1.0543  …       │
│        ϵ_t[39]   0.0091  0.0887  0.0101   77.0926  207.8379  1.0048  …       │
│        ϵ_t[40]   0.5130  0.0985  0.0106   87.2378  276.1671  1.0158  …       │
│        ϵ_t[41]  -0.0660  0.1129  0.0102  127.1767  226.3523  0.9998  …       │
│        ϵ_t[42]  -0.1551  0.1674  0.0144  136.9695  296.3198  1.0066  …       │
│        ϵ_t[43]   0.0785  0.3766  0.0270  196.1357  317.9425  1.0012  …       │
│        ϵ_t[44]  -0.0348  1.0033  0.0754  176.1053  272.3440  0.9992  …       │
│   init_incide…   2.9277  0.2138  0.0205  110.0928  236.2499  1.0009  …       │
│   cluster_fac…   0.0094  0.0063  0.0004  190.5484  218.8171  1.0149  …       │
╰──────────────────────────────────────────────────────────────────────────────╯

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.

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

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