Skip to content

Three towns, step by step ​

Building the model ​

This page builds the model of the home page, a renewal model of an outbreak in three towns, one part at a time:

  • a renewal process in one town;

  • a reporting delay;

  • three towns mixed by a gravity coupling;

  • depletion of a finite population;

  • a fall in the reproduction number from day 50.

It then takes the gradient of the reports with respect to the reproduction number, and compares the run time with hand-written loops. The API overview defines the terms used.

julia
using ComposableRecurrences
using ComposableRecurrences: Depletion
using CairoMakie, AlgebraOfGraphics, DataFramesMeta
using ForwardDiff, Markdown

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

# The rows of `x` as named series in a long table, one row per day.
long(x, names; name = :town) = @chain DataFrame(permutedims(x), names) begin
    @transform(:day = 1:size(x, 2))
    stack(Not(:day); variable_name = name, value_name = :count)
end
small = (size = (600, 280),)

One town ​

In a renewal process the infections on a day are a weighted sum of earlier infections,

where is the number of infections on day . is the reproduction number, the gain of the Recurrence. is the weight of the generation interval on lag , the kernel, with lags. The infections before day 1 are the history. Here  ,   and the history is 10 infections on each of the six days before day 1.

julia
gi = [0.05, 0.2, 0.3, 0.25, 0.12, 0.08]
T = 75
one_seed = fill(10.0, 6)
one_town = Recurrence(gi)(fill(1.8, T); history = one_seed)

@chain DataFrame(day = 1:T, count = one_town) begin
    data(_) * mapping(:day, :count) * visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Infections"), figure = small)
end

Infections grow by about 20% a day.

A reporting delay ​

Reports are a share of infections, after a delay:

where is the number of reports on day . The weight of the delay on lag is , the kernel of the Convolution, with   lags from lag 0. The gain of the convolution is  . The delay reads the same history as the renewal process, one_seed.

julia
delay = Convolution([0.0, 0.1, 0.25, 0.3, 0.2, 0.1, 0.05])
one_report = delay(one_town; gain = 0.4, history = one_seed)

@chain long([one_town one_report]', ["Infections", "Reports"]; name = :series) begin
    data(_) * mapping(:day, :count, color = :series => "") *
        visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Daily count"), figure = small)
end

While infections grow, the reports of a day are about a quarter of its infections, less than , as they are a share of the smaller numbers of earlier days.

Three towns and a gravity coupling ​

Each town has its own infections , and a gravity coupling mixes the towns:

where weights town in town . is 1 when   and 0 otherwise. is the population of town and the distance between towns and . The gravity weight rises with the population of town and falls with its distance, and  . The towns are strata, and the history has infections in town A only.

julia
towns = ["A", "B", "C"]
pop = [60_000.0, 25_000.0, 10_000.0]
dist = [0.0 20.0 45.0; 20.0 0.0 30.0; 45.0 30.0 0.0]
gravity = [a == b ? 0.0 : pop[b] / dist[a, b]^2 for a in 1:3, b in 1:3]
K = 0.998 * [a == b for a in 1:3, b in 1:3] + 0.002 * gravity ./ sum(gravity; dims = 2)

seed = [fill(10.0, 1, 6); zeros(2, 6)]
coupled = Recurrence(gi; coupling = K)(fill(1.8, 3, T); history = seed)

@chain long(coupled, towns) begin
    data(_) * mapping(:day, :count, color = :town => "Town") *
        visual(Lines, linewidth = 2)
    draw(
        _; axis = (xlabel = "Day", ylabel = "Infections", yscale = log10),
        figure = small
    )
end

Towns B and C start from the infections that town A passes on, and then grow at about the rate of town A.

Depletion ​

In town A alone, the susceptible pool starts at the population and falls by the infections drawn from it. The default form of a Depletion, the hazard form, draws

where is the number of new infections before depletion and the hazard.

julia
one_depleted = Recurrence(gi; modifiers = (Depletion(pop[1]),))(fill(1.8, T); history = one_seed)

@chain DataFrame(day = 1:T, count = one_depleted) begin
    data(_) * mapping(:day, :count) * visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Infections"), figure = small)
end

Infections peak on day 36, and 73% of the town is infected by day 75.

An intervention ​

The reproduction number falls linearly from 1.8 on day 50 to 0.8 on day 56:

julia
intervention = [1.8 - clamp((t - 50) / 6, 0, 1) for t in 1:T]
one_intervened = Recurrence(gi)(intervention; history = one_seed)

@chain long([one_town one_intervened]', ["No intervention", "Intervention"]; name = :series) begin
    data(_) * mapping(:day, :count, color = :series => "") *
        visual(Lines, linewidth = 2)
    draw(
        _; axis = (xlabel = "Day", ylabel = "Infections", yscale = log10),
        figure = small
    )
end

The two runs are equal to day 50. With the intervention infections peak on day 53, when the reproduction number is 1.3, and fall by about 6% a day once it is 0.8.

Putting it all together ​

The full model has all five parts:

The susceptible pool of town starts at , and PerStratum(pop) gives each town its own population.

julia
R = [1.8 - clamp((t - 50) / 6, 0, 1) for _ in towns, t in 1:T]

renewal = Recurrence(gi; coupling = K, modifiers = (Depletion(PerStratum(pop)),))
infections = renewal(R; history = seed)
reports = delay(infections; gain = 0.4, history = seed)
round.(Int, vec(sum(infections; dims = 2)))
3-element Vector{Int64}:
 42940
 12145
  5398

The susceptible share of town on day is .

julia
susceptible = 1 .- cumsum(infections; dims = 2) ./ pop
@chain [
        ("Infections", "Daily count") => infections,
        ("Reports", "Daily count") => reports,
        ("Susceptible", "Susceptible share") => susceptible,
    ] begin
    map((((series, panel), x),) -> @transform(long(x, towns), :series = series, :panel = panel), _)
    reduce(vcat, _)
    data(_) * mapping(:day, :count => "", color = :series => "", row = :panel, col = :town) *
        visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day",), facet = (; linkyaxes = :rowwise))
end

Town A peaks on day 36, before the intervention. Towns B and C peak on day 50, against days 53 and 51 without the intervention. By day 75, 49% of town B and 54% of town C are infected, against 73% without it.

Changing the model ​

With the floored depletion form and imported infections added after depletion, the step is

where is the number drawn from the pool and the imported infections. Imports added after the Depletion are not drawn from the pool, unlike imports added before it. The change is one line of the model:

diff
-renewal = Recurrence(gi; coupling = K, modifiers = (Depletion(PerStratum(pop)),))
+renewal = Recurrence(gi; coupling = K, modifiers = (Depletion(PerStratum(pop), Floor()), Transform(+, TimeVarying(PerStratum(ι)))))

A hand-written loop of the changed model gives the same infections:

The hand-written loop
julia
using ComposableRecurrences: Floor, Transform
function loop_renewal(R, seed, gi, K, pop, ι)  # changed: imports passed in
    S, T = size(R)
    L, m = length(gi), size(seed, 2)
    V = promote_type(eltype(R), Float64)
    y = zeros(V, S, m + T)
    y[:, 1:m] .= seed
    pool = V.(pop)
    p = zeros(V, S)
    for t in 1:T
        for s in 1:S
            p[s] = sum(gi[i] * y[s, m + t - i] for i in 1:L)
        end
        for a in 1:S
            v = R[a, t] * sum(K[a, b] * p[b] for b in 1:S)  # changed
            drawn = max(max(pool[a] / pop[a], 0), 1e-6) * v  # changed: floored form
            pool[a] -= drawn  # changed
            y[a, m + t] = drawn + ι[a, t]  # changed: imports after depletion
        end
    end
    return y[:, (m + 1):end]
end

ι = zeros(3, T)
ι[3, 1:10] .= 5.0
extended = Recurrence(
    gi; coupling = K,
    modifiers = (Depletion(PerStratum(pop), Floor()), Transform(+, TimeVarying(PerStratum(ι))))
)
maximum(abs, extended(R; history = seed) .- loop_renewal(R, seed, gi, K, pop, ι))
2.0463630789890885e-12

Gradients ​

The loss is the sum of the reports over towns and days, and its gradient is taken with respect to the reproduction number of every town on every day. Each backend is called through DifferentiationInterface. Mooncake and Enzyme run the rule of each operator, and ForwardDiff differentiates the forward code. Enzyme needs runtime activity here, as the depletion holds the global array pop; the Enzyme extension page states when it is needed.

julia
using ADTypes: AutoEnzyme, AutoForwardDiff, AutoMooncake
import DifferentiationInterface as DI
import Enzyme, Mooncake

reports_of(R) = delay(renewal(R; history = seed); gain = 0.4, history = seed)
loss(R) = sum(reports_of(R))
enzyme = AutoEnzyme(;
    mode = Enzyme.set_runtime_activity(Enzyme.Reverse),
    function_annotation = Enzyme.Const,
)
backends = (AutoForwardDiff(), AutoMooncake(; config = nothing), enzyme)
∂R, ∂R_mooncake, ∂R_enzyme = (DI.gradient(loss, b, R) for b in backends)
isapprox(∂R_mooncake, ∂R; atol = 1.0e-8) && isapprox(∂R_enzyme, ∂R; atol = 1.0e-8)
true
julia
round.(vec(sum(∂R; dims = 2)); digits = 1)
3-element Vector{Float64}:
 17537.3
 12951.4
  4718.1
julia
@chain long(∂R, towns) begin
    data(_) * mapping(:day, :town, :count => "∂ reports / ∂R") * visual(Heatmap)
    draw(_; axis = (xlabel = "Day", ylabel = "Town"))
end

The three gradients agree to an absolute 1e-8. The derivative is largest for town A around its peak, and for towns B and C in the days before the intervention. It is zero on the last day, as the delay has no weight on lag 0 and the infections of that day are not yet reported.

Performance ​

The timed model is the three-town model over 200 days, with a generation interval of 20 lags. The figure gives its minimum time and that of three hand-written versions of the same model: a preallocated loop, a loop that copies its window at every step, and accumulate over a NamedTuple state.

julia
performance_plot("naive vs package")

Performance compares the model of every tutorial with a hand-written loop in the same way.