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 [3].

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. Both keep the model's as the eventual total, so the nowcast is 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 two 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.

A fourth fit takes the plain model to the complete (untruncated) series, what the analyst would eventually see, as a reference.

The corrections differ from the plain model only in their observation model, so each is derived from it with Accessors.@set rather than rebuilt.

julia
using Accessors

naive_model = IDModel(renewal, error)
rt_obs = RightTruncate(error, ReportingCDF(reporting_delay; D = 10))
rt_model = @set naive_model.observation_model = rt_obs
tri_obs = ReportTriangle(error, delay_pmf)
tri_model = @set naive_model.observation_model = tri_obs
IDModel
├─ infection: Renewal
│  └─ rt: AR
│     └─ ϵ_t: HierarchicalNormal
└─ observation: ReportTriangle
   ├─ error: NegativeBinomialError
   └─ delay: ReportingPMF

A fit is a model and the data it is scored against. The four are a table of pairs, so the sampler call is written once.

julia
specs = (
    naive = (model = naive_model, data = observed_so_far),
    right_truncate = (model = rt_model, data = observed_so_far),
    report_triangle = (model = tri_model,
        data = define_y_t(tri_obs, reported_triangle, eventual)),
    complete = (model = naive_model, data = eventual))

fits = map(specs) do spec
    post = as_turing_model(spec.model, spec.data, n)
    chain = sample(post, NUTS(1000, 0.95; adtype = adt), MCMCThreads(), 250, 2;
        progress = false)
    (; post, chain)
end

naive_post, naive_chain = fits.naive
rt_post, rt_chain = fits.right_truncate
tri_post, tri_chain = fits.report_triangle
complete_post, complete_chain = fits.complete
┌ Info: Found initial step size
└   ϵ = 0.0125
┌ Info: Found initial step size
└   ϵ = 0.00625
┌ Info: Found initial step size
└   ϵ = 0.025
┌ Info: Found initial step size
└   ϵ = 0.0125
┌ 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 7 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 9 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.00625
┌ Info: Found initial step size
└   ϵ = 0.003125
┌ Info: Found initial step size
└   ϵ = 0.0125
┌ Info: Found initial step size
└   ϵ = 0.0125

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

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

map(fit -> recent_Rt(fit.post, fit.chain), fits)
(naive = 0.3, right_truncate = 0.9, report_triangle = 0.88, complete = 0.92)

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[1]), the innovation scale (std), the observation overdispersion (cluster_factor) and the initial infections (init_incidence).

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  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.1084  0.2934  0.0402   53.5396  110.1585  1.0078  …       │
│           damp   0.7847  0.0449  0.0125   13.4842   24.3737  1.1112  …       │
│              ρ   0.7847  0.0449  0.0125   13.4842   24.3737  1.1112  …       │
│            std   0.3149  0.0295  0.0081   13.6836   62.4321  1.0366  …       │
│         ϵ_t[1]   3.0077  0.7610  0.1211   39.2772   73.5218  1.0005  …       │
│         ϵ_t[2]  -0.0836  0.6577  0.0982   44.3041   91.3262  1.0400  …       │
│         ϵ_t[3]   1.2531  0.4965  0.0594   69.0353  121.9873  1.0073  …       │
│         ϵ_t[4]  -0.3367  0.4283  0.0656   42.7580   76.7839  1.0152  …       │
│         ϵ_t[5]  -0.4074  0.4355  0.0532   64.9866  190.5404  1.0082  …       │
│         ϵ_t[6]   2.9760  0.4332  0.0717   37.0679  139.4810  1.0308  …       │
│         ϵ_t[7]  -0.5143  0.3971  0.0525   53.3226   72.1730  1.0110  …       │
│         ϵ_t[8]  -0.2325  0.3061  0.0335   83.6289   81.0039  1.0249  …       │
│         ϵ_t[9]   2.3263  0.3173  0.0839   14.8341  157.8487  1.0765  …       │
│        ϵ_t[10]  -1.8624  0.3171  0.0546   35.1218   54.7904  1.0049  …       │
│        ϵ_t[11]   0.6795  0.2135  0.0275   62.6855  144.9289  1.0457  …       │
│        ϵ_t[12]   0.5792  0.2242  0.0306   55.3037  117.9778  1.0028  …       │
│        ϵ_t[13]   0.7049  0.2307  0.0363   46.5566   45.8115  1.0347  …       │
│        ϵ_t[14]  -0.1080  0.1880  0.0291   43.9322  114.7050  1.0193  …       │
│        ϵ_t[15]   1.3155  0.1877  0.0377   25.5858   93.7628  1.0606  …       │
│        ϵ_t[16]   0.3401  0.1887  0.0431   18.9776   58.4343  1.0911  …       │
│        ϵ_t[17]   0.3385  0.1606  0.0222   53.2061   80.1942  1.0379  …       │
│        ϵ_t[18]  -2.1139  0.2539  0.0638   16.1044   67.0725  1.0233  …       │
│        ϵ_t[19]   2.5802  0.2591  0.0647   16.3198  116.6452  1.0206  …       │
│        ϵ_t[20]   0.2841  0.1465  0.0294   24.8503   42.3626  1.0680  …       │
│        ϵ_t[21]  -0.3209  0.1438  0.0308   24.3099   36.0683  1.0310  …       │
│        ϵ_t[22]   0.8777  0.1221  0.0481    6.6501  108.4537  1.1303  …       │
│        ϵ_t[23]  -0.8293  0.1466  0.0319   21.7173   58.1023  1.0272  …       │
│        ϵ_t[24]   1.0066  0.1269  0.0525    5.9232   53.2781  1.1458  …       │
│        ϵ_t[25]  -0.5077  0.1209  0.0255   24.4058   32.9753  1.0070  …       │
│        ϵ_t[26]   0.4897  0.0863  0.0153   32.8368  150.9689  1.0325  …       │
│        ϵ_t[27]   0.6824  0.1025  0.0328   10.3545   74.7083  1.1041  …       │
│        ϵ_t[28]   0.2740  0.0894  0.0191   22.8007  137.6950  1.0691  …       │
│        ϵ_t[29]   0.1734  0.0949  0.0180   27.9463   70.4219  1.0497  …       │
│        ϵ_t[30]  -0.6268  0.1052  0.0217   25.5000   53.4113  1.0114  …       │
│        ϵ_t[31]  -0.5611  0.0916  0.0186   23.5715  137.8237  1.0020  …       │
│        ϵ_t[32]   0.2608  0.0703  0.0108   42.8160  101.8865  1.0064  …       │
│        ϵ_t[33]  -0.0365  0.0683  0.0080   73.8867   89.3700  1.0106  …       │
│        ϵ_t[34]   0.5204  0.0785  0.0142   31.3113   49.9605  1.0151  …       │
│        ϵ_t[35]  -0.1257  0.0734  0.0143   31.8176   48.9546  1.0338  …       │
│        ϵ_t[36]   0.0085  0.0683  0.0079   77.1719  100.6130  1.0141  …       │
│        ϵ_t[37]  -0.4459  0.0825  0.0169   24.7957   45.9898  1.0078  …       │
│        ϵ_t[38]  -0.8746  0.1080  0.0177   37.3140  108.3424  1.0175  …       │
│        ϵ_t[39]  -0.0173  0.1018  0.0238   21.5965   94.1350  1.0948  …       │
│        ϵ_t[40]   0.5439  0.1240  0.0280   19.9658  109.9309  1.0114  …       │
│        ϵ_t[41]  -0.0905  0.1271  0.0166   61.9882   56.2637  1.0265  …       │
│        ϵ_t[42]  -0.1295  0.1783  0.0232   60.6203  124.5383  1.0017  …       │
│        ϵ_t[43]  -0.0742  0.4119  0.0463   79.3426  226.8501  1.0011  …       │
│        ϵ_t[44]  -0.1852  1.0460  0.1067  105.5890   79.2638  1.0016  …       │
│   init_incide…   2.9556  0.2548  0.0408   39.6012   75.0883  1.0051  …       │
│   cluster_fac…   0.0102  0.0062  0.0005  122.7087   99.9814  0.9999  …       │
╰──────────────────────────────────────────────────────────────────────────────╯

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), @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).