Skip to content

Forecasting by continuing a run from its state ​

Introduction ​

A forecast continues a renewal process past the last day with data. This tutorial runs a renewal process to day 50, keeps the state of the run, and continues from it to day 80 in a second call.

Packages used ​

julia
using ComposableRecurrences
using ComposableRecurrences: Resume
using CairoMakie, AlgebraOfGraphics, DataFramesMeta

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

Model ​

The renewal process is

where is the number of infections on day , the reproduction number and the weight of the generation interval on lag , with   lags. Day depends on the past only through . A run to day therefore continues from its last infections and the index of the next day,  . A State holds both.

A call with stop = τ and record = Resume() returns the infections to day and the state. A call with that state returns the infections from day  . Both calls take the whole of , as every call reads its inputs at the day of the model, counted from 1.

julia
gi = [0.1, 0.3, 0.3, 0.2, 0.1]
T = 80
R = [t <= 30 ? 1.4 : t <= 50 ? 0.9 : 1.2 for t in 1:T]
τ = 50

# The run of `renewal` to day `τ` and its continuation to the end of `R`.
function run_then_forecast(renewal, R, history, τ)
    observed, state = renewal(R; history, stop = τ, record = Resume())
    return observed, renewal(R; state)
end

renewal = Recurrence(gi)
observed, forecast = run_then_forecast(renewal, R, [5.0], τ)
vcat(observed, forecast) ≈ renewal(R; history = [5.0])
true

The two calls together equal one call over all 80 days to rounding error.

julia
table = DataFrame(
    day = 1:T, value = vcat(observed, forecast),
    part = [t <= τ ? "Run to day 50" : "Forecast" for t in 1:T]
)
draw(
    data(table) * mapping(:day, :value, color = :part => "") *
        visual(Lines, linewidth = 2) +
        mapping([τ + 0.5]) * visual(VLines, color = :grey, linestyle = :dash);
    axis = (xlabel = "Day", ylabel = "Infections")
)

Infections are 27 on day 50, the last day of the first call, and the forecast rises from 34 on day 51 to 203 on day 80.

Performance ​

The timed model is a renewal process run to day 100 and continued from its state to day 200, with a generation interval of 20 lags. The figure gives its minimum time and that of a preallocated hand-written loop of the same model.

julia
performance_plot("forecasting")

Learning more ​