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.
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 Recurrence.
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
where Convolution, with one_seed.
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
Three towns and a gravity coupling
Each town
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 that town A passes on, and then grow at about the rate of town A.
Depletion
In town A alone, the susceptible pool Depletion, the hazard form, draws
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 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:
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 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. 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 Depletion are not drawn from the pool, unlike imports added before it. The change is one line of the model:
-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
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 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.
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
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.
performance_plot("naive vs package")
Performance compares the model of every tutorial with a hand-written loop in the same way.