Skip to content

Operators ​

This page gives the equations of a step of each operator, the forms of a call and how a run reads its inputs, its history and its state. The API overview defines the terms used.

julia
using ComposableRecurrences
using ComposableRecurrences: exponential_history, Depletion, Resume,
    Pressure, Trace

A step ​

Recurrence and Convolution compute their outputs one step at a time, with time the integer step counted from 1 in the model's time unit. Each series run side by side, such as one per town, is a stratum. A convolution has no coupling and no modifiers.

One recurrence step and one convolution output

A call runs from step start to step stop. For each step of that range, a recurrence computes

and a convolution computes

where is the output, one entry per stratum, the input of a convolution and the weighted sum of past outputs. The kernel has weight on lag over lags, is the coupling, the gain and the add input. The value before the modifiers , which act in order, is , and multiplies element by element. For a recurrence the history holds the outputs before start, and for a convolution the inputs before time 1. Where the coupling acts writes the step stratum by stratum, and Order writes the modifiers' part.

Building an operator ​

Each operator is built once from a kernel and then called like a function.

julia
delay = Convolution([0.0, 0.1, 0.25, 0.3, 0.2, 0.1, 0.05])
delay([10.0, 20.0, 30.0])
3-element Vector{Float64}:
 0.0
 1.0
 4.5

The constructors are Recurrence(kernel; lags, step, coupling, modifiers) and Convolution(kernel; lags, step, method). lags and width apply when the kernel is a delay distribution. The keyword method sets how a convolution sums its lags: Direct(), the default, sums them one by one, and FFTMethod() uses a fast Fourier transform. The transform is worth asking for with a long kernel, of hundreds of lags, over a long series.

An operator, modifier or shape wrapper displays in the REPL as one line with its size and parts, such as Convolution(7 lags) for delay. repr and string keep the constructor form.

Calls ​

A recurrence renewal takes its gain first, and a convolution delay takes its input first and its gain as a keyword.

CallReturns
renewal(gain; history, add, start, stop)the run, a vector or strata × time
delay(x; gain, add, history, start, stop)an array shaped like x
renewal(gain; history, record = (Resume(), Pressure(), Trace()))(; y, state, pressure, trace), with the State to resume from
ComposableRecurrences.contributions(delay, x; ...)each lag's term before the sum, with a column per output time
ComposableRecurrences.contributions(delay, x; indexing = Primary(), ...)the same terms with a column per input time, zero where they arrive after stop
ComposableRecurrences.contributions(K; start, stop)the entries of a table K held by input time, cut at stop as those terms are
delay'(x; tail, start, stop)the transpose, which reads x forward from each time
reverse(renewal)(gain; tail, add, start, stop, record)the run backwards in time, each output from the outputs after it
ComposableRecurrences.growth(renewal, gain; at)(; rate, profile), the rate and the profile over strata of the exponential history the step continues
ComposableRecurrences.growth_gain(renewal, rate; at)the scale of the gain at which the recurrence grows at rate
pressure(renewal, y; history, start) recomputed from y; y over it is the gain as run
ComposableRecurrences.window_sums(y, ends; dims)the sums of y over windows ending at ends
ComposableRecurrences.window_sums(y, starts, stops; dims)the sums of y over windows from starts to stops, which may leave gaps or overlap
ComposableRecurrences.kernel_weights(TimeVarying(w, Primary()), n)the weights a computed kernel w gives cohorts 1 to n

The keyword stop defaults to the common length of the time-indexed inputs, and inputs of different lengths without a stop are an error. An operator can be built inside a model, once for each draw of its parameters: its constructor's checks read only types, so building it adds no measurable cost to a call or a gradient. A draw that makes a checked value NaN, such as a share or a pool's start, passes the call's checks and gives a NaN output, so a sampler can reject it rather than stop. Without a gain, a recurrence takes a gain of 1. A call's record takes the markers Resume(), Pressure() and Trace(), alone or in a tuple. The call then returns y and a field for each marker, always in the order state, pressure, trace. The field pressure is the pressure of each step, shaped like y. The field trace holds one matrix per modifier that records something, with a column per step. A modifier whose state never changes records nothing and is left out. Pass the modifiers as a named tuple, as modifiers = (; pool, imports), and trace is keyed by those names, as trace.pool. A part the call does not ask for is neither built nor differentiated, and the return type follows from the types of the arguments.

julia
pool = Depletion(100.0)
named = Recurrence([0.2, 0.5, 0.3]; modifiers = (; pool))
out = named(fill(1.3, 10); history = ones(3), record = (Pressure(), Trace()))
size(out.trace.pool), size(out.pressure)
((3, 10), (10,))

The transpose sums forward in time from each . For a reporting delay over lags and data up to time , the share of the infections at time reported by is

and delay'(ones(T)) returns . For a delay whose weights sum to 1, it is 1 up to    and falls to at .

A recurrence is a convolution of its own outputs ​

A recurrence reads its own past outputs, so a recurrence with kernel is a convolution of its outputs with shifted by one lag, times the gain :

where is the output at time , the kernel weight on lag , and the convolution kernel vcat(0, k). A recurrence's value cannot depend on itself in the same step, so its first weight is on the previous value. A convolution can weight the input at the current time, as a reporting delay of zero does. Both are written as the quantity is usually written, so a generation interval or a delay goes in unchanged.

julia
k = [0.2, 0.5, 0.3]
gain = fill(1.3, 10)
seed = [1.0, 1.0, 1.0]
y = Recurrence(k)(gain; history = seed)
p = Convolution(vcat(0, k))(y; history = seed)
y ≈ gain .* p
true

The same identity recovers any quantity inside a step from the outputs. An operator returns its outputs and what record asks for, and any other intermediate is recomputed in this way.

Time base ​

Every time-indexed input is read at absolute time , counted from 1. This holds for gain, add, a convolution's x and every TimeVarying kernel, coupling or parameter. Every time-indexed input must cover stop. start and stop choose which times are computed, not how the inputs are read. A run over a window of longer time-varying inputs therefore needs no slicing: the inputs are passed whole with start and stop set. A call from start = 4 reads gain[4] at its first step, and the output has stop - start + 1 entries. With the history value at time , that first step is

julia
gain = collect(range(1.5, 0.8; length = 10))
r = Recurrence(k)
y_late = r(gain; history = seed, start = 4)
length(y_late), y_late[1] ≈ gain[4] * sum(k .* reverse(seed))
(7, true)

A resumed call, a later start and a forecast past the data all read the same column for the same time, so a series built in sections equals one built whole.

History and state ​

The history holds the values before start, oldest first. The recursion reads the last of them, with at least and at least the depth of each part, and zeros stand for any that are missing. Without a history the run starts from zeros. Their strata are those of a strata × time input, or else those of one group of the first modifier whose groups hold more than one value. A Depletion whose flows move between named pools is such a modifier. For a single stratum a number is one value before start, so history = 1.0 is history = [1.0]. A modifier's Init reads the whole history, so a modifier can set its starting state from more than values.

A State holds everything the next step reads: the last outputs, the state of each modifier and the next time. A call that resumes from a State therefore returns the values that one call over both ranges returns, which is how a forecast continues a run.

julia
modifiers = (Depletion(50.0; pools = (S = 50.0 - sum(seed),)),)
r = Recurrence(k; modifiers)
whole = r(fill(1.6, 20); history = seed)
fit, state = r(fill(1.6, 20); history = seed, stop = 12, record = Resume())
forecast = r(fill(1.6, 20); state)
whole ≈ vcat(fit, forecast)
true

The pool in the State carries the depletion over, so the forecast starts from the pool the fit left. A modifier parameter read from past outputs, Recent, deepens the window past , and the State keeps the deeper window.

A run in chunks, each resumed from the state the one before returned, is the single run. For a run from the history over the times to , and cuts    ,

where is the state the chunk ending at returns and the brackets join along time. This holds for the outputs, the pressure, the traces, the last state and their gradients, on host and device arrays. Each chunk reads its inputs at absolute times, so it takes the inputs of the single run and its own stop. An input for one chunk alone, such as the noise of one step, is a number or a PerStratum parameter. A call with stop = start - 1 runs no step and returns the state it starts from, the first state of a stepwise loop.

Between chunks, select(state, strata) returns the state whose stratum is stratum = strata[i] of the one given:

where are the last outputs the state holds and each modifier's state. A stratum may be dropped, repeated or moved. The strata of a group share one state, so they are selected together, value by value. With each = n, strata names blocks of consecutive strata. vcat(state, more...) joins states at the same time along the strata, so a selection can read from several.

julia
using ComposableRecurrences: select
pool = Depletion(PerStratum([50.0, 80.0, 60.0]))
r = Recurrence(k; modifiers = (pool,))
R = fill(1.6, 3, 20)
first_part = r(R; history = ones(3, 3), stop = 12, record = Resume())
kept = [3, 1]
r_kept = Recurrence(k; modifiers = (Depletion(PerStratum([60.0, 50.0])),))
rest = r_kept(R[kept, :]; state = select(first_part.state, kept))
rest ≈ r(R; state = first_part.state)[kept, :]
true

Seeding ​

A recurrence needs values before its first step, in one of two places.

  • Before time 1, as history with start = 1. The run starts at time 1, so the gain and other inputs cover the run only.

  • At times 1 to , as history with start = m + 1. The inputs then cover the seed times too, which a Primary kernel needs, since only times from 1 have a column.

exponential_history builds a seed that grows at a fixed rate, as at the start of an epidemic. The rate at which a recurrence grows under a gain comes from growth. For strata that mix it also returns the profile over strata to scale the seed by. A seed drawn from a finite pool should leave the pool smaller; the pools keyword of Depletion does this.

julia
seed = exponential_history(2.0, 0.1, length(k))
gain = fill(1.2, 13)
before = Recurrence(k)(gain[4:end]; history = seed)
after = Recurrence(k)(gain; history = seed, start = 4)
before ≈ after
true

The two placements give the same run whenever the inputs over the seed times are not read.

What a call returns ​

A recurrence returns the run alone, from start to stop. With include_history = true it returns the seed followed by the run, which is the whole series a later operator should see. The pressure and each trace then have zero columns over the seed, so they share the output's times, and the returned state is unchanged. It needs history, not state. A view passed as the history is differentiable on every backend.

julia
whole = Recurrence(k)(gain; history = seed, include_history = true)
whole == vcat(seed, Recurrence(k)(gain; history = seed))
true

A convolution's history holds inputs before time 1, which it reads but does not return.

A delay after a recurrence therefore takes the seed as its own history. Delaying the seed and run together and dropping the seed times gives the same reports.

julia
delay = Convolution([0.1, 0.4, 0.3, 0.2])
infections = Recurrence(k)(gain; history = seed)
reports = delay(infections; history = seed)
joined = Recurrence(k)(gain; history = seed, include_history = true)
reports ≈ delay(joined)[(length(seed) + 1):end]
true

The seed is passed as history when the reports cover the run only, and joined in front when they cover the seed times too.

Output number type ​

The output's number type is the promotion of the number types of every input and field. So Float32 inputs give a Float32 output, and dual numbers pass through any slot. With integer and Bool inputs and fields alone and no modifiers, the output keeps that integer type promoted with Int. A signed or Bool running total then has the eltype that cumsum gives. Otherwise it is the float type. A user coupling whose pressure is not an integer needs a float input.

A call takes one of several loops, chosen from its kernel, coupling, modifiers and number of strata, and they add the same terms in different orders. A stratum computed alone and the same stratum computed among others therefore agree to rounding, a relative difference of about in Float64, and not bit for bit.

Time-series processes ​

A time-series process, such as a random walk or an autoregression, builds a series from innovations . Each is a recurrence or a convolution: a recurrence takes the innovations as add, and a convolution as its input. As a latent process, one that is not observed, it can drive a gain, such as the reproduction number through its logarithm.

julia
ϵ = [0.5, -0.25, 0.125, 0.25, -0.5]
Recurrence([1.0])(; history = [0.0], add = ϵ)
5-element Vector{Float64}:
 0.5
 0.25
 0.375
 0.625
 0.125
ProcessMathsCode
Random walk  Recurrence([1.0])(; history = [z0], add = ϵ)
Autoregression, AR(p)  Recurrence(φ)(; history, add = ϵ)
Autoregression with a coefficient that changes over time  Recurrence(TimeVarying(reshape(φ, 1, :)))(; history, add = ϵ)
Moving average, MA(q)  Convolution(vcat(1, θ))(ϵ)

These calls have no gain, and the run is as long as ϵ. reshape(φ, 1, :) makes a kernel of one lag with a column per step. A recurrence's own weighted sum is a convolution of its outputs too, as above shows.