Skip to content

Public Documentation ​

Documentation for ComposableRecurrences's public interface.

ComposableRecurrences.ComposableRecurrences Module
julia
ComposableRecurrences

Fast, composable and differentiable recurrences and convolutions.

A recurrence computes each value from its own past values, such as infections from earlier infections. A convolution weights the past values of another series, such as reported cases from earlier infections. For a single series the two are

where is the output at time , a multiplicative input, the convolved input and the kernel weight on lag . Every operator is differentiable with forward- and reverse-mode automatic differentiation backends.

Recurrence and Convolution are the operators. A plain array holds one set of coefficients: a kernel's lag weights, a coupling's S × S matrix or a modifier parameter's single value. PerStratum gives one set per stratum, Pairwise one per pair of strata and TimeVarying one per time. Inputs, histories and outputs are strata × time arrays, or a vector for a single series. Time is absolute, counted from 1, and a call covers the times start:stop.

conceptone way
feedback recursionRecurrence(kernel; coupling, modifiers), lag 1 first
convolutionConvolution(kernel), lag 0 first
strataPerStratum(x), Pairwise(x)
time variationTimeVarying(x), TimeVarying(x, Primary())
strata and timeTimeVarying(PerStratum(x)), TimeVarying(Pairwise(x))
multiplicative inputr(gain; ...)
additive inputadd =, before the modifiers
seed and resumehistory =, state =
modifiersDepletion, Redistribute, Allocate, Transform
pools and flowsDepletion(N, Hazard(), Flow(from => to, d); pools)
filling a poolDepletion(C, Truncate(; into = :O); pools)
optionsstructs such as Hazard(), Floor(), Primary()
extensiona type with a forward! method for a role

To extend the package, define a type and add a ComposableRecurrences.forward! method, and optionally a ComposableRecurrences.pullback! method, for its role (ComposableRecurrences.Step, ComposableRecurrences.Init, ComposableRecurrences.Pressure or ComposableRecurrences.Trace).

Examples

julia
using ComposableRecurrences
g = [0.1, 0.3, 0.6]
y = Recurrence(g)(fill(1.2, 10); history = ones(3))
round.(y; digits = 3)

# output

10-element Vector{Float64}:
 1.2
 1.224
 1.299
 1.461
 1.524
 1.644
 1.798
 1.905
 2.059
 2.227
source

Contents ​

Index ​

Public API ​

ComposableRecurrences.Allocate Type
julia
struct Allocate{T, I}

A modifier that rescales each group of strata to a total fixed outside the model: the strata of a group keep their shares of the group's value and the group takes its total. With imports, a fraction of each total is shared instead by an import pattern that reads the values before an optional within-group spill.

At absolute time , with stratum 's value after the earlier modifiers, the strata of group and its total,

with the machine epsilon of the buffer eltype, so the group sums of equal the totals wherever  . With imports = (fraction, pattern) and spill, the shares come from the spilled values   and a fraction of the total from the import pattern  , read before the spill:

where is the movement matrix of a ComposableRecurrences.Redistribute (the identity without spill) and a coupling. is one once the pattern sum reaches . Below that, the pattern places the share of the total, so the split changes continuously, and a group whose pattern sums to zero takes all of its total by . The group sums of still equal the totals. The split has no branch on the values, so a tape recorded at one input holds at another. Use spill only when the pattern must read the values from before the spill; otherwise place the Redistribute before Allocate in the modifier tuple. It is meant for non-negative values: a group sum at or below zero is floored to . The groups partition the strata; a stratum in no group is an ArgumentError. A group may be empty, given as Int[] or a range such as 3:2 (an untyped [] holds Any and is rejected): it holds no strata, so its total and import fraction are not used and their gradients are zero. The groups are stored flat, in the fields strata (each group's strata in turn) and offsets (where each group starts), so the rule sees only integer arrays and the parameters. total and fraction are parameters over groups, not strata: PerStratum holds one value per group, and a bare matrix is read as groups × time. It reads every stratum of a group, so it is not pointwise, and its groups differ in size and are set by the value, so it is not blockwise (ComposableRecurrences.blocks is nothing). It has no state without imports; with them the state holds , after when there is a spill. It composes with the other modifiers in tuple order: (Allocate(groups, total), Transform(+, b)) adds b after the split. Its reverse pass, with the output cotangent and  , is

and on the floor ( ) the term drops. With imports, and are the same sums over and , and

where is replaced by in while the pattern sum is below , then   , two transposed products.

Arguments

  • groups: a vector of index ranges or vectors, one per group, partitioning the strata.

  • total: each group's total.

Keyword Arguments

  • imports: nothing (the default), or (fraction, pattern) with fraction the share of each group's total placed by the import pattern and pattern an S × S coupling, or TimeVarying of an S × S × T array; a bare S × S × T array is read as the latter.

  • spill: nothing (the default), or a ComposableRecurrences.Redistribute applied after the pattern reads the values; it needs imports.

  • trace_imports: Val(false) (the default), or Val(true) for the trace to hold the imports, the part of each stratum's value the import term placed, after the state, with its rows named spilled, pattern and imports (see ComposableRecurrences.trace_rows); it needs imports. Without it the trace is the state after each step, which costs less to record. It is a Val, not a Bool, so the choice is part of the type even when the model is built inside a gradient.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
totals = [10.0 12.0 15.0 18.0; 2.0 3.0 3.0 4.0]  # groups × time
split = CR.Allocate([1:2, 3:3], TimeVarying(PerStratum(totals)))
r = Recurrence([0.6, 0.4]; modifiers = (split,))
r(fill(1.2, 3, 4); history = ones(3, 2))

# output

3×4 Matrix{Float64}:
 5.0  6.0  7.5  9.0
 5.0  6.0  7.5  9.0
 2.0  3.0  3.0  4.0

Allocate with imports adds an import pattern and a spill.


Fields

  • strata::Vector{Int64}: The strata of every group, group by group.

  • offsets::Vector{Int64}: Group p is strata[(offsets[p] + 1):offsets[p + 1]].

  • total::Any: Each group's total, a parameter over groups.

  • imports::Any: The import fraction, pattern and spill, or nothing.

source
ComposableRecurrences.Convolution Type
julia
struct Convolution{K, M<:ComposableRecurrences.ConvolutionMethod} <: ComposableRecurrences.AbstractOperator

A convolution whose kernel starts at lag 0: each output weights the current and past inputs, then is scaled by the gain and shifted by the add input,

where is the output of stratum at absolute time , its input steps earlier, = kernel[l + 1] the weight on lag , the kernel length, the gain and the add input. for   comes from history and is zero before it. Strata do not mix. In the direct sum a zero weight multiplies its input rather than skipping it, so   gives NaN, as sum(k .* x) does, and a non-finite input reaches every output its lags feed; the transform of ComposableRecurrences.FFTMethod spreads it further. ComposableRecurrences.contributions returns the terms of the sum over before it is taken.

A vector kernel is shared by every stratum, a PerStratum kernel is S × L, and a TimeVarying kernel is L × T or TimeVarying(PerStratum(G)) with G S × L × T, all lag 0 first. A TimeVarying kernel's indexing sets which time its column belongs to: with ComposableRecurrences.Secondary (the default) column weights the inputs reaching output , as above; with ComposableRecurrences.Primary column is the delay pmf of the input at time , which spreads forward through it, so the weight is   and input mass is conserved up to the window's end.

To weight lags from 1, as a renewal's infection pressure does, prepend a zero: Convolution(vcat(0, g)) recomputes   from the outputs of a Recurrence with kernel . A sum that reads the inputs forward from each time is the transpose c', which transpose sets out.

Called as c(x; gain = 1, add, history = nothing, start = 1, stop), the call covers the absolute times start:stop:

  • x: the inputs, length T or S × T, read at absolute time t. The inputs before start come from x itself, and the inputs after its end are zero. A tuple of S series, one per stratum and all of length T, is read as the rows of S × T, and the output is then a tuple of S series; the keywords are as for S × T.

  • gain: a scalar, a length-T vector shared by every stratum, or S × T, read at time t; one when left out.

  • add: nothing, a scalar, length T or S × T, read at time t.

  • history: the inputs before t = 1, oldest first (any length m, or S × m); earlier inputs are zero. Not with a Primary() kernel, which has no column for them.

  • start: the first time; 1 by default.

  • stop: the last time; by default the common length of the time-indexed inputs (x, gain, add). It may pass the end of x, but gain and add must cover it. Only the outputs that a lag of x reaches are summed, so an input that is zero from some time on can be passed up to that time, as in c(x[:, 1:(t0 - 1)]; stop = T).

The output has the layout of x and length stop - start + 1.

Arguments

  • kernel: the kernel, lag 0 first, or a kernel of delays.

Keyword Arguments

Examples

julia
using ComposableRecurrences
delay = [0.0, 0.5, 0.3, 0.2]         # P(delay = 0, 1, 2, 3)
# Report 40% of the delayed inputs, on a baseline of 1.
Convolution(delay)(ones(8); history = ones(3), gain = 0.4, add = 1.0)

# output

8-element Vector{Float64}:
 1.4
 1.4
 1.4
 1.4
 1.4
 1.4
 1.4
 1.4

Fields

  • kernel::Any: The kernel, lag 0 first.
source
ComposableRecurrences.Depletion Type
julia
struct Depletion{I<:NamedTuple, C<:Tuple}

Depletion of pools: each group of strata holds pools, and parts act on the step's value and the pools in the order given. A draw takes the value from the pools, or fills one, and ComposableRecurrences.Flows move between them.

With one pool drawn from, then flows, each stratum at absolute time from the call's first time steps as

where is the value entering the modifier, the value it passes on, the starting pool, the population at time , the draw's form, forward!(form, Step(), v, s, N), and the flows, such as a count out of the pool,  . The hazard fraction divides by N whatever the pool starts at.

With pools in a group, a draw takes from the weighted pools and each pool loses the draw in proportion to its weight:

where is pool 's weight, zero for a pool weights does not name. When   the draw comes from the first pool weights names alone. A draw into pool (into = f) fills it instead, up to :     and   , as admissions fill beds. Its form is Truncate() or Truncate(κ), and its capacity is not negative. What a draw leaves of the value it takes,   , goes nowhere by default; with overflow = :stratum to the group's second value,   , and with overflow = :queue to a queue held after the pools in the state, whose content joins the draw's value at the next step. Each draw takes the value the parts before it pass on.

The flows act on the pools where they stand among the parts, as when patients leave before the step's admissions or an allowance is granted at the start of a period. Hazard and share flows given one after another act together, then each count flow in the order given; a count flow from 0 brings its demand in from outside.

A draw is a form, Hazard(), Floor(), Truncate(), Truncate(κ) or a new type with a forward!(form, Step(), v, s, N) method, which draws from the first pool alone. A built-in form given weights, into or overflow, such as Hazard(; weights = (S = 1, V = σ)) or Truncate(; into = :O), is a draw with them. The draw's Hazard() takes its hazard from the value over the population, ; a Hazard() flow's demand is the rate itself. A form without a pullback! is differentiated by a local step when its float parameters are scalars, and by plain AD otherwise.

One pool, with draws that leave nothing over, is a pointwise step, blocks (1, 1), whose state is the pool. Any other is blockwise: each group has one value, or two with overflow = :stratum, value    being value of group for groups, and the state holds pool 1 of every group, then pool 2, and so on, then the queue. A Depletion covers every stratum, so a stratum without a cap takes an infinite N. With overflow = :stratum group overflows into stratum  , so another pairing permutes the strata. For groups that share one overflow stratum, a ComposableRecurrences.Redistribute after the Depletion, with   on the other overflow strata and K sending each to the shared one, moves their values into it.

Without a draw the pools are the step's values: the values hold pools of groups each, pool by pool (blocks is (n, n)), so value    is pool of group . On a Recurrence with kernel [1.0] the core carries the previous step's pools forward, and the Depletion applies the step's flows,  . The state then holds what flowed into each pool at the step, where a negative count adds nothing.

Depletion in practice builds births and deaths, leaky protection, beds, allowances and a ward from these parts. A Depletion holds the fields pools (each pool's starting value, nothing for its default) and pieces: the draws, each with N and its pools named by position, and the flows given one after another as one tuple. Each part is a modifier on the pools it shares with the others: its group step forward!(piece, Step(), v, s, t, g) takes the group's values and its pools, then the queue, as tuples of one-entry views, with pullback! and ComposableRecurrences.Trace alike, and the Depletion runs them in order. A draw's trace is the value it passes on and what it leaves, and a run of flows' the amount each moves.

Arguments

  • N: the population a draw reads, or the capacity a draw fills up to, a parameter read at each step's group and time, a bare matrix being groups × time; left out for a Depletion without a draw, or whose truncated draws from its pools do not read it.

  • pieces: the draws and flows, in the order they act; Hazard() alone when none are given.

Keyword Arguments

  • pools: each pool's name and starting value, a named tuple such as (S = N, V = 0.0), or a tuple of names when each takes its default; (S = nothing,) by default. A starting value is one value or PerStratum, or nothing for N at time 1 in the first pool the first draw from the pools names, and zero in the others. A Depletion without a draw takes its pools from the history instead, so each starts at nothing. A seed drawn from the pool is pools = (S = max(N - sum(seed), 0),).

A draw takes these keywords on its form:

  • weights: each pool's weight in the draw, a named tuple such as (S = 1, V = σ); the first pool's alone at 1 by default. A weight is one value or PerStratum, constant over time; an integer weight is fixed, a float one a parameter. One pool is drawn with weight 1.

  • into: the name of the pool the draw fills, in place of weights, or nothing.

  • overflow: where what the draw leaves goes: nothing (the default), :stratum or :queue; one draw at most has a queue.

Examples

Depletion from a pool that starts below the population by the seed:

julia
using ComposableRecurrences
CR = ComposableRecurrences
seed = [1.0, 2.0]
depletion = CR.Depletion(100.0, CR.Hazard(); pools = (S = 100.0 - sum(seed),))
r = Recurrence([0.5, 0.5]; modifiers = (depletion,))
y = r(fill(2.0, 8); history = seed)
round.(y; digits = 3)

# output

8-element Vector{Float64}:
  2.867
  4.472
  6.344
  8.541
 10.342
 11.087
 10.29
  8.287

Fields

  • pools::NamedTuple: Each pool's starting value by name, nothing for its default.

  • pieces::Tuple: The draws and the runs of flows, in the order they act.

source
ComposableRecurrences.Derived Type
julia
struct Derived{F, A<:Tuple}
julia
Derived(f, args...)

A value computed from at least one argument args by a function f: a modifier parameter, or the weights of a cohort kernel.

As a modifier parameter, at stratum and absolute time ,

where is argument read by ComposableRecurrences.param, any parameter including another Derived. A Derived of parameters goes wherever a modifier takes a parameter.

As a kernel, TimeVarying(d, Primary()), the weight on lag of cohort (the input at time ) in stratum is

with each argument read at that entry:

argumentread at entry
a number cc
a vector p of lag weightsp[i], the kernel's ith lag
PerStratum(v), PerStratum(P)v[k], P[k, i]
TimeVarying(x, Primary())at time
TimeVarying(x)at time  
Derived, ComposableRecurrences.Survivalits own weight

i is the lag's index in the kernel: lag    in a Convolution and   in a Recurrence. So a TimeVarying(x) argument is read, in both uses, at the time the value acts: the step of a modifier, or the time   a weight lands, and a calendar-time series such as a hazard is TimeVarying(h). Every argument with a lag axis has the kernel's number of lags, and every argument with a strata axis the call's strata; a kernel with any of them is per stratum. The arguments with a lag axis, and those with Primary() indexing, make a Derived a kernel only: as a modifier parameter it is an error.

A call with a kernel computes the weights it reads inside its own call, a block of cohorts at a time, and runs as with the dense kernel of those weights, on the calling task and on host arrays. ComposableRecurrences.kernel_weights returns them as an array.

The reverse pass, for the cotangent of a value read, is

with the partial derivatives in closed form for +, -, * and / in a kernel, and otherwise from one local forward-mode derivative of f, which needs the dual-number extension loaded. Values captured inside f (a closure, or a callable struct with float fields) are not arguments: an operator with such a map is differentiated by the AD backend instead, so they keep their gradients.

Arithmetic with a Derived on either side builds another Derived, so κ * x, x + c, x - c, x / N, x ^ p and -x all work when x is a Derived, with a number, a vector, PerStratum or TimeVarying on the other side. +, -, * and / also work with a ComposableRecurrences.Survival on either side. Wrap a plain parameter as Derived(identity, x) to start such an expression.

Arguments

  • f: the function, called as f(a_1, ..., a_n) on the arguments' values.

  • args: the arguments, at least one.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# A multiplier from a scale and a log value that varies with t.
logR = TimeVarying(0.3 .* sin.(1:10))
β = 0.8 * CR.Derived(exp, logR)
r = Recurrence([0.5, 0.5]; modifiers = (CR.Transform(*, β),))
round.(r(; history = ones(2), stop = 10); digits = 3)

# output

10-element Vector{Float64}:
 1.03
 1.067
 0.875
 0.619
 0.448
 0.392
 0.409
 0.432
 0.381
 0.276

A delay pmf whose mass is scaled down for cohorts from time 3 on:

julia
using ComposableRecurrences
CR = ComposableRecurrences
p = [0.5, 0.3, 0.2]
scale = TimeVarying([1.0, 1.0, 0.5, 0.5], CR.Primary())
K = TimeVarying(CR.Derived(*, p, scale), CR.Primary())
round.(Convolution(K)(ones(4)); digits = 3)

# output

4-element Vector{Float64}:
 0.5
 0.8
 0.75
 0.6

Fields

  • f::Any: The function, called on the arguments' values.

  • args::Tuple: The arguments.

source
ComposableRecurrences.Device Type
julia
Device(backend)

Another name for the type Parallel.

Arguments

  • backend: a KernelAbstractions backend, such as CUDABackend().

  • min_work: the smallest loop work that runs as a kernel, as for Parallel; 0 by default.

Examples

julia
using ComposableRecurrences, KernelAbstractions
const CR = ComposableRecurrences
CR.Device(KernelAbstractions.CPU()) isa CR.Parallel

# output

true
source
ComposableRecurrences.Direct Type
julia
struct Direct <: ComposableRecurrences.ConvolutionMethod

The lag sum of a Convolution taken term by term,

at cost for outputs and lags. It takes every kernel and number type.

Examples

julia
using ComposableRecurrences
Convolution([0.5, 0.5]; method = ComposableRecurrences.Direct())([1.0, 2.0, 4.0])

# output

3-element Vector{Float64}:
 0.5
 1.5
 3.0

Fields

source
ComposableRecurrences.EXECUTOR Constant

The executor that operator calls use for their parallel loops, Serial by default.

Set it for a block of code with with; operator types do not change. An operator op gives the same output under any two executors e_1 and e_2:

Each operator call reads it once. Threaded needs every modifier the loops run, including user-defined ones, to write only its own stratum's slots. Some AD backends do not differentiate tasks, so code they trace runs serially; a rule's forward and reverse passes use the set executor.

Examples

julia
using ComposableRecurrences
using Base.ScopedValues: with
const CR = ComposableRecurrences
with(CR.EXECUTOR => CR.Threaded()) do
    CR.EXECUTOR[]
end

# output

ComposableRecurrences.Threaded(500000, 0)
source
ComposableRecurrences.FFTMethod Type
julia
struct FFTMethod <: ComposableRecurrences.ConvolutionMethod

The lag sum of a Convolution through the discrete Fourier transform of the zero-padded series, by overlap-add,

The    buffered inputs, from the history and the rest up to the last time , are split into blocks of   , each transformed at size , the smallest 5-smooth number at least   . Lags from on reach no input and are dropped first. A block of the whole series is one transform. For a series much longer than the kernel the cost is rather than . It is faster than the direct method from about 300 lags and 1000 outputs, the sizes from which ComposableRecurrences.Auto takes it; time both on the sizes of a model before choosing it. The reverse pass uses the same transforms.

It runs once the weak dependency of the FFT extension is loaded; without it, a call with this method is refused. It runs for a fixed kernel (a vector or PerStratum) on Float32 or Float64 arrays; a TimeVarying kernel, any other number type (dual numbers, say) and other arrays (device or traced) take ComposableRecurrences.Direct. It does not use the set ComposableRecurrences.EXECUTOR.

The transform's error in each sum is about the machine epsilon times the size of the inputs and kernel in its block, not times the sum itself. So each sum is checked against an estimate of that error,

summed over the blocks that reach it, with the machine epsilon; measured errors stay below about half of it. The check is on each output after the gain and add input, on each input cotangent with what it already holds, and on each kernel cotangent, summed over the strata when they share the kernel. A value whose estimate exceeds of it ( in Float32) has its sum taken directly instead, and once such sums would cost more than a quarter of the direct method, the whole pass takes the direct method. So the outputs and gradients match the direct method to that relative accuracy, and they cannot come out negative from a positive kernel and inputs. A series spanning many orders of magnitude, such as a long exponential growth, then costs up to both methods together. A NaN or Inf input makes every output its block's transform reaches NaN, including earlier ones.

Examples

julia
k = [0.1, 0.4, 0.3, 0.2]
x = collect(1.0:6.0)
Convolution(k; method = ComposableRecurrences.FFTMethod())(x) ≈ Convolution(k)(x)

# output

true

Fields

source
ComposableRecurrences.Floor Type
julia
struct Floor{A, W, I, O}

The floored depletion form: the value is scaled by the share of the pool left, with a floor.

For one stratum at one step,

where is the value asked for, the pool before the step, the population, the heterogeneity exponent, the scaling, the value drawn and the pool after the step. The pool can go negative, and then the floor applies.

Arguments

Keyword Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0], [80.0]
CR.forward!(CR.Floor(), CR.Step(), v, s, 100.0)
v, s

# output

([1.6], [78.4])

Fields

  • α::Any: The heterogeneity exponent α, or nothing for one.

  • weights::Any: As a draw, each pool's weight by name, or nothing.

  • into::Any: As a draw, the pool it fills, or nothing.

  • overflow::Any: As a draw, where what it leaves goes.

source
ComposableRecurrences.Flow Type
julia
struct Flow{D, F<:Union{ComposableRecurrences.Hazard{Nothing, Nothing, Nothing, ComposableRecurrences._Drop}, ComposableRecurrences.Share, ComposableRecurrences.Split, ComposableRecurrences.Truncate{<:Any, Nothing, Nothing, ComposableRecurrences._Drop}}, E, P, G, N}

A flow from pool from into pool to of a ComposableRecurrences.Depletion, out of it with to = 0 or into it with from = 0, that moves its demand by a form.

Each step it moves an amount out of pool from and into to,

with the form setting from the demand and the pool it leaves:

formdemand
ComposableRecurrences.Hazard (the default)a hazard rate  , with the sum of the hazard rates out of
ComposableRecurrences.Sharea share 
ComposableRecurrences.Truncatea count, or a smooth one with Truncate(κ)
ComposableRecurrences.Splita count, from several poolseach source's part of , in proportion to the pools the step starts from

The hazard rates out of one pool compete, as in the Hazard depletion form, so together they move  ; with non-negative, finite rates a non-negative pool stays non-negative. A per-step probability   is the rate  . A constant rate out of a compartment is a geometric stay in it; for another stay, convolve the inflow with its survival. A Hazard() flow's demand is the rate itself, with no population and no heterogeneity, where a Hazard() depletion draws the value divided by its population N. For each group at absolute time , with pools , hazard flows at rates and share flows at shares , these act together on the pools before the step's flows,

then each count flow, in the order given, moves its out of what remains in . Each share is between 0 and 1, checked unless it is a Derived, which is only known at each step. Shares out of one pool that sum to more than leave it negative. A negative count adds to pool from, without a cap, and moves nothing into to. A flow from 0 is a count from outside the Depletion, which never runs out: it moves   into to, and a negative one moves nothing. Its form is Truncate() or Truncate(κ). The derivative through and takes the active branch. Rates are not checked.

Arguments

  • pools: from => to, each a pool's name or its position from 1, with to = 0 to leave the Depletion and from = 0 to enter it; for Split(), from is a tuple of two or more pools.

  • demand: the rate, share or count, a parameter read at each step's group and time, with PerStratum holding one per group; a bare matrix is read as groups × time.

Keyword Arguments

  • form: Hazard(), the default, Share(), Truncate(), Truncate(κ) or Split().

  • name: nothing, the default, or a Symbol. When every flow of a Depletion without a draw is named, its trace returns the amount each moves by name (see ComposableRecurrences.trace_rows). Named flows in a Depletion have different names.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
waning = CR.Flow(:V => :S, 0.1)
transfers = CR.Flow(1 => 0, 3.0; form = CR.Truncate())
waning.form, transfers.to

# output

(ComposableRecurrences.Hazard(), 0)

Fields

  • from::Any: The pool the flow leaves, by name or position; a tuple for Split().

  • to::Any: The one pool it enters, by name or position, or 0 when it leaves.

  • demand::Any: The rate, share or count, a parameter.

  • form::Union{ComposableRecurrences.Hazard{Nothing, Nothing, Nothing, ComposableRecurrences._Drop}, ComposableRecurrences.Share, ComposableRecurrences.Split, ComposableRecurrences.Truncate{<:Any, Nothing, Nothing, ComposableRecurrences._Drop}}: How the demand moves: Hazard(), Share(), Truncate or Split().

source
ComposableRecurrences.Gather Type
julia
struct Gather{P, R<:(AbstractVector{<:Integer})}
julia
Gather(p, rows)

A parameter read, for stratum , from row = rows[k] of the parameter p, so a value given per group is read by each stratum of its group:

with read by ComposableRecurrences.param. Strata that share a row add their cotangents into it. p is a parameter with a row axis, such as PerStratum(v), TimeVarying(PerStratum(P)) or a Derived of them; rows past the end of a Derived are found when read. A Gather is a modifier parameter, an argument of a Derived, a Recurrence's gain or add, or a Depletion's population.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
force = TimeVarying(PerStratum([1.0 2.0; 10.0 20.0]))  # groups × time
x = CR.Gather(force, [1, 1, 2])
[CR.param(x, k, t) for k in 1:3, t in 1:2]

# output

3×2 Matrix{Float64}:
  1.0   2.0
  1.0   2.0
 10.0  20.0

Fields

  • p::Any: The parameter read.

  • rows::AbstractVector{<:Integer}: The row of p each stratum reads.

source
ComposableRecurrences.Hazard Type
julia
struct Hazard{A, W, I, O}

The hazard depletion form: the value is drawn from the pool as a hazard, so the pool never goes negative.

For one stratum at one step,

where is the value asked for, the pool before the step, the population, the heterogeneity exponent, the hazard, the value drawn and the pool after the step. With α > 1, infections slow sooner as the pool shrinks, as when the most susceptible are infected first.

The default draw of a ComposableRecurrences.Depletion. As the form of a ComposableRecurrences.Flow it takes no exponent.

Arguments

  • α: the heterogeneity exponent; nothing, the default, or true for an exponent of exactly one that is not a parameter, so the step skips the power and its derivative. false is a fixed exponent of zero. In a Depletion any other integer takes the population's float type; pass a float to differentiate the exponent.

Keyword Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0], [80.0]
CR.forward!(CR.Hazard(), CR.Step(), v, s, 100.0)
round.(v; digits = 3), round.(s; digits = 3)

# output

([1.584], [78.416])

Fields

  • α::Any: The heterogeneity exponent α, or nothing for one.

  • weights::Any: As a draw, each pool's weight by name, or nothing.

  • into::Any: As a draw, the pool it fills, or nothing.

  • overflow::Any: As a draw, where what it leaves goes.

source
ComposableRecurrences.Increments Type
julia
struct Increments{X}

The increments of a computed kernel along its lags.

Inside a kernel TimeVarying(Increments(x), Primary()), the weight on lag of cohort in stratum is

where is the weight of the kernel TimeVarying(x, Primary()), and before the kernel's first lag is zero. On a cumulative distribution, such as 1 - Survival(hazard), it gives the probability mass at each lag.

Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# The probability a delay with hazard `h` ends at each lag.
h = [0.2, 0.3, 0.4]
pmf = CR.Increments(1 - CR.Survival(h))
round.(CR.kernel_weights(TimeVarying(pmf, CR.Primary()), 1); digits = 3)

# output

3×1 Matrix{Float64}:
 0.2
 0.24
 0.224

Fields

  • x::Any: The kernel to take the increments of.
source
ComposableRecurrences.Init Type
julia
struct Init

The role of a modifier's initial state: forward!(m, Init(), s, history) writes the state s (one entry per stratum, or one per pool for a ComposableRecurrences.Depletion with several, allocated by the operator at its buffer eltype) from the full history, and returns nothing.

It sets the state before the first step of the call at ,

where is the whole history of length , not only the last values the recursion reads, and is the modifier's own map. The default is  .

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
s = zeros(2)
CR.forward!(CR.Depletion(PerStratum([100.0, 50.0])), CR.Init(), s, ones(2, 3))
s

# output

2-element Vector{Float64}:
 100.0
  50.0

Fields

source
ComposableRecurrences.Local Type
julia
struct Local

The role of a map's local derivative at one entry: the partial derivatives of a Derived map or a ComposableRecurrences.Transform map at its arguments, given its value there.

For a map   of scalars, pullback!(grads, f, Local(), y, x...) returns the partial derivatives

one per argument and shaped as it is: a Transform map f(v, θ) with a tuple or NamedTuple θ returns (∂f/∂v, ∂f/∂θ), the second shaped as θ. y is the map's value there, from the forward pass. grads holds no cotangents for this role. The operators look for the method with Float64 arguments, so it should accept any Real arguments. Without one the partials come from a local forward-mode derivative, which needs ForwardDiff loaded. The package's rules for min and max give the first argument the cotangent on a tie, so a tie can differ from ForwardDiff's convention, which also varies between its versions.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# A logistic hazard of the sum of its arguments, whose derivative reads its
# value.
struct LogisticSum end
(::LogisticSum)(a, b) = inv(1 + exp(-(a + b)))
function CR.pullback!(grads, ::LogisticSum, ::CR.Local, y, a, b)
    d = y * (1 - y)
    return d, d
end
h = CR.Derived(LogisticSum(), [-2.0, -1.0], 0.5)
cdf = TimeVarying(1 - CR.Survival(h), CR.Primary())
round.(CR.kernel_weights(cdf, 1); digits = 3)

# output

2×1 Matrix{Float64}:
 0.182
 0.491

Fields

source
ComposableRecurrences.NoAdjoint Type
julia
struct NoAdjoint{O}

An operator wrapper that the AD backend differentiates through its forward loop, bypassing the operator's rule, the package's own reverse pass.

Called exactly like the wrapped operator, it computes the same output,

for every input , so its gradient is the same quantity by a different route: the backend's derivative of the forward loop rather than the rule's pullback. Use it to time the rule against plain AD, and to check the two gradients agree.

It turns off the operator's rules, with two exceptions inside the call; rules for what is built before the call still apply. Which rules are kept lists them, with their backends and measured costs.

Examples

julia
using ComposableRecurrences
r = Recurrence([0.2, 0.3, 0.5])
y = ComposableRecurrences.NoAdjoint(r)(fill(1.1, 6); history = ones(3))
round.(y; digits = 3)

# output

6-element Vector{Float64}:
 1.1
 1.122
 1.16
 1.23
 1.271
 1.323

Fields

  • op::Any: The wrapped operator.
source
ComposableRecurrences.Normalised Type
julia
struct Normalised{X}

The weights of a computed kernel over their total across its lags.

Inside a kernel TimeVarying(Normalised(x), Primary()), the weight on lag of cohort in stratum is

where is the weight of the kernel TimeVarying(x, Primary()), the sum runs over all of the kernel's lags, and a total that is not finite or is at most eps is replaced by eps, so a cohort whose weights are all zero keeps weights of zero. Every lag of each cohort enters its total, so for cohorts and lags a TimeVarying(h) argument needs the times up to    in a Convolution and   in a Recurrence.

Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# The probability mass of a delay with hazard `h`, given that it ends by
# the last lag.
h = [0.2, 0.3, 0.4]
pmf = CR.Normalised(CR.Increments(1 - CR.Survival(h)))
round.(CR.kernel_weights(TimeVarying(pmf, CR.Primary()), 1); digits = 3)

# output

3×1 Matrix{Float64}:
 0.301
 0.361
 0.337

Fields

  • x::Any: The kernel to normalise.
source
ComposableRecurrences.Pairwise Type
julia
struct Pairwise{A<:AbstractArray}

A Recurrence kernel for every pair of strata: adds leading S × S axes, so it is S × S × L.

Each stratum's pressure sums every stratum's past values through its own lag weights:

where = x[i, j, l] weights stratum 's output at lag in stratum , is that output at absolute time  , and replaces the coupled pressure of a Recurrence. The kernel already mixes strata, so the coupling must be I. TimeVarying(Pairwise(A)) has A S × S × L × T.

Pairwise(K₁ => k₁, K₂ => k₂, ...) holds the same kernel as its routes,  , such as community and funeral contacts with different generation intervals. Route convolves the past values with its own kernel, then mixes the result with its own coupling:

with the length of route 's kernel and its   coupling. A route kernel is any Recurrence kernel but routes, and a route coupling any Recurrence coupling; kernels may differ in length, and the history covers the longest. A dense S × S × L array costs a step; routes cost one kernel convolution and one coupling product each, and a sparse route coupling stays sparse. The keyword constructor Recurrence(routes) folds routes with a cheaper form, and the positional Recurrence(routes, I, ()) keeps them as given: one route is its kernel with its coupling, and routes whose couplings are all λ * I on vector kernels are the one kernel . The recurrence's rule applies when it covers every route coupling, as for the coupling of a Recurrence.

Examples

julia
using ComposableRecurrences
P = fill(0.25, 2, 2, 2)
Recurrence(Pairwise(P))(ones(2, 4); history = ones(2, 2))

# output

2×4 Matrix{Float64}:
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0
julia
using ComposableRecurrences
using SparseArrays: sparse
community = [0.9 0.1; 0.1 0.9]
funeral = sparse([0.0 0.4; 0.4 0.0])  # funerals in the other place
routes = Pairwise(community => [0.5, 0.3, 0.2], funeral => [0.0, 0.0, 0.0, 1.0])
y = Recurrence(routes)(fill(1.2, 2, 6); history = ones(2, 4))
round.(y; digits = 3)

# output

2×6 Matrix{Float64}:
 1.68  2.088  2.578  3.181  4.144  5.253
 1.68  2.088  2.578  3.181  4.144  5.253

Fields

  • x::AbstractArray: The pairwise kernels, lag on the last axis.
source
ComposableRecurrences.Parallel Type
julia
struct Parallel{B} <: ComposableRecurrences.Executor

An executor that runs every index of a loop as one thread of a kernel on a KernelAbstractions backend, such as a GPU's: thread k computes

backend is a KernelAbstractions backend, such as CUDABackend(), and the arrays the loop reads and writes must live on it. Kernel launches on one device run in order, so a loop reads the writes of the loop before it; reading the result on the host waits for them. A loop whose work is below min_work runs in order on the calling task, as Serial does. Set it only for a backend whose arrays live in host memory, such as the KernelAbstractions CPU backend: on a GPU that loop would read the device arrays one entry at a time from the host. The default 0 launches every loop. Needs KernelAbstractions to be loaded. Under the default Serial executor, or Threaded, operator calls on arrays that live on a GPU (with GPUArrays loaded) run their strata loops with it without being asked. Every array a call reads must live on the device. Independent strata run as one kernel per call, and strata that mix as one kernel per step with the time loop on the host.

A loop body takes device data only, on every backend.

Examples

julia
using ComposableRecurrences, JLArrays, KernelAbstractions
const CR = ComposableRecurrences
y = JLArray(zeros(4))
ex = CR.Parallel(KernelAbstractions.get_backend(y))
CR.each!((k, y) -> (y[k] = k^2; nothing), ex, 4, 4, y)
Array(y)

# output

4-element Vector{Float64}:
  1.0
  4.0
  9.0
 16.0

Fields

  • backend::Any: The backend the loop's kernel runs on.

  • min_work::Int64: The smallest loop work that runs as a kernel.

source
ComposableRecurrences.PerStratum Type
julia
struct PerStratum{A<:AbstractArray}

A coefficient given per stratum: adds a leading strata axis to its slot.

A stratum is one of parallel series computed together, such as a place or an age group. As a Recurrence kernel it is S × L, one row of lag weights per stratum, and stratum convolves only its own past values:

with = x[i, l] the weight on lag , the output of stratum at absolute time   and the value passed on to the coupling. A Convolution kernel is read the same way from lag 0. Rows of any lengths, PerStratum([k1, k2]), are stacked into one S × L array, with the shorter rows padded with zero weights. As a modifier parameter it is a length-S vector, = x[i]. A coefficient per stratum and per time is TimeVarying(PerStratum(x)).

Examples

julia
using ComposableRecurrences
G = [0.2 0.8; 0.5 0.5]
Recurrence(PerStratum(G))(ones(2, 4); history = ones(2, 2))

# output

2×4 Matrix{Float64}:
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0

Fields

  • x::AbstractArray: The coefficients, strata on the first axis.
source
ComposableRecurrences.PieceInterface Type
julia
    PieceInterface

An Interfaces.jl Interface with mandatory components (:forward, :adjoint, :linear) and optional components (:pointwise, :blocks, :nstate, :stateless, :pullback).

An operator, coupling, modifier or depletion form with forward or forward! for a role.

The mandatory forward component checks that forward (for Run()) or forward! (for the other roles) runs and keeps to its role's conventions (outputs written into the leading arrays and nothing returned, inputs unchanged). The mandatory adjoint component checks that a pullback! method for the type and role is found by ComposableRecurrences.uses_adjoint: a method with a typed grads or typed arguments after the role is not, apart from a blockwise group step's with v::Tuple, s::Tuple, and needs a uses_adjoint method, and one with the wrong number of arguments fails too. The mandatory linear component checks a type declared linear (ComposableRecurrences.islinear): for a coupling's Pressure(), or a whole-step modifier's Step(), built as the matrix from forward! on the basis vectors, forward! on a fixed input equals at rtol = 1e-8, at the given time and at a later one, and a modifier's step leaves its state as it was; it passes any other type and role, and fails a declared modifier that is not a whole-step one. The optional pointwise component checks that a pointwise modifier's step on the whole vectors equals its step on a one-entry view of each stratum,

where is the modifier, and its value and state vectors at time and the number of strata. For Init() it checks that a pointwise modifier writes each from stratum only: the modifier rebuilt with the parameters it reads at stratum and time 1, given a history whose other rows differ, writes the same . It passes any other modifier. The optional blocks component checks the same for a blockwise modifier (ComposableRecurrences.blocks), group by group, and passes any other modifier. The optional nstate component checks the state length against ComposableRecurrences.nstate. The optional stateless component checks that a modifier declared ComposableRecurrences.isstateless leaves its state as it was in Step(), and passes any other modifier and role. The optional pullback component checks a pullback! for a modifier's or a depletion form's Step(), or a coupling's Pressure(), against the Jacobian of forward! from ForwardDiff: for a fixed cotangent of the outputs it compares the cotangents of the type's float parameters and the role's inputs with at rtol = 1e-8. It needs using ForwardDiff, and passes with a note without it; it passes any other role and a type without a pullback!.

Test objects are Arguments(; piece, role, args), with kwargs for Run() and pullback = false for an object the pullback component passes without a check.

Examples

julia
using ComposableRecurrences, Interfaces, ForwardDiff
CR = ComposableRecurrences
Interfaces.test(CR.PieceInterface, CR.Transform; show = false)

# output

true

Extended help

Mandatory keys:

  • forward: forward or forward! runs in its role

  • adjoint: uses_adjoint finds a pullback! method for the role

  • linear: a type declared islinear is its matrix at every time

Optional keys:

  • pointwise: a Step and an Init work stratum by stratum

  • blocks: a vector Step matches the group Step on each group

  • nstate: Init and Step keep the state at nstate(m, S) entries

  • stateless: a type declared isstateless keeps its state in Step

  • pullback: pullback! matches the ForwardDiff Jacobian of forward!

source
ComposableRecurrences.Pressure Type
julia
struct Pressure

The role of a coupling: forward!(C, Pressure(), q, p, t) writes into q the mixing of the per-stratum kernel convolutions p at absolute time t, and returns nothing.

For the built-in couplings

where is stratum 's kernel convolution of its past values, the pressure on stratum and the weight of stratum in stratum , with strata. λ * I gives  , a matrix C gives = C[i, j] at every , and a TimeVarying coupling gives = C.x[i, j, t]. To add a coupling, define a type and add this method; it may compute any from and . Add a ComposableRecurrences.pullback! method for a rule.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
q = zeros(2)
CR.forward!([0.9 0.1; 0.2 0.8], CR.Pressure(), q, [1.0, 2.0], 1)
q

# output

2-element Vector{Float64}:
 1.1
 1.8

Fields

source
ComposableRecurrences.Primary Type
julia
struct Primary

The indexing of a TimeVarying kernel whose column τ is the kernel of the input at absolute time τ, which spreads forward through it.

For a Convolution with kernel length ,

where is the output of stratum at absolute time , the input steps earlier, and the weight on delay (kernel[l + 1]) in column , the column of the input's own time. When every column sums to one, each input's total is kept once all its delays fall inside the window. In a Recurrence with kernel length the input is the output itself, so each output keeps the kernel of the time it was produced:

where is stratum 's kernel convolution at time , its output steps earlier and the weight on lag (kernel[l]) in column . Only outputs at times from 1 have a column, so a seed of length needs start > m. Kernel slots only: anywhere else it is an ArgumentError.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
P = [0.6 0.2 0.4; 0.4 0.8 0.6]         # one delay pmf per input time
Convolution(TimeVarying(P, CR.Primary()))(ones(3))

# Cohorts from time 3 on transmit less.
K = [0.5 0.5 0.2 0.2 0.2 0.2; 0.5 0.5 0.2 0.2 0.2 0.2]
r = Recurrence(TimeVarying(K, CR.Primary()))
h = [1.0, 1.0]
round.(vcat(h, r(fill(1.5, 6); history = h, start = 3)); digits = 3)

# output

6-element Vector{Float64}:
 1.0
 1.0
 1.5
 1.2
 0.81
 0.603

Fields

source
ComposableRecurrences.Recent Type
julia
struct Recent{W<:(AbstractVector), C}

A modifier parameter read from the recurrence's own recent outputs.

At stratum and absolute time ,

where is the final output of stratum at time  , after every modifier, the weight on lag , the number of weights and the S × S coupling, weighting stratum in stratum . A coupling of ones reads the total over strata, and a contact matrix the incidence each stratum sees. Recent(n) with an integer n sums the last n outputs,  . Outputs before the history are zero.

A Recent goes wherever a modifier takes a parameter, alone or inside a Derived. Arithmetic with a Recent on either side builds a Derived, so κ * Recent(7) and Derived(exp, -κ * Recent(7)) work. The Recurrence binds it to its outputs once per call and keeps at least past outputs, its ComposableRecurrences.depth. Outside a recurrence it has no outputs to read, and ComposableRecurrences.param throws.

The reverse pass sends the cotangent of the value read to the outputs it read, the weights and the coupling,

with   without a coupling. These run inside the recurrence's own reverse pass, so the gradient follows the feedback through the outputs.

It works only in the modifiers of a Recurrence, and the recurrence's rule gives its gradient.

Arguments

  • w: the weights, lag 1 first, or an integer n for the sum of the last n outputs. The weights are real numbers and keep their element type, so integer, Float32 and traced weights are held as given.

Keyword Arguments

  • coupling: nothing to read each stratum's own outputs, or an S × S matrix of real numbers mixing them.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# Transmission falls as the last week's incidence grows.
β = CR.Derived(exp, -0.05 * CR.Recent(7))
r = Recurrence([0.2, 0.5, 0.3]; modifiers = (CR.Transform(*, β),))
round.(r(fill(2.0, 8); history = ones(3)); digits = 3)

# output

8-element Vector{Float64}:
 1.721
 1.807
 2.196
 2.404
 2.432
 2.505
 2.414
 2.273

Fields

  • w::AbstractVector: The weights, lag 1 first.

  • coupling::Any: The coupling, nothing or an S × S matrix.

source
ComposableRecurrences.Recurrence Type
julia
struct Recurrence{K, C, M<:Tuple, B, N} <: ComposableRecurrences.AbstractOperator

A recurrence over strata whose kernel starts at lag 1, stepped from a window of its own past values.

At absolute time , each stratum's kernel convolution of its last values is mixed by the coupling, scaled by the gain (a multiplier on each step's value, such as a reproduction number) and shifted by the add input, then passed through the modifiers in tuple order:

for   (start, stop), where

  • is the output of stratum at time , one of strata; for   it is the history;

  • is the kernel's weight on lag , kernel[l], the same for every and unless the kernel is PerStratum or TimeVarying;

  • holds each stratum's kernel convolution and is the   coupling, weighting stratum in stratum ;

  • is the gain and the add input, and is the element-wise product;

  • is the value entering the modifiers, the value after the -th and that modifier's state after step ; with no modifiers  .

A Pairwise kernel replaces with  . kernel[l] weights , as a generation interval or AR coefficients are written: a recurrence has no lag 0. The kernel is a length-L vector shared by every stratum, a PerStratum S × L matrix, or a TimeVarying L × T or TimeVarying(PerStratum(G)) with G S × L × T. A TimeVarying kernel with ComposableRecurrences.Primary indexing reads the column of each output's own time,   in place of , so each output keeps the kernel of the time it was produced; its seed must sit at times from 1. A Pairwise S × S × L kernel (or TimeVarying(Pairwise(A))) weights every pair of strata and already mixes them, so its coupling is I. A Pairwise(K₁ => k₁, K₂ => k₂) kernel sums routes, each a kernel with its own coupling, so its coupling is I too; the keyword constructor folds routes that have a cheaper equivalent form. The coupling is I (or a scaled λ * I), any S × S matrix (dense, sparse, Diagonal), a TimeVarying S × S × T array, or any struct with forward! on ComposableRecurrences.Pressure. A bare S × S × T array is read as TimeVarying: its third axis is time, not lags. Modifiers are structs with forward! on ComposableRecurrences.Step and, for an initial state, ComposableRecurrences.Init.

Called as r(gain = 1; history, state, add, start, stop, record), the call covers the absolute times start:stop:

  • gain: a scalar, a length-T vector shared by every stratum, or S × T, read at absolute time t; one when left out. It may instead be a parameter, such as PerStratum, TimeVarying or a Derived of them, read at each stratum and absolute time. A parameter has no length, so give stop unless add sets it.

  • history: the outputs at times start - h to start - 1, oldest first, length h for a single series or S × h; zeros when left out. The recursion reads the last outputs, with at least L and at least the ComposableRecurrences.depth of each part, and a shorter history is zero-padded. A modifier's Init sees all of it.

  • state: a ComposableRecurrences.State to resume from, in place of history; record = (:state,) returns the next one.

  • add: nothing, a scalar, length T or S × T, read at time t, or a parameter, as for gain.

  • start: the first time; 1, or state.t when resuming. With start = h + 1 the seed sits at times 1:h, and the time-indexed inputs cover it.

  • stop: the last time; by default the common length of the time-indexed inputs (gain, add), required without one.

  • record: a tuple of what to return beside the output y, which makes the call return a named tuple with fields in the order y, state, trace:

    • :state, the ComposableRecurrences.State after the last step;

    • :trace, with trace.modifiers holding each modifier's series per step, a ComposableRecurrences.ntrace by T matrix of its ComposableRecurrences.Trace records, and trace.pressure the pressure each step drew against, laid out as y, as ComposableRecurrences.pressure returns it; both differentiable as the output is. Named modifiers give trace.modifiers as a named tuple keyed by their names, and a tuple of modifiers gives a tuple;

    • :pressure, or a modifier's name, for that part of the trace alone, read as above, as trace.pressure or trace.modifiers.name;

    • :force, for trace.force, the value    of each step before the modifiers, laid out as y and differentiable as it is. It is built only when named, so :trace alone leaves it empty; record (:trace, :force) for both. The parts not named are not built: they come back empty, so the call returns the type a whole trace has, and add no cotangent.

    record = () returns (; y), and without record the call returns y. Pass the tuple as a literal, or in a Val, as record = Val((:trace,)), where it reaches the call as a variable or the call is compiled from its argument types alone; the return type then infers from the argument types.

  • include_history: when true, y is the history followed by the run, and each trace has zero columns over the history, so the output and the trace share their times; false by default. The state is unchanged. It needs history, not state.

Every time-indexed array, kernels, couplings and modifier parameters included, must cover stop. Only a kernel takes Primary() indexing; the constructor rejects it in the coupling or a modifier. The output is length stop - start + 1 for a single series or S rows of it; the history sets which, and the number of strata. The output number type follows the inputs and fields; see Output number type. The constructor checks once whether the local step can rebuild every part it differentiates and stores the result in the field rebuilds; see Rules and plain AD.

Arguments

  • kernel: the kernel, lag 1 first, or a kernel of delays.

Keyword Arguments

  • coupling: how the strata's kernel convolutions mix; I by default.

  • modifiers: a tuple of modifiers applied after the core of each step, or a named tuple, as modifiers = (; pool, imports), whose names key their traces and record reads.

  • lags: for a kernel of delays only, the number of lags from lag 0.

  • step: for a kernel of delays only, the width of a lag in the delays' own unit; 1 by default.

Examples

julia
using ComposableRecurrences
g = [0.6, 0.3, 0.1]                   # weights on lags 1, 2, 3
K = [0.9 0.1; 0.2 0.8]
R = fill(1.1, 2, 10)
r = Recurrence(g; coupling = K)
y = r(R; history = ones(2, 3))

# The seed followed by the run, with the seed at times 1 to 3: the seed's
# 3 columns, then the run's 10.
h = ones(2, 3)
whole = r(hcat(h, R); history = h, start = 4, include_history = true)

# Resume from the returned state over the same inputs.
fit = r(R; history = ones(2, 3), stop = 5, record = (:state,))
size(whole), y ≈ hcat(fit.y, r(R; state = fit.state))

# output

((2, 13), true)

Fields

  • kernel::Any: The kernel, lag 1 first.

  • coupling::Any: How the strata's kernel convolutions mix.

  • modifiers::Tuple: The modifiers, applied in order after the core of each step.

  • rebuilds::Any: Whether the local step rebuilds the parts that use it.

source
ComposableRecurrences.Redistribute Type
julia
struct Redistribute{L, A}

A modifier that moves a share of each stratum's value to others through a movement matrix whose columns sum to one, so the total is conserved.

For each stratum at absolute time ,

where is the value entering the modifier, the value it passes on, = M[i, j] the share of origin 's value that is realised in destination and the arrivals, kept as the state. The columns of sum to one, so summing over gives ; this is checked at Init to within the square root of the machine epsilon. With leak = true a column may sum to less than one, for a share lost on the way. M is an S × S matrix, or TimeVarying of an S × S × T array for movement that changes over time; its entries are its parameters, and a gradient with respect to anything they are built from flows through that construction.

Redistribute(K, ε) builds from a kernel and an origin intensity : a share of origin 's value is realised in  , and the rest stays,

so    whatever the diagonal of , and every column of sums to one. So the derivative in includes that column sum: , for  , moves by and by . A movement written as   , for a kernel whose columns are taken to sum to one, has the same values on such kernels but a gradient in that differs by a constant down each column. The two agree once is built so that its columns sum to one, for example by a softmax over each column. ε is one value or a vector over origins, which gives a matrix, or an origins × time matrix, which gives an S × S × T movement. PerStratum(ε) and TimeVarying(PerStratum(E)) are read as the vector and the matrix they hold. Any other parameter, such as TimeVarying(ε) or one built with Derived or Recent, is read at each step as . The movement is held as and and read from them, so a step costs one product with and its reverse pass gives the cotangents of and without storing a matrix per time.

Place it before a ComposableRecurrences.Depletion to deplete each stratum's pool by what it realises; a modifier sees   , the gain times the coupled pressure plus the add input, so the add values move too. The step is the coupling product , and its reverse pass the transposed product,   and   .

Arguments

  • M: the movement matrix, M[p, q] the share of origin q realised in destination p.

  • K: in place of M, the S × S kernel matrix, K[p, q] the weight from origin q to p.

  • ε: with K, the origin intensity: one value, a vector over origins, an origins × time matrix, PerStratum or TimeVarying(PerStratum) of these, or any other parameter, read at each step.

Keyword Arguments

  • leak: false (the default), or true to allow columns summing to less than one. It sets the type parameter L of Redistribute{L}, so pass it as a literal, which is folded at compile time. For a flag read from a variable, Redistribute{leak}(M) names the type directly.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
movement = CR.Redistribute([0.0 0.3; 0.2 0.0], 0.1)
r = Recurrence([0.5, 0.5]; modifiers = (movement,))
y = r(fill(1.2, 2, 5); history = [1.0 1.0; 0.0 0.0])
round.(y; digits = 3)

# output

2×5 Matrix{Float64}:
 1.176  1.28  1.445  1.604  1.796
 0.024  0.04  0.067  0.095  0.131

Fields

  • M::Any: The movement matrix, M[p, q] from origin q to destination p.
source
ComposableRecurrences.Serial Type
julia
struct Serial <: ComposableRecurrences.Executor

An executor that runs every index in order on the calling task:

Examples

julia
using ComposableRecurrences
const CR = ComposableRecurrences
y = zeros(3)
CR.each!((k, y) -> (y[k] = k^2; nothing), CR.Serial(), 3, 3, y)
y

# output

3-element Vector{Float64}:
 1.0
 4.0
 9.0

Fields

source
ComposableRecurrences.Share Type
julia
struct Share

The share flow form: a ComposableRecurrences.Flow with this form moves a share of the pool it leaves.

Flow out of pool , with demand , moves

with the pool before the step's flows, alongside any ComposableRecurrences.Hazard flows. Shares out of one pool that sum to more than it holds leave it negative. Share() is a form for flows only, not a depletion form.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
CR.Flow(1 => 0, 0.15; form = CR.Share()).form

# output

ComposableRecurrences.Share()

Fields

source
ComposableRecurrences.Split Type
julia
struct Split

The split flow form: a ComposableRecurrences.Flow with this form draws one count from several pools, in proportion to the pools the step starts from.

A split flow names its sources as a tuple, (i_1, …, i_n) => to, with  . With the pool before the step's flows and  , source 's share is

or, when  , all of for the first source. A source that holds less than its share when the flow runs passes the part it cannot cover,   with what it holds, to the other sources in proportion to their , or to the first other source when theirs sum to zero or less. Each source then loses its share and what it was passed, capped as a Truncate() count is, and to gains what they lose. Split() is a form for flows only, not a depletion form.

Examples

Discharges split between unconfirmed and confirmed patients by the patients present at the start of each day, after half the unconfirmed patients are confirmed. On the second day the unconfirmed patients' share is 1.25, but they hold 0.75, so the confirmed patients take the other 0.5:

julia
using ComposableRecurrences
CR = ComposableRecurrences
leave = CR.Flow((:u, :c) => 0, CR.TimeVarying([2.0, 5.0]); form = CR.Split())
d = CR.Depletion(
    CR.Flow(:u => :c, 0.5; form = CR.Share()), leave; pools = (:u, :c)
)
Recurrence([true]; modifiers = (d,))(; history = [6.0; 2.0;;], stop = 2)

# output

2×2 Matrix{Float64}:
 1.5  0.0
 4.5  1.0

Fields

source
ComposableRecurrences.Step Type
julia
struct Step

The role of one step of a modifier, or of a depletion form inside its ComposableRecurrences.Depletion.

A modifier maps the step's values and its own state at absolute time to new ones,

where holds one value per stratum, is the modifier's state after the previous step and its state after this one. A pointwise modifier acts on each stratum separately,  .

  • forward!(m, Step(), v, s, t) updates the step's values v and the modifier's state s in place (one entry per stratum, or one per pool for a ComposableRecurrences.Depletion with several) and returns nothing. A pointwise modifier, with ComposableRecurrences.blocks (1, 1), writes entry k from entry k only, and may be called on a one-entry view of stratum k.

  • forward!(m, Step(), v, s, t, g) is the group step of a blockwise modifier (ComposableRecurrences.blocks), with v and s tuples of one-entry views of group g's values and state.

  • forward!(form, Step(), v, s, N) draws v from pool s in place for a depletion form, with v and s views and N a number.

A step writes its outputs and returns nothing; one that returns anything else is an error. The matching ComposableRecurrences.pullback! takes grads first and then the same arguments, as pullback!(grads, m, Step(), v, s, t).

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0], [80.0]
CR.forward!(CR.Hazard(), CR.Step(), v, s, 100.0)
round.(v; digits = 3), round.(s; digits = 3)

# output

([1.584], [78.416])

Fields

source
ComposableRecurrences.Survival Type
julia
struct Survival{H}

The survival of each cohort through each lag of a kernel against a hazard.

Inside a kernel TimeVarying(s, Primary()), the weight on lag of cohort in stratum is

where is the hazard at lag , any argument of a Derived kernel read as there, = from (0 by default) is the first lag the hazard acts at and is the kernel's first lag (0 in a Convolution, 1 in a Recurrence). Lags before from have survival one. A hazard that changes with calendar time is TimeVarying(h), read at the time   each lag lands; one that changes with the lag is a vector of lag weights.

This is the Recurrence Recurrence([1]) with gain   and a history of one, run over each cohort's lags, computed as part of the kernel: one pass per cohort forward, and one back.

Arguments

  • hazard: the hazard, any argument of a Derived kernel.

Keyword Arguments

  • from: the first lag the hazard acts at, 0 by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# Cohorts confirmed from the step after entry at a hazard `h` per step, and
# still present with probability `S[l + 1]` at lag `l`.
h = [0.1, 0.2, 0.3, 0.4]
S = [1.0, 0.8, 0.5]
confirmed = S * (1 - CR.Survival(TimeVarying(h); from = 1))
CR.kernel_weights(TimeVarying(confirmed, CR.Primary()), 2)

# output

3×2 Matrix{Float64}:
 0.0   0.0
 0.16  0.24
 0.22  0.29

Fields

  • hazard::Any: The hazard.

  • from::Int64: The first lag the hazard acts at.

source
ComposableRecurrences.Threaded Type
julia
struct Threaded <: ComposableRecurrences.Executor

An executor that runs the indices of a loop in contiguous chunks, one task per chunk, the first on the calling task. With m chunks, chunk c covers

There are m = min(ntasks, n) chunks, with ntasks the number of threads unless it is set. ntasks fixes the number of chunks whatever the thread count, so a test can exercise the split paths the same way on any machine. A loop whose work is below min_work, or with one chunk, runs in order on the calling task, as Serial does. The threshold applies to each loop. min_work = 0 forces every loop of more than one index to split and is meant for tests of the threaded paths. The loops of strata that mix then split every step and start tasks every step, so at small sizes it runs much slower than Serial. work counts multiply-adds. Operators split three kinds of loop, and count the work of each kind so that one min_work sets where each of them breaks even:

  • strata that mix through a coupling, a pairwise kernel or a modifier with a vector step: one loop per step, counted in full;

  • independent strata, each over the whole series: one loop per call, counted as an eighth, so it splits from eight times min_work;

  • a convolution with a fixed kernel and its lag contributions: one loop per call of vector multiply-adds, counted as a sixteenth; a convolution that forms each output as one dot, such as one with a time-varying kernel, counts as independent strata do.

In the loops split once per call, a multiply-add counts once per 64-bit word of the element type, so a dual number with 8 partials counts 9. An element type that is not a bits type, such as BigFloat or a tracked real, counts as one word, as do the floats of an AD backend that carries its tangents or shadows beside the arrays rather than in them. Loops split every step count each multiply-add once whatever the type.

The default min_work of 500 000 comes from whole-loss timings (benchmark/threshold.jl). Strata that mix split only with a pairwise kernel over a few hundred strata or a coupling over tens of thousands. Results are identical to Serial because each index writes only its own slots. A reverse pass sums per chunk the cotangents of parameters that chunks of strata share, such as a scalar modifier parameter, so those agree with Serial up to rounding. Errors inside a split loop arrive wrapped in a CompositeException: an error in a chunk on a new task as a TaskFailedException, and one in the chunk the calling task runs as an exception that shows it with its backtrace. On arrays that live on a GPU, Threaded runs a call as Parallel on the arrays' own backend, as Serial does: host threads cannot index them.

Examples

julia
using ComposableRecurrences
const CR = ComposableRecurrences
y = zeros(4)
ex = CR.Threaded(; min_work = 0, ntasks = 2)
CR.each!((k, y) -> (y[k] = k^2; nothing), ex, 4, 4, y)
y

# output

4-element Vector{Float64}:
  1.0
  4.0
  9.0
 16.0

Fields

  • min_work::Int64: The smallest loop work that is split across threads.

  • ntasks::Int64: The most chunks a loop is split into; 0 uses the number of threads.

source
ComposableRecurrences.TimeVarying Type
julia
struct TimeVarying{I, A}

A coefficient that changes over time: adds a trailing time axis to its slot.

Column of the array holds the coefficient for absolute time , counted from 1, so a resumed call carries on through the same array. With the default indexing the step at time reads ; a Primary() kernel's weight on lag is read from column  :

A kernel is L × T, or TimeVarying(PerStratum(G)) with G S × L × T: TimeVarying is always the outer wrapper. It may also be a vector of T columns of any lengths, ks[τ] being column , with zero weight past each column's end, so a Primary() pmf truncated at the horizon visits only its entries. Like an array, the columns are held as given, not copied: host columns of one concrete type, vectors or views, are read where they are, so changing one after building the kernel changes the kernel. Columns of mixed types, columns of tracked numbers and columns on a device are stacked into one vector instead, as is a kernel that adapt moves to a device. A Recurrence coupling is S × S × T. A modifier parameter is length T, or TimeVarying(PerStratum(B)) with B S × T.

A coefficient that changes at a few times is given by its change points, [t_1 => c_1, t_2 => c_2, ..., t_J => c_J] with     :

so the last value holds at every later time and the coefficient covers any stop. Each value has the form of one column: a number for a parameter, a vector of lag weights for a kernel (shorter ones padded with zero weights), an S × S matrix for a coupling, or a PerStratum of these. Only the values are stored: they are copied when stacked into one array, so changing a value after building the coefficient does not change it. Pairwise values are not taken; a pairwise kernel is the dense TimeVarying(Pairwise(A)). Values and gradients equal those of the dense array that repeats each value over its segment. Inside a differentiated function, build the pairs as Pair.(starts, values) or a comma-separated literal, not by vcat (one backend loses their derivatives).

The indexing sets which time a kernel's column belongs to, and is held as a type parameter so nothing branches on it:

  • ComposableRecurrences.Secondary (the default): column t weights the inputs reaching output t. This is the only meaning outside a kernel.

  • ComposableRecurrences.Primary: column c is the kernel of the input at time c, which spreads forward through it. In a Recurrence the input is the output at time c, so each output keeps the kernel of the time it was produced.

The two agree for a fixed kernel.

Arguments

  • x: the coefficients, time on the last axis, a PerStratum of them, a vector of kernel columns, or a vector of start => value change points.

  • indexing: Secondary() (default) or Primary().

Examples

julia
using ComposableRecurrences
G = [0.8 0.7; 0.2 0.3]  # lags 1 and 2 over two steps
Recurrence(TimeVarying(G))(1.0; history = [1.0, 1.0], stop = 2)

# output

2-element Vector{Float64}:
 1.0
 1.0

A delay pmf per input time, truncated at the horizon:

julia
using ComposableRecurrences
ks = [[0.5, 0.5], [0.75, 0.25], [1.0]]
Convolution(TimeVarying(ks, ComposableRecurrences.Primary()))(ones(3))

# output

3-element Vector{Float64}:
 0.5
 1.25
 1.25

A generation interval that shortens from time 6, given by its change points, against the dense array that repeats each kernel:

julia
using ComposableRecurrences
long_gi, short_gi = [0.2, 0.5, 0.3], [0.6, 0.4]
r = Recurrence(TimeVarying([1 => long_gi, 6 => short_gi]))
y = r(1.2; history = ones(3), start = 4, stop = 8)
G = hcat([t < 6 ? long_gi : [short_gi; 0.0] for t in 1:8]...)
dense = Recurrence(TimeVarying(G))(1.2; history = ones(3), start = 4, stop = 8)
y ≈ dense, round.(y; digits = 3)

# output

(true, [1.2, 1.248, 1.475, 1.661, 1.904])

Fields

  • x::Any: The coefficients, time on the last axis.
source
ComposableRecurrences.Trace Type
julia
struct Trace

The role of a modifier's trace: what a call with record = (:trace,) records for it at each step.

At absolute time the modifier maps its values and state to , and its trace is

with the modifier's own map: by default its state after the step,  , and a modifier whose state never changes, such as ComposableRecurrences.Transform, records nothing. A ComposableRecurrences.Depletion with a draw records its pools after the step, the value it passes on and the overflow   , what its draws leave of the demand and the queue (zero without one), with rows for each pool, then the values passed on, then the overflows, each over the strata or groups; without a draw it records the amount each flow moves, a row per flow over the groups, by name when every flow is named. ComposableRecurrences.Redistribute records its arrivals, its state. A modifier records its trace with forward!(m, Trace(), r, v, s, v′, s′, t), writing into r, which takes the shape of v for its kind of step: for a pointwise modifier (ComposableRecurrences.ispointwise) a tuple of vectors, one per trace value, indexed by stratum as v is, their kth entries filling row (j - 1) * S + k; for a blockwise modifier (ComposableRecurrences.blocks), as forward!(m, Trace(), r, v, s, v′, s′, t, g) for group g, a tuple of one-entry views filling rows (j - 1) * G + g for groups, with v, s, v′ and s′ tuples of one-entry views; for any other modifier the step's column of ComposableRecurrences.ntrace rows. Its pullback, pullback!(grads, m, Trace(), v, s, t) (with g for a group), is given grads = (; piece, trace, v, s, v′, s′): trace holds the cotangent of r, in its shape, and the pullback adds the cotangents of the step's inputs and outputs into v, s, v′ and s′ and those of the modifier's parameters into piece.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = ([0.0], [0.0], [0.0])
CR.forward!(CR.Depletion(100.0), CR.Trace(), r, [2.0], [80.0], [1.6], [78.4], 1)
r

# output

([78.4], [1.6], [0.3999999999999999])

Fields

source
ComposableRecurrences.Transform Type
julia
struct Transform{F, P}

A modifier that maps each stratum's value through a function f, with optional parameters θ.

At time , for each stratum ,

where is the stratum's value when the modifier is reached (after the modifiers before it in the tuple), its value after, and the unused state. is the parameter θ read at stratum and time . A tuple or NamedTuple of these is read entry by entry, so f receives a tuple or NamedTuple of scalars. Without θ the map is  .

The reverse pass, for output cotangent , is

with the partial derivatives from the map's local rule, a ComposableRecurrences.pullback! method for f in the ComposableRecurrences.Local role, when it has one, or else from a local forward-mode derivative of f. The local rule receives the step's output   from the forward pass, so a derivative written in terms of the value need not recompute it. Values captured by f (a closure, or a callable struct with float fields) are not in , so the AD backend differentiates the Recurrence holding such a map.

Three maps have their own pullbacks. Transform(+, b) adds where it sits in the tuple. After a ComposableRecurrences.Depletion, the added values are neither scaled by nor drawn from the pool. Alone, Transform(+, TimeVarying(PerStratum(B))) gives the values of passing B as add. Transform(clamp, lo, hi) bounds each value to , the parameters lo and hi, with  . Its pullback sends the cotangent to the active bound, or to when neither is. Transform(*, γ) scales each value by . First in the modifiers, it scales the add values with the kernel's, so the gain acts on both before an ComposableRecurrences.Allocate or a draw. A γ that is a plain number has no cotangent, so its pullback adds none.

It acts on a Recurrence and is pointwise. Its rule takes the map's local rule or the local forward-mode derivative, or a hand-written pullback for +, clamp and *.

Arguments

  • f: the map, called as f(v) or f(v, θ).

  • θ: the parameters, or nothing.

  • lo, hi: with clamp, the lower and upper bounds, each a parameter.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# Iterate a probability generating function, q_t = G(q_{t-1}) from q_0 = 0:
# q_t is the probability that a negative binomial branching process has
# died out by generation t.
G(s, θ) = (θ.p / (1 - (1 - θ.p) * s))^θ.r
q = CR.Transform(G, (; r = 0.5, p = 0.4))
y = Recurrence([1.0]; modifiers = (q,))(; history = [0.0], stop = 6)
round.(y; digits = 3)

# output

6-element Vector{Float64}:
 0.632
 0.803
 0.879
 0.92
 0.945
 0.961

Each partial derivative of G contains G itself, so a local rule for it can read the output:

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct NBPGF end
(::NBPGF)(s, θ) = (θ.p / (1 - (1 - θ.p) * s))^θ.r
function CR.pullback!(grads, ::NBPGF, ::CR.Local, y, s, θ)
    D = 1 - (1 - θ.p) * s
    return y * θ.r * (1 - θ.p) / D,
        (; r = y * log(θ.p / D), p = y * θ.r * (1 - s) / (θ.p * D))
end
q = CR.Transform(NBPGF(), (; r = 0.5, p = 0.4))
y = Recurrence([1.0]; modifiers = (q,))(; history = [0.0], stop = 3)
round.(y; digits = 3)

# output

3-element Vector{Float64}:
 0.632
 0.803
 0.879

Fields

  • f::Any: The map, called as f(v) or f(v, θ).

  • θ::Any: The parameters, or nothing.

source
ComposableRecurrences.Truncate Type
julia
struct Truncate{K, W, I, O}

The truncated depletion form: the value is drawn in full while the pool holds it, and the pool is drawn down to zero otherwise.

For one stratum at one step, with  ,

where is the value asked for, the pool before the step, the value drawn and the pool after the step. The population is not read. The minimum has a kink at   and the floor one at  ; the derivative takes the active branch, and the value asked for on a tie. A NaN pool gives a NaN draw.

Truncate(κ) replaces the minimum by a smooth one of softness :

with   and   when or is zero. Then   , with   at  , and tends to the minimum as   or as and part. A non-positive value is drawn as it is, and the floor at   keeps its kink.   is the exact minimum; Truncate() is that form with no softness to differentiate.

Arguments

  • κ: the softness, with   ; omitted for the exact minimum.

Keyword Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0, 2.0], [80.0, 1.5]
CR.forward!(CR.Truncate(), CR.Step(), v, s, 100.0)
v, s

# output

([2.0, 1.5], [78.0, 0.0])
julia
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0], [2.0]
CR.forward!(CR.Truncate(0.1), CR.Step(), v, s, 100.0)
round.(v; digits = 3), round.(s; digits = 3)

# output

([1.866], [0.134])

Fields

  • κ::Any: The softness κ, or nothing for the exact minimum.

  • weights::Any: As a draw, each pool's weight by name, or nothing.

  • into::Any: As a draw, the pool it fills, or nothing.

  • overflow::Any: As a draw, where what it leaves goes.

source
ComposableRecurrences.add_cotangent! Function
julia
add_cotangent!(_::Union{Nothing, NamedTuple{()}}, v, idx...)

Add v to the mirror x̄ at index idx,

so the cotangents from every use of a parameter sum. This is x̄[idx...] += v for an array, x̄[] += v for a Ref (the index is ignored), the same into the array of a wrapper's (; x) mirror, and nothing for nothing or the empty mirror (;) of an object with no fields.

Arguments

  • x̄: the mirror: an array, a Ref, (; x), (;) or nothing.

  • v: the cotangent to add.

  • idx: the index into an array mirror.

Examples

julia
using ComposableRecurrences
x̄ = zeros(2)
ComposableRecurrences.add_cotangent!(x̄, 1.5, 2)
x̄

# output

2-element Vector{Float64}:
 0.0
 1.5
source
ComposableRecurrences.add_param! Function

Add the cotangent v of the parameter x, read at stratum k and absolute time t, into its mirror x̄.

For a scalar loss and the value read by ComposableRecurrences.param,

so v lands in the entry param read, or, for a Derived parameter, in each of its arguments by the chain rule. A modifier's ComposableRecurrences.pullback! writes every parameter's cotangent through add_param!, with x̄ from ComposableRecurrences.cotangent, so it accepts every parameter form. A nothing mirror takes nothing for x itself, but a Recent parameter still sends its cotangent to the outputs it read, so a pullback calls add_param! for every parameter whatever its mirror.

Arguments

  • x̄: the mirror of x.

  • x: the parameter.

  • v: the cotangent of the value read.

  • k: the stratum.

  • t: the absolute time.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
x̄ = (; x = zeros(3))
CR.add_param!(x̄, TimeVarying([1.0, 2.0, 3.0]), 0.5, 1, 2)
x̄.x

# output

3-element Vector{Float64}:
 0.0
 0.5
 0.0
source
ComposableRecurrences.blocks Function
julia
blocks(m) -> Tuple{Int64, Int64}

Return the group shape of modifier m: (nv, ns), its values and state entries per group, or nothing when its step reads the whole vectors.

A modifier with (nv, ns) holds pools of groups each in its values and in its state, pool by pool: with   strata, value    is pool of group and state entry    is state pool of group . Its step factorises over groups: at absolute time , group 's new values and state depend only on its own,

(1, 1) is a pointwise modifier (ComposableRecurrences.ispointwise), whose groups are the strata: it implements forward!(m, Step(), v, s, t) writing entry k of v and s from entry k only, for each k in eachindex(v). The operator may call it on a one-entry view of stratum k, whose axes are k:k, so a parameter read at k through ComposableRecurrences.param reads the right entry; a broadcast against a field with one entry per stratum, such as v .*= m.w, cannot run on such a view. Any other shape is blockwise: the modifier implements forward!(m, Step(), v, s, t, g) with v and s tuples of one-entry views of group g's values and state entries, writing them in place, and optionally pullback!(grads, m, Step(), v, s, t, g) with grads.v and grads.s tuples of views, overwritten with the input cotangents. Both return nothing, and the default vector ComposableRecurrences.Step loops the groups. The group step reads parameters at group g, so a PerStratum parameter has entries. blocks should follow from the type of m, not from the value of a field, so the loops are compiled for its shape; a shape read from a field is known only at run time. ComposableRecurrences.ispointwise and ComposableRecurrences.nstate follow from it. The default is nothing. Groups of different sizes, such as the patches of ComposableRecurrences.Allocate, are a value of the modifier, so its blocks is nothing.

Arguments

  • m: the modifier.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
weights = (S = 1, V = 0.3)
leaky = CR.Depletion(100.0, CR.Hazard(; weights); pools = (:S, :V))
CR.blocks(leaky), CR.blocks(CR.Transform(clamp, 0.0, 1.0)), CR.blocks(nothing)

# output

((1, 2), (1, 1), nothing)
source
ComposableRecurrences.convert_floats Function
julia
convert_floats(_::Type{T<:AbstractFloat}, x)

Convert every float x holds to the float type T: float arrays, which stay on their device, and single floats, such as a population or a scale. Each float becomes the nearest value of type T,

Integers, Bools, numbers that are not floats (such as dual numbers), functions and the structure of x are kept.

An operator's output takes its float type from every array and number it is given, so a Float64 parameter promotes a run on Float32 arrays to Float64. Converting the whole model keeps the run in T, which a GPU needs: most run Float32 much faster, and some have no Float64 at all. Compose it with a device move, for example adapt(CuArray, convert_floats(Float32, r)).

It needs Functors.jl, whose fmap walks the model: run using Functors first.

Arguments

  • T: the float type, such as Float32.

  • x: an operator, a modifier, a coefficient or an array.

Examples

julia
using ComposableRecurrences, Functors
using ComposableRecurrences: Depletion, convert_floats
r = Recurrence([0.5, 0.3]; modifiers = (Depletion(60.0),))
y = convert_floats(Float32, r)(Float32.(fill(1.2, 4)); history = Float32[1, 1])
eltype(y)

# output

Float32
source
ComposableRecurrences.cotangent Function
julia
cotangent(_::Nothing, name::Symbol)

Return the cotangent of field name in the mirror x̄ of a struct, or nothing when x̄ is nothing or has no such field.

For a struct with fields and a scalar loss , the mirror holds

and this returns for the field named name.

A mirror holds a struct's cotangents for a ComposableRecurrences.pullback!, one entry per field: a Ref for a float scalar, an array of the same shape for a float array, and nothing for an integer, range or function.

Arguments

  • x̄: the mirror, a NamedTuple of field mirrors or nothing.

  • name: the field.

Examples

julia
using ComposableRecurrences
ComposableRecurrences.cotangent((; K = zeros(2)), :K)

# output

2-element Vector{Float64}:
 0.0
 0.0
source
ComposableRecurrences.delay_masses Function
julia
delay_masses(
    k::AbstractVector,
    lags;
    step
) -> AbstractVector
julia
delay_masses(k, lags; step = 1)

Return the masses of a delay k on lags 0 to lags - 1, lag 0 first, as a vector of length lags:

where is the delay in its own unit, = step is the width of a lag in that unit and = lags. With the default step = 1 a lag is one unit of the delay. A delay on continuous time is censored with both windows one step wide: its primary event is uniform over one step and runs from the start of that step, so four masses with step = 0.25 do not sum to the mass with step = 1. A Convolution kernel is this vector. A Recurrence kernel starts at lag 1, so it is the vector without , and its sum scales the gain. lags has no default: a kernel of delays without lags is an error, and so is lags on a kernel with no delays. Both operators pass step on, and step without lags is an error. A step other than 1 suits a model whose time unit differs from the delay's unit, such as step = 7 for weekly steps and delays in days.

The method for a vector returns it as it is, whatever lags and step. A package that owns a delay type adds a method for that type:

  • it returns an AbstractVector of length lags, lag 0 first;

  • it takes step as a keyword, defaulting to 1, and gives lag l the mass on  ; the operators always pass it, so a method that serves step = 1 only still takes the keyword;

  • it builds the masses from the delay's parameters with differentiable operations, so that gradients reach those parameters through the kernel;

  • it does not normalise the masses or fold the mass past lags - 1 into the last lag, since where a delay is cut is the caller's choice.

A type with a method is a delay, whatever its supertype, so Recurrence(kernel; lags) and Convolution(kernel; lags) take it. An array of delays is read by its element type, so that type, or a supertype of it, needs the method.

A delay on continuous time has masses only once a censoring choice turns it into one on whole steps, so a method for it belongs with that choice. A package extension adds one that double interval censors the delay.

Arguments

  • k: the delay, or a vector of masses.

  • lags: the number of lags, from lag 0.

Keyword Arguments

  • step: the width of a lag in the delay's own unit; 1 by default.

Examples

julia
using ComposableRecurrences
k = [0.2, 0.5, 0.3]
ComposableRecurrences.delay_masses(k, 3) === k

# output

true
source
julia
delay_masses(ds::Tuple{Any, Vararg{Any}}, lags; step) -> Any

Return the masses of a chain of delays ds, each a delay or a vector of masses: the first lags masses of their full linear convolution,

Each delay's masses come from its own method, on lags step units wide. A vector of masses is read as given, whatever its length and step, so it must already be on lags of that width.

A chain of discretised delays and a sum of continuous delays discretised once are different models.

Examples

julia
using ComposableRecurrences
a, b = [0.5, 0.5], [0.2, 0.8]
ComposableRecurrences.delay_masses((a, b), 3),
Convolution((a, b); lags = 4).kernel

# output

([0.1, 0.5, 0.4], [0.1, 0.5, 0.4, 0.0])
source
ComposableRecurrences.exponential_history Function
julia
exponential_history(I0::Real, r::Real, L::Integer) -> Any

Return a geometric history of L steps that grows by a factor each step and ends at I0, to seed a Recurrence.

For one series, and for stratum of , it is

oldest first, so  .

Arguments

  • I0: the value at the last step; a vector gives one per stratum.

  • r: the rate per step; with a vector I0, a scalar or one per stratum. ComposableRecurrences.growth_rate gives it from a reproduction number and generation interval.

  • L: the number of steps, at least 1, usually the kernel length.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
g = [0.2, 0.5, 0.3]
h = CR.exponential_history(5.0, 0.1, length(g))
round.(vcat(h, Recurrence(g)(fill(1.2, 6); history = h)); digits = 3)

# output

9-element Vector{Float64}:
 4.094
 4.524
 5.0
 5.388
 5.922
 6.454
 7.042
 7.694
 8.395
source
ComposableRecurrences.forward! Function

Run x in role on primal arguments args, writing the outputs in place.

For the role's inputs it computes its outputs

with the map of the role: ComposableRecurrences.Step a modifier step  , ComposableRecurrences.Init an initial state from the history, ComposableRecurrences.Pressure a coupling   and ComposableRecurrences.Trace a modifier's record  . The outputs are written into the leading array arguments, and the method returns nothing; returning anything else is an error. To extend the package, define a type and add this method for its role: ComposableRecurrences.Step and ComposableRecurrences.Init for a modifier or depletion form, ComposableRecurrences.Pressure for a coupling and ComposableRecurrences.Trace for a modifier's record.

A pointwise step runs under ComposableRecurrences.Parallel when it reads and writes only eachindex(v) entries, and allocates nothing.

Arguments

  • x: the coupling, modifier or depletion form.

  • role: Step(), Init(), Pressure() or Trace().

  • args: the role's arguments.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Offset{T}
    b::T
end
CR.blocks(::Offset) = (1, 1)
function CR.forward!(m::Offset, ::CR.Step, v, s, t)
    for k in eachindex(v)
        v[k] += m.b
    end
    return nothing
end
r = Recurrence([0.5, 0.5]; modifiers = (Offset(1.0),))
r(1.0; history = ones(2), stop = 4)

# output

4-element Vector{Float64}:
 2.0
 2.5
 3.25
 3.875
source
ComposableRecurrences.growth_rate Function
julia
growth_rate(R::Real, g::AbstractVector{<:Real}) -> Any

Return the growth rate per step of a renewal with reproduction number R and generation interval g, from the Euler–Lotka equation

where is g[l], the weight on lag , as in a Recurrence kernel. It gives the rate that ComposableRecurrences.exponential_history needs for a seed that grows as the renewal does.

The derivative in R and g is exact under every automatic differentiation backend, without a rule.

Arguments

  • R: the reproduction number, positive.

  • g: the generation interval, with g[1] the weight on lag 1; its weights are non-negative with a positive sum.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
g = [0.2, 0.5, 0.3]
r = CR.growth_rate(1.5, g)
residual = 1.5 * sum(g[l] * exp(-r * l) for l in 1:3)
round(r; digits = 4), round(residual; digits = 8)

# output

(0.1977, 1.0)
source
ComposableRecurrences.islinear Function
julia
islinear(x) -> Bool

Return whether forward! of coupling or modifier x is linear in its input and does not read the time.

For a coupling this is forward!(C, Pressure(), q, p, t) linear in p; for a whole-step modifier (ComposableRecurrences.blocks nothing, neither pointwise nor blockwise) with no state of its own, it is forward!(m, Step(), v, s, t) linear in v. Either is then a matrix with

for every . A Recurrence call builds once, from forward! on the basis vectors, and runs the built-in dense coupling, or a dense step, in its place, so the gradient takes the built-in's pullback! and the outer AD differentiates the calls of forward!. A forward! written as a matrix product, such as mul!(q, C.K, p), then gives a gradient close to the built-in's; one written as scalar loops is differentiated loop by loop, so a pullback! of its own is still faster. A type with its own pullback! for the role keeps it, as does a call through ComposableRecurrences.NoAdjoint. Declare it from the type, ComposableRecurrences.islinear(::MyType) = true, so the route folds. ComposableRecurrences.PieceInterface checks the declaration. The default is false.

Arguments

  • x: the coupling or modifier.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Mix{M}
    K::M
end
function CR.forward!(C::Mix, ::CR.Pressure, q, p, t)
    q .= C.K * p
    return nothing
end
CR.islinear(::Mix) = true
r = Recurrence([0.5, 0.3]; coupling = Mix([0.9 0.1; 0.2 0.8]))
y = r(fill(1.1, 2, 4); history = ones(2, 2))
y ≈ Recurrence([0.5, 0.3]; coupling = [0.9 0.1; 0.2 0.8])(
    fill(1.1, 2, 4); history = ones(2, 2)
)

# output

true
source
ComposableRecurrences.isstateless Function
julia
isstateless(m) -> Bool

Return whether modifier m leaves its state unchanged in its ComposableRecurrences.Step.

A stateless modifier's state after every step is the state it started with,

where is the state after the step at time and the number of steps. Its trace then has no rows, and the reverse pass reads in place of a record of the state per step. The default is false; a modifier declares it for its type, and the optional stateless component of ComposableRecurrences.PieceInterface checks the declaration.

Arguments

  • m: the modifier.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
CR.isstateless(CR.Transform(clamp, 0.0, 1.0)), CR.isstateless(CR.Depletion(9.0))

# output

(true, false)
source
ComposableRecurrences.kernel_weights Function
julia
kernel_weights(
    kernel::TimeVarying{ComposableRecurrences.Primary, <:Union{ComposableRecurrences.Derived, ComposableRecurrences.Increments, ComposableRecurrences.Normalised, ComposableRecurrences.Survival}},
    n::Integer
) -> Any

Return the weights of the computed kernel TimeVarying(w, Primary()), with w a Derived or ComposableRecurrences.Survival. They cover the cohorts at times 1 to n, as an array: L × n, or S × L × n with strata, lag 0 first,

where is the weight on lag of cohort and the kernel's number of lags.

Every entry is computed, so a TimeVarying(h) argument read at the time   a weight lands covers the times up to n + L - 1, and a TimeVarying(c, Primary()) one the times up to n. It is differentiable, with the reverse pass of Derived and ComposableRecurrences.Survival.

Arguments

  • kernel: the kernel, TimeVarying(w, Primary()) with w a Derived or a Survival.

  • n: the number of cohorts.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
# The probability each cohort has been reported by each delay, against a
# hazard that falls with the delay and rises with the calendar time.
base = [0.2, 0.3, 0.4]
level = TimeVarying([1.0, 1.0, 1.2, 1.2])
reported = 1 - CR.Survival(CR.Derived(*, base, level))
round.(CR.kernel_weights(TimeVarying(reported, CR.Primary()), 2); digits = 3)

# output

3×2 Matrix{Float64}:
 0.2    0.2
 0.44   0.488
 0.709  0.734
source
ComposableRecurrences.nstate Function
julia
nstate(m, S) -> Any

Return the number of state entries modifier m keeps for S strata, from its ComposableRecurrences.blocks.

The recurrence allocates each modifier's state with

passes it to the modifier's ComposableRecurrences.Init and ComposableRecurrences.Step, and checks a resumed state against it. A pointwise modifier keeps one entry per stratum, and a Depletion with two pools keeps the first pool then the second,  . Of the built-ins with blocks nothing, an ComposableRecurrences.Allocate with imports keeps its import pattern as well.

Arguments

  • m: the modifier.

  • S: the number of strata.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
weights = (S = 1, V = 0.3)
leaky = CR.Depletion(100.0, CR.Hazard(; weights); pools = (:S, :V))
CR.nstate(CR.Transform(clamp, 0.0, 1.0), 3), CR.nstate(leaky, 3)

# output

(3, 6)
source
ComposableRecurrences.ntrace Function
julia
ntrace(m, S) -> Any

Return the number of rows of a modifier's trace for S strata, one column per step.

For a modifier with trace values per stratum, or per group of a blockwise modifier with groups,

the default is the modifier's ComposableRecurrences.nstate, its state after each step, or none for a modifier whose state never changes (ComposableRecurrences.isstateless).

Arguments

  • m: the modifier.

  • S: the number of strata.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
CR.ntrace(CR.Transform(clamp, 0.0, 1.0), 3), CR.ntrace(CR.Depletion(100.0), 3)

# output

(0, 9)
source
ComposableRecurrences.param Function

Return the value of the modifier parameter x at stratum k and absolute time t.

A parameter is one value , PerStratum giving , TimeVarying giving , TimeVarying(PerStratum(x)) giving , or a Derived parameter computed from these:

A Recent reads the recurrence's own recent outputs instead. A modifier reads every parameter through param, and writes its cotangent through ComposableRecurrences.add_param!, so it accepts every parameter form, including forms added later.

Arguments

  • x: the parameter.

  • k: the stratum.

  • t: the absolute time.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
x = TimeVarying(PerStratum([1.0 2.0; 3.0 4.0]))
CR.param(x, 2, 1), round(CR.param(2 * CR.Derived(sqrt, x), 2, 1); digits = 3)

# output

(3.0, 3.464)
source
ComposableRecurrences.param_rows Function
julia
param_rows(m, S)

Return how many rows each top-level parameter field of a whole-step modifier m has in a call over S strata, or nothing to skip the check.

A row is one entry of a PerStratum or one row of a TimeVarying(PerStratum(x)). Before its ComposableRecurrences.Init, each call checks

where is the field and this count, and throws a DimensionMismatch that names a field that fails. Pointwise and blockwise modifiers ignore it: their rows follow from ComposableRecurrences.blocks.

Arguments

  • m: the modifier, with blocks(m) === nothing.

  • S: the number of strata in the call.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Mix{A}
    a::A
end
function CR.forward!(m::Mix, ::CR.Step, v, s, t)
    v .*= CR.param.(Ref(m.a), eachindex(v), t)
    return nothing
end
CR.param_rows(::Mix, S) = S
r = Recurrence([0.5]; modifiers = (Mix(PerStratum([1.0, 2.0])),))
r(ones(3, 2); history = ones(3, 1))

# output

ERROR: DimensionMismatch: a has 2 rows, expected 3
source
ComposableRecurrences.pressure Function
julia
pressure(r::Recurrence, y; kwargs...) -> Any

Compute the pressure each step of r draws against, given its outputs y: the kernel convolution of the past values, mixed by the coupling, before the gain, add input and modifiers,

with the symbols of Recurrence. is what the coupling's ComposableRecurrences.Pressure role writes, computed as the step computes it, for any kernel and coupling a Recurrence takes. for   comes from history, as in the call. For one series with kernel and no coupling,   , the convolution of with lagged by one step.

For the outputs of r(gain; history) without modifiers or an add input,   , so y ./ pressure(r, y; history) returns the gain. With modifiers or added values the ratio is the gain as realised on each step, with their effect included. Where is zero the ratio is NaN or Inf. For outputs from a traced call, trace.pressure is the same pressure. It is differentiable in the outputs, the history, the kernel and the coupling. pressure(NoAdjoint(r), y) gives the same values with the rule turned off, as ComposableRecurrences.NoAdjoint does for the call.

Arguments

  • r: the recurrence, or NoAdjoint(r).

  • y: its outputs at times start to start + T - 1, length T for a single series or S × T.

Keyword Arguments

  • history: the outputs before start, as passed to the call; zeros when left out.

  • start: the first time, as passed to the call; 1 by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.6, 0.4]; coupling = [0.9 0.1; 0.2 0.8])
R = [1.2 1.1 1.0; 0.9 1.3 1.0]
h = [1.0 2.0; 3.0 1.0]
y = r(R; history = h)
y ./ CR.pressure(r, y; history = h) ≈ R

# output

true
source
ComposableRecurrences.pullback! Function

Accumulate the reverse pass of ComposableRecurrences.forward! for x in role.

For forward! computing outputs   from inputs and the object's parameters , given the output cotangent (the gradient of a scalar loss with respect to ) it adds

grads is a NamedTuple: grads.piece holds , mirroring the object's parameters (or is nothing), and the other fields are named after the role's arguments. Output cotangents are read on entry and input cotangents accumulated; a buffer forward! updated in place is overwritten with the cotangent of its incoming value. It returns nothing. A pointwise or blockwise Step gets the same views as its forward!, with grads.v and grads.s views of the same entries. The mirror grads.piece has one entry per field: a Ref for a float scalar, an array of the same shape for a float array and nothing for a field held constant. An operator's native rule calls a method whose grads and arguments after the role are untyped, as only such a method sets ComposableRecurrences.uses_adjoint. Without one, the object is differentiated by a local dual-number step inside the rule where that is cheap, and the whole operator takes plain AD otherwise.

Arguments

  • grads: the cotangents, (; piece, ...), with piece the mirror of x's parameters.

  • x: the operator, coupling, modifier or depletion form.

  • role: the role.

  • args: the primal arguments forward! was given.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
m = CR.Transform(clamp, 0.0, 1.0)
grads = (; piece = (; θ = (Ref(0.0), Ref(0.0))), v = [1.0], s = [0.0])
CR.pullback!(grads, m, CR.Step(), [2.0], [0.0], 1)
grads.v, grads.piece.θ[2][]

# output

([0.0], 1.0)
source
ComposableRecurrences.trace_rows Function
julia
trace_rows(
    m,
    S
) -> NamedTuple{(:smoothed, :left), <:Tuple{Any, Any}}

Return the names of a modifier's trace rows for S strata, or nothing.

A named tuple of row counts , in row order and summing to ComposableRecurrences.ntrace ,

makes a call return the trace as a named tuple of views of its matrix, one per name; nothing, the default, returns one matrix.

Arguments

  • m: the modifier.

  • S: the number of strata.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
P = [0.0 1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0]
m = CR.Allocate(
    [1:2, 3:3], 10.0; imports = (0.2, P), trace_imports = Val(true)
)
CR.trace_rows(m, 3)

# output

(pattern = 3, imports = 3)
source
ComposableRecurrences.window_sums Function
julia
window_sums(
    x::AbstractVecOrMat,
    ends::AbstractVector{<:Integer};
    dims
) -> Any

Sum x over consecutive windows along dimension dims, the first from time 1 and each later one from the time after the end before it,

with = ends[v] clamped to 0:n, the length of x along dims. A matrix gives its sums in place of dimension dims. It is differentiable in x, with a reverse pass that adds each window's cotangent to its times.

Arguments

  • x: a vector, or a matrix with time along dims.

  • ends: the last time of each window; one not after the end before it gives an empty window, whose sum is zero, and the next window starts after it, so a time can fall in more than one window.

  • dims: the dimension of x that is time; the last by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
daily = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
CR.window_sums(daily, [2, 5, 5, 8])

# output

4-element Vector{Float64}:
  3.0
 12.0
  0.0
  6.0
source
julia
window_sums(
    x::AbstractVecOrMat,
    starts::AbstractVector{<:Integer},
    stops::AbstractVector{<:Integer};
    dims
) -> Any

Sum x along dimension dims over windows given by their first and last times, which may leave gaps between them or overlap,

with = starts[v] and = stops[v], each window cut to the times 1:n of x along dims. A matrix gives its sums in place of dimension dims. It is differentiable in x.

Arguments

  • x: a vector, or a matrix with time along dims.

  • starts: the first time of each window.

  • stops: the last time of each window; one before its start gives an empty window, whose sum is zero.

  • dims: the dimension of x that is time; the last by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
daily = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
# A gap after the first window, then two windows that share day 5.
CR.window_sums(daily, [1, 4, 5], [2, 5, 7])

# output

3-element Vector{Float64}:
  3.0
  9.0
 11.0
source