Skip to content

Latent processes driving R_t ​

Introduction ​

A smoothly changing reproduction number is often a latent process on the log scale. Random walks, AR and MA processes are recurrences or convolutions of innovations, and they can drive a renewal process.

Packages used ​

julia
using ComposableRecurrences
using ComposableRecurrences: Transform, Depletion, Flow, Hazard, Truncate, Derived,
    Recent
using CairoMakie, AlgebraOfGraphics, DataFramesMeta
using ForwardDiff
using Random

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

Three processes from one set of innovations ​

where is each process's value on day and the innovation on that day, drawn with standard deviation 0.1. Here the AR coefficients are   and  , and the MA coefficients   and  . Each recurrence has the AR coefficients as its kernel and takes the innovations as add. The MA(2) process is a Convolution of the innovations with the kernel . With no gain the call runs over the length of add.

julia
T = 100
ϵ = 0.1 .* randn(Xoshiro(1), T)

rw = Recurrence([1.0])(; history = [0.0], add = ϵ)
ar = Recurrence([0.6, 0.3])(; history = zeros(2), add = ϵ)
ma = Convolution([1.0, 0.8, 0.4])(ϵ)

@chain DataFrame("day" => 1:T, "Random walk" => rw, "AR(2)" => ar, "MA(2)" => ma) begin
    stack(Not(:day); variable_name = :series, value_name = :value)
    data(_) * mapping(:day, :value, color = :series, layout = :series) *
        visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Value"))
end

The random walk wanders furthest, because every innovation persists. The AR(2) process follows it loosely: its coefficients sum to 0.9, so innovations decay. The MA(2) process stays near zero, because it forgets each innovation after two days.

A time-varying AR coefficient ​

where is the AR coefficient on day , falling in equal steps from 0.95 on day 1 to 0.5 on day 100, and the innovations above. The coefficient can be a TimeVarying kernel, one column per day. With a single lag it can also be the gain on the unit kernel. The gain scales the lag sum before the add input is added, so both forms give the same process. The comparison holds at 0.95 throughout.

julia
φ = range(0.95, 0.5; length = T)
tvar_kernel = Recurrence(TimeVarying(reshape(collect(φ), 1, :)))(; history = [0.0], add = ϵ)
tvar_gain = Recurrence([1.0])(φ; history = [0.0], add = ϵ)
fixed = Recurrence([0.95])(; history = [0.0], add = ϵ)

@chain DataFrame(
    "day" => 1:T, "Fixed at 0.95" => fixed, "Falling from 0.95 to 0.5" => tvar_kernel
) begin
    stack(Not(:day); variable_name = :series, value_name = :value)
    data(_) * mapping(:day, :value, color = :series) * visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Value"))
end

The two agree at first. As the coefficient falls, innovations fade sooner and the process stays nearer zero. The kernel and gain forms agree to round-off.

An AR(1) process as the log reproduction number ​

where is the log reproduction number, an AR(1) process, the reproduction number on day and the number of infections on day . The reproduction number is the gain of the renewal, the innovations are new draws with standard deviation 0.05, and is the generation interval on lag . Here   and there are   lags. Each run starts from ten infections on each of the five days before day 1. An AR(1) process with a coefficient below one reverts to zero, so stays near 1. Twenty draws of the innovations give twenty paths of and their infections.

julia
renewal = Recurrence([0.1, 0.3, 0.3, 0.2, 0.1])
rng = Xoshiro(2)
@chain 1:20 begin
    map(_) do i
        log_R = Recurrence([0.95])(; history = [0.0], add = 0.05 .* randn(rng, T))
        R = exp.(log_R)
        DataFrame(
            "day" => 1:T, "draw" => i, "Reproduction number" => R,
            "Infections" => renewal(R; history = fill(10.0, 5))
        )
    end
    reduce(vcat, _)
    stack(Not([:day, :draw]); variable_name = :quantity, value_name = :value)
    data(_) * mapping(:day, :value, group = :draw => nonnumeric, layout = :quantity) *
        visual(Lines, linewidth = 1, alpha = 0.5)
    draw(_; axis = (xlabel = "Day", ylabel = "Value"), facet = (; linkyaxes = :none))
end

stays between 0.57 and 1.84 across the twenty draws. Small differences in compound, so some outbreaks die out and others grow large.

Transmission that saturates with incidence ​

People may reduce their contacts when incidence is high. A saturating form (Capasso and Serio 1978) caps daily infections below :

where is the value before the modifiers on day , the only modifier, a Transform, and the level daily infections stay below. The generation interval and the infections are as in the previous model. Here the gain is constant,   . Each run starts from five infections on the day before day 1. With   infections settle at  , which is 33.3 for   and 100 for  .

julia
gi = [0.1, 0.3, 0.3, 0.2, 0.1]
R = fill(1.5, T)
saturate(v, κ) = v / (1 + v / κ)

@chain [100.0, 300.0] begin
    map(_) do κ
        y = Recurrence(gi; modifiers = (Transform(saturate, κ),))(R; history = [5.0])
        DataFrame(day = 1:T, series = "κ = $(Int(κ))", count = y)
    end
    reduce(vcat, _)
    vcat(_, DataFrame(day = 1:T, series = "No response", count = Recurrence(gi)(R; history = [5.0])))
    data(_) * mapping(:day, :count, color = :series) * visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Infections (log scale)", yscale = log10))
end

The total infections over the 100 days depend smoothly on and :

where   is the number of days. ForwardDiff gives the gradient of at   and  . Each panel varies one parameter and holds the other at that point. The dashed line in each panel is the tangent the gradient gives.

julia
function total_infections(x)
    modifiers = (Transform(saturate, x[1]),)
    return sum(Recurrence(gi; modifiers)(fill(x[2], T); history = [5.0]))
end
line_names = ["Total infections", "Tangent from the gradient"]
function tangents(f, x0, names, grids)
    grad = ForwardDiff.gradient(f, x0)
    frames = map(eachindex(x0)) do i
        xs = collect(grids[i])
        curve = [f(setindex!(copy(x0), x, i)) for x in xs]
        tangent = f(x0) .+ grad[i] .* (xs .- x0[i])
        DataFrame(
            parameter = names[i], value = vcat(xs, xs), total = vcat(curve, tangent),
            line = repeat(line_names; inner = length(xs))
        )
    end
    return reduce(vcat, frames)
end
@chain tangents(total_infections, [100.0, 1.5], ["κ", "R"], [60:5:140, 1.3:0.02:1.7]) begin
    data(_) * visual(Lines, linewidth = 2) * mapping(
        :value, :total; linestyle = :line => sorter(line_names) => "", layout = :parameter
    )
    draw(
        _; axis = (xlabel = "Parameter value", ylabel = "Total infections"),
        facet = (; linkxaxes = :none)
    )
end

Each tangent touches its curve at the point, so the gradient matches the slope.

Feedback from recent incidence ​

The saturating response reacts to the current day only. A response to the last week's incidence is built from existing modifiers. The parameter Recent reads the recurrence's own past outputs, Derived maps them, and any modifier parameter takes the result. The response scales the new infections before depletion, and a Depletion of a pool of then draws from it. The same source can drive ring vaccination, removing doses from the susceptible pool in proportion to recent cases:

where is the number of new infections before depletion and that number after the response , a Transform. The susceptible pool after day is , and the ring vaccination doses on day , half the last week's infections, are . The depletion is the second modifier , which draws from the pool by the hazard form. Here  , the response strength is   and the pool starts at  . The models without a response take  , and those without ring vaccination take  .

julia
N = 5_000.0
λ = 10.0
response = Transform(*, Derived(exp, -λ / N * Recent(7)))
ring = Depletion(N, Hazard(), Flow(:S => 0, 0.5 * Recent(7); form = Truncate()))
feedback = [
    "Depletion only" => (Depletion(N),),
    "Response to the last week" => (response, Depletion(N)),
    "Ring vaccination" => (ring,),
    "Both" => (response, ring),
]
@chain feedback begin
    map(_) do (name, modifiers)
        y = Recurrence(gi; modifiers)(R; history = [5.0])
        DataFrame(day = 1:T, model = name, count = y)
    end
    reduce(vcat, _)
    data(_) * mapping(:day, :count, color = :model) * visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Infections"))
end

With depletion alone infections peak at 111 on day 37, and the response lowers the peak to 23, ring vaccination to 36 and both together to 16.

The reverse-mode rule sends gradients back through the outputs Recent reads, so Mooncake and Enzyme follow the feedback. ForwardDiff gives the gradient of the total infections of the response-and-depletion model at   and  .

julia
function total_with_response(x)
    modifiers = (Transform(*, Derived(exp, -x[1] / N * Recent(7))), Depletion(N))
    return sum(Recurrence(gi; modifiers)(fill(x[2], T); history = [5.0]))
end
@chain tangents(total_with_response, [λ, 1.5], ["λ", "R"], [0:1:20, 1.3:0.02:1.7]) begin
    data(_) * visual(Lines, linewidth = 2) * mapping(
        :value, :total; linestyle = :line => sorter(line_names) => "", layout = :parameter
    )
    draw(
        _; axis = (xlabel = "Parameter value", ylabel = "Total infections"),
        facet = (; linkxaxes = :none)
    )
end

A stronger response lowers the total, and a higher raises it.

Performance ​

Each bar times an AR(2) process over 200 days, against a preallocated hand-written loop.

julia
performance_plot("latent processes")

References ​

  • Capasso and Serio (1978), "A generalization of the Kermack-McKendrick deterministic epidemic model", Mathematical Biosciences 42, 43-61, 10.1016/0025-5564(78)90006-8

Learning more ​

  • API overview: a map of every operator, coupling and modifier.

  • Public API: every public name with its docstring.