Skip to content

Nowcasting reported cases from a right-truncated reporting triangle ​

Introduction ​

This tutorial is for a user who needs to estimate recent counts that are still incomplete because of reporting delays. Cases are counted by their reference day, here the day of infection, and each is reported some days later. On a given day the counts of recent reference days are incomplete, because many of their reports have not yet been made. A nowcast estimates the eventual count of each reference day from the reports made so far [, ]. The tutorial simulates daily infections and their reports, truncates the reports at day and computes the following, in order.

  • the share of each reference day's reports made by day , from the transpose of the delay convolution;

  • the nowcast of each eventual count as the reports to date over that share;

  • the exact posterior predictive distribution of each eventual count under a Poisson model with a gamma prior, and its coverage over 1000 simulated report sets;

  • the same nowcast with a delay whose hazard depends on the reporting day;

  • the gradient of the log-likelihood of the observed reports with respect to the parameters of that delay.

The delay is known in each section except the last, which differentiates the likelihood that an estimate of the delay would maximise.

It assumes you have read Reporting triangle, case reproduction number and expected descendants. The posterior section uses the result of Conjugate gamma–Poisson estimation.

Packages used ​

julia
using ComposableRecurrences
using ComposableRecurrences: Depletion, Derived, Increments, Normalised,
    Primary, Survival, contributions
using Distributions: Gamma, NegativeBinomial, Poisson, quantile, rate, shape
using Random, Statistics
using ForwardDiff
using CairoMakie, AlgebraOfGraphics, DataFramesMeta

CairoMakie.activate!(type = "png", px_per_unit = 2)

Model ​

Infections on day follow a renewal equation with a finite susceptible population, as in Renewal then delay. Each infection is reported with probability , and a reported infection is reported days after infection with probability , for  . The number of reports of infections on day made at delay is

independently over and , where is the expected eventual count of reference day . The array over reference day and delay is the reporting triangle. On day the cells with    are observed, and the count reported to date and the eventual count of day are

The run covers   days with  , and the nowcast is made on day  .

julia
gi = [0.05, 0.2, 0.3, 0.25, 0.12, 0.08]
T, τ, D = 60, 50, 14
population = 20_000.0
seed = fill(5.0, length(gi))
R = [t <= 35 ? 1.5 : 0.9 for t in 1:T]
pool = Depletion(population; pools = (S = population - sum(seed),))
infections = Recurrence(gi; modifiers = (pool,))(R; history = seed)

w = let x = [d * exp(-d / 2) + 0.02 for d in 0:D]
    x ./ sum(x)
end
delay = Convolution(w)
ρ = 0.3

Simulated reports ​

The expected triangle is the terms of the delay convolution before its sum over delays. contributions returns them, with one column per reference day when indexing = Primary(), and leaves out every term that arrives after stop. Given a table by reference day in place of a convolution, it leaves out the cells reported after stop in the same way, which truncates the simulated triangle at day .

How the counts are drawn

A Poisson count with mean is drawn as the Poisson quantile function at a uniform draw ,  . The uniform draws are made apart from the functions that use them, so later sections can reuse the same draws.

julia
# Poisson counts with means `m`, drawn at the uniforms `u`.
poisson_counts(m, u) = float.(quantile.(Poisson.(m), u))

# The sum of a triangle over delays, by reference day.
by_reference_day(triangle) = vec(sum(triangle; dims = 1))

u = rand(Xoshiro(1), D + 1, T)
expected = contributions(
    delay, infections; gain = ρ, indexing = Primary(), stop = T + D
)
cells = poisson_counts(expected, u)
observed = contributions(cells; stop = τ)
to_date = by_reference_day(observed)
eventual = by_reference_day(cells)[1:τ]
Int.(to_date[(τ - 4):τ]), Int.(eventual[(τ - 4):τ])
([10, 21, 3, 4, 0], [19, 27, 19, 14, 17])

The first five numbers are the counts reported by day 50 for reference days 46 to 50, and the last five their eventual counts.

Nowcast with a known delay ​

The expected count reported by day is the expected eventual count times the share of the delay distribution that falls by .

sums the delay forward from day to day , which is the transpose of the delay convolution applied to a series of ones. is the maximum likelihood estimate of from the reports to date.

julia
# The share of each reference day's reports made by day `τ`.
reported_share(delay, τ) = delay'(ones(τ))

# The reports to date over the share reported by day `τ`.
nowcast(to_date, share) = to_date ./ share

F = reported_share(delay, τ)
round.(F[(τ - 4):τ]; digits = 3)
5-element Vector{Float64}:
 0.633
 0.499
 0.334
 0.154
 0.005

These are the shares for reference days 46 to 50. On day 50 almost none of day 50's reports have been made, since is small.

Exact posterior of the eventual count ​

With a gamma prior on , the reports to date have the gamma posterior of Conjugate gamma–Poisson estimation, with the share in place of the infection pressure.

The reports still to come are then negative binomial, so the posterior predictive distribution of the eventual count is exact and needs no sampler.

The posterior predictive distribution

The reports still to come,  , are Poisson with mean   and independent of those already made given . Over the gamma posterior they are negative binomial,

and the eventual count is the reports to date plus this count.

The prior has shape   and rate  , a mean of 100 reports a day.

julia
# The posterior predictive distribution of the reports still to come on
# each reference day, from a gamma prior and the reports to date.
function still_to_come(prior, to_date, share)
    size = shape(prior) .+ to_date
    p = (rate(prior) .+ share) ./ (rate(prior) + 1)
    return NegativeBinomial.(size, p)
end

# The quantiles `p` of the eventual count of each reference day.
function eventual_quantiles(prior, to_date, share, p)
    remaining = still_to_come(prior, to_date, share)
    return to_date .+ quantile.(remaining, p)
end

prior = Gamma(1, 100)
days = (τ - 19):τ
posterior_table = DataFrame(
    day = collect(days), eventual = eventual[days], to_date = to_date[days],
    nowcast = nowcast(to_date, F)[days],
    lower = eventual_quantiles(prior, to_date, F, 0.025)[days],
    median = eventual_quantiles(prior, to_date, F, 0.5)[days],
    upper = eventual_quantiles(prior, to_date, F, 0.975)[days]
)

draw(
    data(posterior_table) * (
        mapping(:day, :lower, :upper) * visual(Band, alpha = 0.3) +
            mapping(:day, :median) * visual(Lines, linewidth = 2) +
            mapping(:day, :to_date) * visual(Scatter, marker = :circle) +
            mapping(:day, :eventual) *
            visual(Scatter, color = :black, marker = :xcross)
    );
    axis = (xlabel = "Reference day", ylabel = "Reports"),
    figure = (size = (640, 300),)
)

The band is the central 95% posterior predictive interval of the eventual count, the line its median, the circles the counts reported by day 50 and the crosses the eventual counts.

The interval is exact for counts drawn from the model with drawn from the prior. Here is fixed by the run, so the check is the coverage over 1000 report sets drawn from the same expected triangle, for the last 14 reference days.

julia
# The share of report sets in which the central 95% interval of each
# reference day's eventual count contains it.
function coverage(prior, delay, expected, τ, draws)
    share = reported_share(delay, τ)
    hits = map(draws) do u
        cells = poisson_counts(expected, u)
        to_date = by_reference_day(contributions(cells; stop = τ))
        eventual = by_reference_day(cells)[1:τ]
        lower = eventual_quantiles(prior, to_date, share, 0.025)
        upper = eventual_quantiles(prior, to_date, share, 0.975)
        lower .<= eventual .<= upper
    end
    return mean(reduce(hcat, hits); dims = 2)
end

rng = Xoshiro(2)
draws = [rand(rng, D + 1, T) for _ in 1:1000]
recent_coverage = coverage(prior, delay, expected, τ, draws)[(τ - 13):τ]
round.(extrema(recent_coverage); digits = 3)
(0.961, 0.991)

These are the lowest and highest coverage of the 95% intervals over the last 14 reference days. The coverage is above 0.95 because is fixed by the run rather than drawn from the prior, which is wider.

A delay whose hazard depends on the reporting day ​

Reports are often made less often on some days of the week. A discrete-time hazard expresses this. The probability of a report at delay given none before it depends on the day the report would be made [, ]. With a baseline by delay and an effect of reporting day ,

The delay distribution depends on the reference day, and so does the share  .

Normalising the masses and the operators that build them

The masses sum to one less the share of reports made after delay , so divides them by their sum and each sums to one over  . Derived computes the hazard from its two parts, Survival the product, Increments the mass at each delay, and Normalised the masses over their sum.

A TimeVarying kernel with Primary() indexing gives each reference day its own column of masses, and the same transpose returns . Here    on days 6 and 7 of each week and 0 otherwise.

julia
inverse_logit(b, e) = 1 / (1 + exp(-(b + e)))

# The delay convolution whose hazard is a baseline by delay `β` plus an
# effect `η` of the reporting day, given that reports end by the last delay.
function hazard_delay(β, η)
    hazard = Derived(inverse_logit, β, TimeVarying(η))
    mass = Normalised(Increments(1 - Survival(hazard)))
    return Convolution(TimeVarying(mass, Primary()))
end

β = [-2.0; fill(-0.8, D)]
η = [mod1(t, 7) >= 6 ? -1.5 : 0.0 for t in 1:(T + D)]
weekly = hazard_delay(β, η)
expected_weekly = contributions(
    weekly, infections; gain = ρ, indexing = Primary(), stop = T + D
)
cells_weekly = poisson_counts(expected_weekly, u)
to_date_weekly = by_reference_day(contributions(cells_weekly; stop = τ))
eventual_weekly = by_reference_day(cells_weekly)[1:τ]
F_weekly = reported_share(weekly, τ)
no_effect = reported_share(hazard_delay(β, zero(η)), τ)
two_digits(x) = round.(x[(τ - 6):τ]; digits = 2)
two_digits(F_weekly), two_digits(no_effect)
([0.85, 0.77, 0.66, 0.51, 0.4, 0.34, 0.12], [0.91, 0.87, 0.8, 0.71, 0.58, 0.39, 0.12])

These are the shares of reference days 44 to 50 with the weekly effect, then without it. Days 48 and 49 are days 6 and 7 of the week, so fewer reports are made on them, and the shares of the days before them are lower. A nowcast that ignores the weekly effect uses the shares without it.

julia
weekly_fits = map(
    (F_weekly, no_effect),
    ("Hazard by reporting day", "Hazard without the weekly effect")
) do share, label
    q = [
        eventual_quantiles(prior, to_date_weekly, share, p)[days]
            for p in (0.025, 0.5, 0.975)
    ]
    DataFrame(
        day = collect(days), lower = q[1], median = q[2], upper = q[3],
        eventual = eventual_weekly[days], series = label
    )
end

draw(
    data(reduce(vcat, weekly_fits)) * mapping(col = :series) * (
        mapping(:day, :lower, :upper) * visual(Band, alpha = 0.3) +
            mapping(:day, :median) * visual(Lines, linewidth = 2) +
            mapping(:day, :eventual) *
            visual(Scatter, color = :black, marker = :xcross)
    );
    axis = (xlabel = "Reference day", ylabel = "Reports"),
    figure = (size = (640, 300),)
)

The error of one report set is noisy, so the comparison uses the 1000 report sets of the previous section. The next result is the mean absolute error of the posterior median over the last 14 reference days, for the shares with and then without the weekly effect.

julia
# The mean absolute error of the posterior median of the last `n`
# reference days, over the report sets `draws` from `expected`.
function median_error(prior, share, expected, τ, draws; n = 14)
    errors = map(draws) do u
        cells = poisson_counts(expected, u)
        to_date = by_reference_day(contributions(cells; stop = τ))
        eventual = by_reference_day(cells)[1:τ]
        median = eventual_quantiles(prior, to_date, share, 0.5)
        mean(abs.(median .- eventual)[(τ - n + 1):τ])
    end
    return mean(errors)
end

errors = map(
    share -> median_error(prior, share, expected_weekly, τ, draws),
    (F_weekly, no_effect)
)
round.(errors; digits = 2)
(2.47, 3.14)

The shares with the weekly effect give the smaller error.

The gradient with respect to the delay ​

When the delay is estimated, its parameters maximise the likelihood of the observed cells. With given, the log-likelihood of the truncated triangle is

and the expected cells are the truncated expected triangle. The triangle is a function of through the operators, so its gradient comes from automatic differentiation.

julia
# The Poisson log-likelihood, up to a constant, of the observed cells
# given the expected cells of the same shape.
function log_likelihood(observed, expected)
    return sum(observed .* log.(expected) .- expected)
end

# The log-likelihood of the cells observed by day `τ` for the hazard
# baselines `β`, with expected eventual counts `λ`.
function delay_log_likelihood(β, η, λ, observed, τ)
    delay = hazard_delay(β, η)
    expected = contributions(delay, λ; indexing = Primary(), stop = τ)
    keep = observed .> 0
    return log_likelihood(observed[keep], expected[keep]) -
        sum(expected[.!keep])
end

λ = ρ .* infections[1:τ]
observed_weekly = contributions(cells_weekly; stop = τ)
ℓ(β) = delay_log_likelihood(β, η, λ, observed_weekly, τ)
gradient = ForwardDiff.gradient(ℓ, β)
round.(gradient[1:4]; digits = 2)
4-element Vector{Float64}:
  32.66
 -19.19
   4.66
   0.78

These are the derivatives of with respect to at the simulating values. They are the score of the delay model, which is zero in expectation at the simulating values and is what a gradient-based fit of follows.

Learning more ​

References ​

  1. M. Höhle and M. an der Heiden. Bayesian nowcasting during the STEC O104:H4 outbreak in Germany, 2011. Biometrics 70, 993–1002 (2014).

  2. J. F. Lawless. Adjustments for reporting delays and the prediction of occurred but not reported events. Canadian Journal of Statistics 22, 15–31 (1994).

  3. F. Günther, A. Bender, K. Katz, H. Küchenhoff and M. Höhle. Nowcasting the COVID-19 pandemic in Bavaria. Biometrical Journal 63, 490–502 (2021).