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. It is for a reader who needs the exact meaning of a call, and the API overview defines the terms used.
using ComposableRecurrences
using ComposableRecurrences: exponential_history, Depletion, Resume,
Pressure, TraceA step
Recurrence and Convolution compute their outputs one step at a time, with time the integer step
A call runs from step start to step stop. For each step
and a convolution computes
where add input. The value before the modifiers 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.
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.5The output has one entry for each input time.
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, with the FFTW extension loaded.
How an operator displays
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.
| Call | Returns |
|---|---|
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.advance!(renewal, state, gain; add, stop, record) | (; y, state) as renewal(gain; state, record = Resume()) returns, run in the buffer of state, which it uses up |
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) | 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. 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.
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 trace is read by the name pool, and both fields have an entry for each of the 10 steps.
Building an operator inside a model
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. A part the call does not ask for is neither built nor differentiated, and the return type follows from the types of the arguments.
The transpose sums forward in time from each
and delay'(ones(T)) returns
A recurrence is a convolution of its own outputs
A recurrence reads its own past outputs, so a recurrence with kernel
where 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.
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 .* ptrueThe 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 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
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 depth of each part, and zeros stand for any that are missing. Without a history the run starts from zeros.
The strata and shape of a history
The strata of a history 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 vector is the values of one series, so one value before start for each of history = PerStratum(x), which is history = reshape(x, S, 1). A modifier's Init reads the whole history, so a modifier can set its starting state from more than
A State holds everything the next step reads: the last State therefore returns the values that one call over both ranges returns, which is how a forecast continues a run.
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)trueThe 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 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
where 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 strata[i] of the one given:
where each = n, strata names blocks of vcat(state, more...) joins states at the same time along the strata, so a selection can read from several.
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, :]trueA method that keeps its own state vector, such as a filter from another package, reads a State as one vector and builds one back. The vector vec(state) holds each stratum's outputs, oldest first, then each modifier's state. The call State(like, x; t) returns the state of that shape whose next step is at time t. Time is absolute in every call and the vector holds none, so the method passes it.
state = first_part.state
x = vec(state)
again = ComposableRecurrences.State(state, x; t = state.t)
length(state), vec(again) == x(12, true)A resumed call leaves the state it is given as it was: it copies the state's outputs into a new buffer, runs there and returns a new state. The call advance!(r, state, gain) runs the same steps in the buffer the state already has and returns the same outputs and state. A loop of single steps then copies no history. The state passed is used up, and the loop carries on from the one returned.
using ComposableRecurrences: advance!
function stepwise(r, R, state, n)
y = zeros(size(R, 1), n)
for t in 1:n
out = advance!(r, state, R)
y[:, t] = out.y
state = out.state
end
return y, state
end
start = r(R; history = ones(3, 3), stop = 0, record = Resume()).state
y, last_state = stepwise(r, R, start, 20)
y ≈ r(R; history = ones(3, 3))trueParticle filtering of a renewal model with LowLevelParticleFilters.jl runs a particle filter on a recurrence, a particle at a time and with the particles as strata.
Seeding
A recurrence needs values before its first step, in one of two places.
Before time 1, as
historywithstart = 1. The run starts at time 1, so the gain and other inputs cover the run only.At times 1 to
, as historywithstart = m + 1. The inputs then cover the seed times too, which aPrimarykernel 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.
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 ≈ aftertrueThe 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.
whole = Recurrence(k)(gain; history = seed, include_history = true)
whole == vcat(seed, Recurrence(k)(gain; history = seed))trueA 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.
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]trueThe 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.
Integer inputs
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.
Agreement between loops
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 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 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.
ϵ = [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.125The output is the running sum of ϵ, a random walk from 0.
| Process | Maths | Code |
|---|---|---|
| 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