Three towns, step by step
Building the model
The example is an outbreak in three towns. People travel between the towns, each town has a finite population, infections are reported after a delay, and an intervention lowers transmission from day 50.
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
Each infection causes new infections some days later. A renewal process models this: new infections are a weighted sum of earlier infections,
where Recurrence takes it as its gain, the number it multiplies each day's weighted sum by.
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, so the curve bends upwards.
A reporting delay
Infections are not observed directly. Reports are a share
where one_seed, 10 infections on each of the six days before day 1. Convolution, and a delay of zero days is lag 0.
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, each day's reports come from the smaller numbers of earlier days, so they are about a quarter of that day's infections.
Three towns and a gravity coupling
People travel between towns, so infections in one town cause infections in the others. Each town now has its own infections
where
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 town A passes on, so they start lower. They then grow at about the same rate as town A.
Depletion
Each infection removes a person from the pool of people who can be infected. A finite pool stops an outbreak growing without limit. In town A alone, the susceptible pool
where
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 rise as before, then peak on day 36 and decline as the pool runs down. About 73% of the town is infected by day 75.
An intervention
An intervention such as distancing lowers the reproduction number. From day 50 it falls from 1.8 to 0.8 over six days:
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 match until day 50. Infections peak on day 53, when the reproduction number has fallen to 1.3. Once the reproduction number is below one, infections fall by about 6% a day.
Putting it all together
The finished model joins the four steps for three towns:
The susceptible pool PerStratum(pop) gives each town its own population.
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
5398The susceptible share of town
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, because its susceptible pool runs down. The intervention brings the peaks of towns B and C forward to day 50, from days 53 and 51 without it. About 49% of town B and 54% of town C are infected, against 73% without the intervention.
Changing the model
Switching to the floored depletion form and adding imported infections after depletion changes one line of the operator version. The step becomes
where Depletion do not draw down the pool, unlike imports added before it.
-renewal = Recurrence(gi; coupling = K, modifiers = (Depletion(PerStratum(pop)),))
+renewal = Recurrence(gi; coupling = K, modifiers = (Depletion(PerStratum(pop), Floor()), Transform(+, TimeVarying(PerStratum(ι)))))The same change in the hand-written loop
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-12Gradients
The gradient of all reports with respect to every town's reproduction number on every day comes from any backend through DifferentiationInterface. Mooncake and Enzyme differentiate through the package's reverse rule, while ForwardDiff differentiates the forward code. Enzyme needs runtime activity here because the depletion holds the global array pop; the Enzyme extension page says when.
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)trueround.(vec(sum(∂R; dims = 2)); digits = 1)3-element Vector{Float64}:
17537.3
12951.4
4718.1@chain long(∂R, towns) begin
data(_) * mapping(:day, :town, :count => "∂ reports / ∂R") * visual(Heatmap)
draw(_; axis = (xlabel = "Day", ylabel = "Town"))
end
Total reports are most sensitive to town A's reproduction number around its peak. The reproduction numbers of B and C matter most just before the intervention, when their own outbreaks are largest. Sensitivity fades after the intervention and is zero on the last day, whose infections are not yet reported.
Performance
The chart compares the time the operators take with three hand-written versions of the same model. Each bar times the three-town model over 200 days with a 20-day generation interval. The hand-written versions are a preallocated loop, a loop that copies its window every step, and accumulate over a NamedTuple state.
performance_plot("naive vs package")
The benchmarks page compares each tutorial's model with a hand-written loop of it in the same way.