Skip to content

Shapes and couplings ​

This page states which shape each coefficient takes, how a delay distribution becomes a kernel, and where a coupling acts in a step. It is for a reader choosing how a coefficient varies over strata and time, and the API overview defines the terms used.

julia
using ComposableRecurrences
using LinearAlgebra: I

Slots and shapes ​

An operator reads numbers of two kinds.

  • Data change from call to call: the inputs, the history, gain, add and the outputs.

  • Coefficients belong to the operator and are set when it is built: its kernel, its coupling and its modifiers' parameters.

A slot is a place in an operator that holds a coefficient. There are three kinds: a kernel, of a Recurrence or a Convolution, a coupling and a modifier parameter. The name is that of a slot in a form: the operator fixes where a number goes, and the model chooses what goes there.

text
Recurrence(k; coupling = K, modifiers = (Depletion(N),))
           |             |                         |
        kernel       coupling             modifier parameter

A shape is how a coefficient varies across strata and time, and so how many numbers fill its slot. The name is that of an array's shape, its size along each axis.

  • A plain array has only the slot's own axes, so one set of numbers serves every stratum and time. These are the lags for a kernel, S × S for a coupling and one value for a modifier parameter.

  • A wrapper adds axes: PerStratum a leading strata axis, Pairwise leading S × S axes and TimeVarying a trailing time axis.

Slot and shape are separate because one slot takes many shapes. The kernel slot of a Recurrence holds one kernel for every stratum, one per stratum or one per step. On two strata, the last output of each shows the difference: the per-stratum kernel gives the strata different values, and the per-step kernel changes the value over time.

julia
g = [0.5, 0.3, 0.2]
x = fill(1.1, 2, 10)
h = ones(2, 3)
shared = Recurrence(g)
per_stratum = Recurrence(PerStratum([0.5 0.3 0.2; 0.6 0.3 0.1]))
per_step = Recurrence(TimeVarying([g .* (1 + 0.05t) for t in 1:10]))
[r(x; history = h)[:, end] for r in (shared, per_stratum, per_step)]
3-element Vector{Vector{Float64}}:
 [1.8149830919279304, 1.8149830919279304]
 [1.8149830919279304, 1.9479061438333936]
 [8.881934291370747, 8.881934291370747]

Data are not slots and are not wrapped; their shapes are in Data shapes. Each slot accepts its own set of wrappers.

SlotBarePerStratumTimeVaryingPairwisePairwise routesDerivedRecentGather
Recurrence kernellagsyesyesyesyesin TimeVarying(d, Primary())noof a PerStratum kernel, fixed or TimeVarying
Convolution kernellagsyesyesnonoin TimeVarying(d, Primary())nono
couplingS × S or λI; S × S × T read as TimeVaryingnoyesnonononono
modifier parameterone value; S × T read as TimeVarying(PerStratum(x))yesyesnonoyesyesyes
Recurrence gain and addone value, length T or S × Tyesyesnonoyesnoyes

Primary indexing is for kernels only; anywhere else it is an ArgumentError.

Wrappers ​

Three wrappers set the shape of a coefficient:

  • PerStratum(x): one kernel or parameter per stratum, strata first.

  • Pairwise(A): one kernel per pair of strata, receiving stratum first; Pairwise(K₁ => k₁, K₂ => k₂) sums routes, each a coupling and a kernel.

  • TimeVarying(x): a kernel, coupling or parameter that changes over time, time last.

The others compute a coefficient from parameters or from the run:

  • Derived(f, args...): a parameter computed by f, or a cohort kernel computed inside the operator.

  • Gather(p, rows): a parameter or kernel read by stratum k at row rows[k] of p, so strata share the rows they read.

  • Survival(h): each cohort's survival against a hazard h, for a computed kernel.

  • Increments(x): a computed kernel's differences along its lags, such as a delay's mass from its distribution, Increments(1 - Survival(h)), whose masses sum to one less the survival through the last lag.

  • Normalised(x): a computed kernel's weights over each cohort's total across its lags, so Normalised(Increments(1 - Survival(h))) sums to one; it fills on the host only.

  • Either map also takes a kernel's weights, TimeVarying(K, Primary()), such as a table from kernel_weights that other code reads too.

  • Recent(n): a parameter that sums the recurrence's own last n outputs.

A TimeVarying kernel can be a vector with one kernel per step, each of any length. It can also be change points: start => value pairs, each value holding from its start time. Inside a differentiated function, build them as TimeVarying says.

  • By default, column of a time-varying kernel belongs to output time , ComposableRecurrences.Secondary(). It holds the weights the output at puts on earlier times, such as the delays of the reports at .

  • With Primary(), column belongs to input time . It holds how the value at spreads over later times, such as the delays of the infections at . For a recurrence, the value at is its own output.

Most wrappers hold the stored array without copying it. Where a bare array's shape has one reading, the wrapper can be left out: a coupling's third axis can only be time, and a modifier parameter's matrix can only be strata × time.

Shapes with one reading and shapes with two

A bare array also needs no wrapper as a Depletion's population, a Flow's demand, or an Allocate's total and import fraction, whose rows are groups. An Allocate's import pattern is a coupling, so its bare third axis is time too. Where a shape has two readings, the wrapper names the reading, and a bare array is an error that names both. These shapes have two readings:

  • a modifier parameter's vector: one value per stratum, or one per time;

  • a kernel matrix: strata × lags, or lags × time;

  • a three-dimensional kernel: strata × lags × time, or strata × strata × lags.

A Derived argument always takes its wrapper, as it can feed a kernel or a modifier.

julia
rate = fill(0.1, 2, 10)
imports = ComposableRecurrences.Transform(+, rate)
imports.θ isa TimeVarying
true

The bare strata × time matrix rate is stored as a TimeVarying parameter.

Data shapes ​

Inputs, outputs and histories are strata × time arrays, or a vector for a single series. The call's gain and add take three shapes:

ShapeWhat it means
scalarone value for every stratum and time
length-T vectorone value per time, shared by every stratum
S × T matrixone value per stratum and time

A bare vector is always read as time. A recurrence also takes a parameter, such as PerStratum, TimeVarying, Gather or a Derived of them, read at each stratum and time. A parameter has no length, so give stop. For a recurrence, a value per stratum that is constant over time is PerStratum(ρ), with ρ a vector of S values:

julia
r = Recurrence([0.5, 0.3])
r(PerStratum([1.0, 2.0]); history = ones(2, 2), stop = 4)
2×4 Matrix{Float64}:
 0.8  0.7  0.59  0.505
 1.6  2.2  3.16  4.48

For a convolution it is repeat(ρ, 1, T) as the gain, or ρ .* c(x) without add.

Parameters shared across strata ​

Strata can cross two factors, such as age groups and locations, or the particles of a filter and the strata of the model. A parameter then differs over one factor only, and a PerStratum of it would repeat each value. Gather(p, rows) stores the parameter once per level and reads it by an index:

where is the value stratum reads at time , the stored parameter with a row per level and = rows[k] the level of stratum . Here four strata are two ages in each of two places, with a susceptibility per age and a population per place:

julia
using ComposableRecurrences: Depletion, Gather, select
age = [1, 2, 1, 2]
place = [1, 1, 2, 2]
susceptibility = Gather(PerStratum([1.0, 0.6]), age)
population = Gather(PerStratum([500.0, 200.0]), place)
r = Recurrence([0.5, 0.3]; modifiers = (Depletion(population),))
r(susceptibility; history = ones(4, 2), stop = 3)
4×3 Matrix{Float64}:
 0.79936   0.698073  0.586736
 0.47977   0.323515  0.183085
 0.798402  0.695194  0.581879
 0.479424  0.32279   0.182315

The Gather is the outer wrapper, so a level's value over time is Gather(TimeVarying(PerStratum(P)), rows). It is a modifier parameter, a Derived argument, a gain or add, a Depletion's population or a Recurrence kernel. In a gradient the strata that share a row add their cotangents into it, so an AD backend differentiates the stored array.

select(parameter, strata) reads a parameter at chosen strata. It changes the index and leaves the stored values where they are:

julia
kept = select(population, [4, 1])
kept.rows, kept.p === population.p
([2, 1], true)

Batches of strata ​

A batch is independent copies of an -stratum model. The copies run as strata, with stratum    being stratum of batch , so there is no batch axis inside the operators. A coupling and a shared parameter make the copies one model.

  • Batched(K) is the coupling that mixes the strata of each batch by the same   matrix,

    where holds each stratum's kernel-weighted past and the pressure on it. It is one matrix product on the strata reshaped to  .

  • A Gather stores a parameter once whether it differs by stratum, by batch or by neither.

A call whose history is    runs the batches as strata and returns   , with time last as in every time-indexed input:

julia
using ComposableRecurrences: Batched
K = [0.9 0.1; 0.2 0.8]
population = Gather(PerStratum([500.0, 200.0]), repeat(1:2, 3))
batched = Recurrence(
    [0.5, 0.3]; coupling = Batched(K), modifiers = (Depletion(population),)
)
h = ones(2, 3, 2) .* [1.0 2.0 4.0]
size(batched(1.4; history = h, stop = 5))
(2, 3, 5)

A resumed call takes inputs in either layout and returns its state on the strata, and select with each = S selects whole batches.

Nesting ​

Wrappers nest from the outside in: time, then strata, then the slot's own axes. TimeVarying(PerStratum(G)) is an S × L × T kernel and TimeVarying(Pairwise(A)) is S × S × L × T. A Derived or Recent parameter sits inside arithmetic, as in β * Recent(7), and its arguments may be any other parameter. Recent(7; coupling = C) mixes the recent outputs between strata, so each place responds to the incidence in both:

julia
using ComposableRecurrences
CR = ComposableRecurrences
# Each of two places responds to the incidence in both.
C = [0.8 0.2; 0.2 0.8]
β = CR.Derived(exp, -0.05 * CR.Recent(7; coupling = C))
r = Recurrence([0.2, 0.5, 0.3]; modifiers = (CR.Transform(*, β),))
round.(r([2.0 2.0 2.0; 1.0 1.0 1.0]; history = ones(2, 3)); digits = 3)

# output

2×3 Matrix{Float64}:
 1.721  1.823  2.241
 0.861  0.795  0.691
Arguments of a Derived kernel

A Derived kernel's arguments may also be vectors of lag weights, Primary() coefficients and Survival. A time-varying argument, or a Survival's hazard, may be given by change points, whose last value holds past the data. Change points run on the host, as they do in every other slot.

How a modifier reads a parameter

Every modifier reads a parameter through param, which takes every form. A new wrapper or parameter form therefore works with every modifier that reads through param. A parameter's cotangent goes back through add_param!, which also takes every form.

Delay distributions as kernels ​

A delay distribution can stand in for a kernel, given the number of lags. The operator turns it into masses, the probability that the delay falls on each whole lag.

julia
using Distributions, CensoredDistributions
Recurrence(Gamma(2.0, 2.5); lags = 15)
masses = ComposableRecurrences.delay_masses(Gamma(2.0, 2.5), 15)
round(masses[1]; digits = 3), round(sum(masses[2:end]); digits = 3)
(0.022, 0.957)

A recurrence's kernel starts at lag 1, so it keeps the masses on lags 1 to 14, 0.957 of the delay, and drops the 0.022 on lag 0. A convolution keeps lag 0, so Convolution(d; lags = 4) has 4 kernel entries and Recurrence(d; lags = 4) has 3. The keyword width is the width of one lag in the delay's unit, 1 by default. A model with a weekly time unit and delays in days takes width = 7.

Discrete distributions have masses with Distributions.jl loaded, and continuous ones with CensoredDistributions.jl. Any other type works as a delay when it has a delay_masses method, which gives its masses on lags 0 to lags - 1. Here is a delay type with masses   on whole units, and the masses of width units summed for a lag:

julia
using ComposableRecurrences
struct GeometricDelay
    p::Float64
end
function ComposableRecurrences.delay_masses(d::GeometricDelay, lags; width = 1)
    q = (1 - d.p)^width
    return map(l -> (1 - q) * q^l, 0:(lags - 1))
end
Convolution(GeometricDelay(0.5); lags = 3).kernel,
Recurrence(GeometricDelay(0.5); lags = 3, width = 2).kernel

# output

([0.5, 0.25, 0.125], [0.1875, 0.046875])

Delays take the same wrappers as arrays, such as PerStratum(ds) or TimeVarying(ds, Primary()), with Pairwise for Recurrence only. Pairwise(D) is a matrix of delays with D[i, j] the delay of stratum j in stratum i, and TimeVarying also takes PerStratum or Pairwise of delays, with time last. A tuple (d₁, d₂) is a chain of delays, one after another, and is itself a delay.

Where the coupling acts ​

The coupling mixes the strata after the kernel and before the gain. It has no lag of its own: it mixes each stratum's kernel-weighted past at the current step. For strata, the step before the modifiers is, stratum by stratum,

where is the value of stratum at time and its kernel weight on lag . is the coupling's weight of stratum in stratum , and and the gain and add of stratum .

A coupling is square: a recurrence's outputs are its own later inputs, so they have the same strata. A map of a series from strata to is a matrix product W * X, with W an   matrix, before or after an operator. Towns summed to a region, or one series shared out to several, are such maps. A delay per mapped stratum is then Convolution(PerStratum(P))(W * X).

This order sets what a per-stratum coefficient means.

  • A PerStratum kernel belongs to the stratum sending, since the kernel weights each stratum's own past.

  • A gain of S rows belongs to the stratum receiving, since it multiplies the mixed value.

  • A row of the coupling is the stratum receiving, and a column the stratum sending.

The transmissibility of a sending stratum therefore goes in the kernel or the columns of the coupling, and the susceptibility of a receiving stratum in the gain or the rows. Scaling by a transmissibility gives the same step as scaling by .

julia
k = [0.4, 0.4, 0.2]
K = [0.8 0.3; 0.2 0.7]
gain = fill(1.1, 2, 8)
h = ones(2, 3)
σ = [1.0, 0.5]                  # transmissibility of each sender
by_kernel = Recurrence(PerStratum(σ .* k'); coupling = K)(gain; history = h)
by_columns = Recurrence(k; coupling = K .* σ')(gain; history = h)
by_kernel ≈ by_columns
true

A receiver's susceptibility in the gain gives the same run as in the rows of the coupling:

julia
using ComposableRecurrences
ρ, T = [1.0, 2.0], 3
h = ones(2, 1)
by_gain = Recurrence([0.5])(repeat(ρ, 1, T); history = h)
by_rows = Recurrence([0.5]; coupling = ρ .* [1 0; 0 1])(; history = h, stop = T)
by_gain == by_rows

# output

true

The coupling can be I, λ * I, a dense, Diagonal or sparse matrix, a TimeVarying array with time last, a Batched matrix or a type you write.

Coupling or pairwise kernel ​

A coupling with a shared kernel assumes every pair of strata has the same lag shape, scaled by the coupling. A Pairwise kernel gives each pair its own lag shape, so it does the coupling's job and the coupling stays I:

where weights stratum in stratum at lag . When every pair shares the shape,  , the two give the same values, and the coupling is cheaper.

julia
A = reshape(K, 2, 2, 1) .* reshape(k, 1, 1, :)
pairwise = Recurrence(Pairwise(A))(gain; history = h)
coupled = Recurrence(k; coupling = K)(gain; history = h)
pairwise ≈ coupled
true

Pairwise(K₁ => k₁, K₂ => k₂) sits between the two: a sum of a few kernels, each with its own coupling, such as household and community contacts with different generation intervals. With routes , each a coupling and a kernel ,

Use a coupling when one lag shape fits, Pairwise routes for a few shapes, and a Pairwise array when the shape differs by pair.

Your own coupling ​

Write your own coupling type when the mixing has structure a matrix wastes, such as low rank or a formula in time. The type needs a forward! method that writes the pressure q on each stratum from each stratum's kernel-weighted past p, and may add a pullback! for a hand-written gradient. Specialising for speed writes a rank-one coupling this way.