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))
shared across strataGather(p, rows)
batches of strataBatched(K), an S × B × h history
multiplicative inputr(gain; ...)
additive inputadd =, before the modifiers
seed and resumehistory =, state =
reorder, repeat or drop strataselect(state, strata)
step a state in placeadvance!(r, state, gain)
a state as one vectorvec(state), State(like, x; t)
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 step, or a forward! for a role

To extend the package with a modifier, define a type and add a ComposableRecurrences.step method, and optionally a ComposableRecurrences.step_pullback method. A coupling, or a modifier whose step reads every stratum at once, adds 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.AbstractParameter Type
julia
abstract type AbstractParameter

The supertype of a value read at each stratum and absolute time ,

wherever a modifier, a Recurrence's gain or add, or a Derived takes a parameter.

A subtype implements ComposableRecurrences.param(x, k, t), and ComposableRecurrences.add_param!(x̄, x, v, k, t) to take a cotangent. Arithmetic with one on either side builds a Derived. PerStratum and TimeVarying are parameters by their contents instead.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Ramp <: CR.AbstractParameter
    slope::Float64
end
CR.param(x::Ramp, k, t) = x.slope * t
round.(CR.param.(Ref(2 * Ramp(0.1)), 1, 1:3); digits = 2)

# output

3-element Vector{Float64}:
 0.2
 0.4
 0.6

Fields

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

A modifier that rescales each group of strata to a total given from outside the model, each stratum keeping its share of its group:

where is stratum 's value after the earlier modifiers, the strata of group , its total at time and the machine epsilon of the buffer eltype. With imports = (fraction, pattern) a fraction of each total is placed by the import pattern   and the rest by the spilled values   (  without spill):

total and fraction are parameters over groups, not strata: PerStratum holds one value per group, and a bare matrix is read as groups × time. Allocate with imports works through an import pattern and a spill.

Arguments

  • groups: a vector of index ranges or vectors, one per group, partitioning the strata; a group may be empty, as Int[] or 3:2. They are stored flat, in the fields strata (each group's strata in turn) and offsets (where each group starts).

  • 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 pattern and imports, after spilled with spill (see ComposableRecurrences.trace_rows); it needs imports.

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

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.Batched Type
julia
struct Batched{M<:(AbstractMatrix)}

A coupling that mixes each batch of strata by the same   matrix K, for independent copies of an -stratum model run as strata.

Stratum    is stratum of batch , and the pressure on it is

where holds each stratum's kernel convolution and is the number of strata of the call over .

Arguments

  • K: the   matrix, weighting stratum in stratum of the same batch.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
K = [0.9 0.1; 0.2 0.8]
h = ones(2, 3, 2) .* [1.0 2.0 3.0]  # S × B × h
y = Recurrence([0.5, 0.5]; coupling = CR.Batched(K))(1.2; history = h, stop = 4)
each = Recurrence([0.5, 0.5]; coupling = K)
size(y), y[:, 3, :] ≈ each(1.2; history = h[:, 3, :], stop = 4)

# output

((2, 3, 4), true)

Fields

  • K::AbstractMatrix: The matrix that mixes the strata of each batch.
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 TimeVarying kernel reads its columns as its ComposableRecurrences.Primary or ComposableRecurrences.Secondary indexing sets. With lags = 1:length(g) the weights sit on lags from 1, so that the convolution of the outputs of a Recurrence with kernel is  . It is the kernel with zeros on the lags before the first, so its transpose and its ComposableRecurrences.contributions count lags from 0.

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, or a number for the one input of a single series before t = 1, or PerStratum(x) of a length-S vector for one input of each stratum); 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

  • method: how the lag sum is computed, ComposableRecurrences.Direct (the default) or ComposableRecurrences.FFTMethod.

  • lags: for a kernel of delays, the number of lags from lag 0; for an array of weights, the range of lags they sit on, such as 1:length(g), in place of the default 0:(L - 1).

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

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, its step(form, θ, v, s), 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. A draw into pool (into = f) fills it instead, up to :     and   . The Hazard() of a draw takes its hazard from the value over the population, ; the demand of a Hazard() flow is the rate itself. Pools, draws and flows gives the overflow, the order of flows and the layout of strata and state, and Depletion in practice builds births and deaths, leaky protection, beds, allowances and a ward.

Arguments

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} <: ComposableRecurrences.AbstractParameter
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. 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

Fields

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

  • args::Tuple: The arguments.

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 is the default method, and 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 runs only when asked for with method = FFTMethod(). It is faster than the direct method from about 300 lags and 1000 outputs; 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} <: ComposableRecurrences.ExponentForm

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
CR.step(CR.Floor(), (; α = nothing, N = 100.0), 2.0, 80.0)

# 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.Split, ComposableRecurrences.Share, 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.Split, ComposableRecurrences.Share, 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 strata share the rows they read:

with read by ComposableRecurrences.param (Parameters shared across strata).

Arguments

  • p: a parameter with a row axis, such as PerStratum(v), TimeVarying(PerStratum(P)), a Derived of them, or a per-stratum kernel.

  • rows: the row of p each stratum reads, a vector of indices.

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} <: ComposableRecurrences.ExponentForm

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′ = CR.step(CR.Hazard(), (; α = nothing, N = 100.0), 2.0, 80.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} <: ComposableRecurrences.LagMap

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. Normalised(Increments(1 - Survival(hazard))) rescales the masses to sum to one over the lags, as they otherwise leave out the delays after  .

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 the starting state of a whole-step modifier, in forward!(m, Init(), s, history) and pullback!(grads, m, Init(), s, history).

It sets the state before the first step of a call that starts at time ,

where is the modifier's map, the output and the whole history, of length . forward! writes the state into s; without a method the state is zero. pullback! reads the cotangent of the state in grads.s, adds that of the history into grads.history and those of the modifier's parameters into grads.piece. A modifier with a ComposableRecurrences.step method starts its state with ComposableRecurrences.init and has no method for this role.

Arguments

  • s: the state, of ComposableRecurrences.nstate entries.

  • history: the history, a vector for one stratum or a matrix of strata by time.

  • grads: (; piece, s, history), for pullback!.

Each method takes these arguments untyped and returns nothing. Steps across strata gives the roles side by side.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Carried end
function CR.forward!(::Carried, ::CR.Init, s, history)
    s .= sum(history)
    return nothing
end
function CR.forward!(::Carried, ::CR.Step, v, s, t)
    v .+= s
    return nothing
end
function CR.pullback!(grads, ::Carried, ::CR.Step, v, s, t)
    grads.s .+= grads.v
    return nothing
end
function CR.pullback!(grads, ::Carried, ::CR.Init, s, history)
    grads.history === nothing || (grads.history .+= sum(grads.s))
    return nothing
end
r = Recurrence([1.0]; modifiers = (Carried(),))
r(1.0; history = [1.0, 2.0], stop = 3)

# output

3-element Vector{Float64}:
  5.0
  8.0
 11.0

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} <: ComposableRecurrences.LagMap

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 at most eps is replaced by eps, so a cohort whose weights are all zero keeps weights of zero. A total that is not finite is kept: a NaN total gives that cohort weights of NaN, and an infinite one gives zero for its finite entries and NaN for its infinite ones. 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

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 (:nstate, :stateless, :pullback, :step).

An operator, coupling, modifier or depletion form in one of its roles.

The mandatory forward component checks that the type runs in its role and keeps to the role's conventions: forward for Run(), a modifier's step on the whole vectors for Step() (its pure ComposableRecurrences.step at each stratum or group, or a whole-step modifier's forward!), a depletion form's draw at each entry, the starting state for Init(), a coupling's forward! for Pressure() and a modifier's trace for Trace(). Outputs are written into the leading arrays, forward! returns nothing and inputs are 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, 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 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 the pullback of a modifier's or a depletion form's Step(), or a coupling's Pressure(), against the Jacobian of the forward step from ForwardDiff: for a fixed cotangent of the outputs it compares the cotangents of the type's float parameters and the role's inputs ,

at rtol = 1e-8. It passes any other role and a type the rule does not take.

The optional step component checks a modifier or depletion form written as a pure ComposableRecurrences.step, at each stratum or group of its Step() arguments: each of its step, init, step_pullback and trace methods takes its arguments after the modifier untyped, as a typed method is not found, and so does each forward! of a whole-step modifier for Init() and Trace() after the role; the step's result type is inferred from its arguments; the step reads its float parameters from θ and not from the type's own fields (its result is unchanged when those fields change and θ is held); and a ComposableRecurrences.step_pullback gives the cotangents of the local forward-mode derivative at rtol = 1e-8, with no cotangent left out for a parameter the step depends on. It passes any other type and role.

Test objects are Arguments(; piece, role, args), with kwargs for Run() and pullback = false for an object the pullback component passes without a check. The arguments are those of the role on whole vectors: (v, s, t) for a modifier's Step(), (v, s, N) with a float population N for a depletion form's, (s, history) for Init(), (q, p, t) for Pressure() and (r, v, s, v′, s′, t), with r the step's column of ComposableRecurrences.ntrace rows, for Trace().

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:

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

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

  • pullback: the step's pullback matches its ForwardDiff Jacobian

  • step: a pure step has untyped methods, infers and matches its step_pullback

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} <: ComposableRecurrences.AbstractParameter

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, 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  ; its docstring gives the rules for its coupling. A TimeVarying kernel reads its columns as its ComposableRecurrences.Primary or ComposableRecurrences.Secondary indexing sets, and only a kernel takes Primary().

Called as r(gain = 1; history, state, add, start, stop, record, include_history), it covers the absolute times start:stop and returns stop - start + 1 outputs for a single series, or S rows of them:

  • gain: a scalar, a length-T vector, S × T or a parameter, read at absolute time t; one when left out.

  • history: the outputs before start, oldest first, length h, S × h, PerStratum(x) for one output per stratum, or S × B × h for batches; zeros when left out (History and state).

  • state: a ComposableRecurrences.State to resume from, in place of history; ComposableRecurrences.advance! runs the same steps in the state's own buffer.

  • add: nothing, or an input of the forms gain takes.

  • start, stop: the first and last times; start is 1, or state.t when resuming, and stop the common length of gain and add, required when neither has one.

  • record: Resume(), Pressure() or Trace(), alone or in a tuple, for a named tuple of y and those parts (What a call returns).

  • include_history: true for the history followed by the run.

Arguments

  • kernel: the kernel, lag 1 first, or a kernel of delays. Without one, Recurrence(; coupling, modifiers) carries each stratum's previous value forward, as the kernel [true] does: the modifiers and the add input then set how the values change.

Keyword Arguments

  • coupling: how the strata's kernel convolutions mix: I (the default) or λ * I, an S × S matrix, a TimeVarying S × S × T array, or a struct with forward! on ComposableRecurrences.Pressure.

  • modifiers: a modifier, or a tuple of modifiers applied in order after the core of each step, or a named tuple, as modifiers = (; pool, imports), whose names key their traces; a new modifier is a struct with a ComposableRecurrences.step, or with forward! on ComposableRecurrences.Step for a step on every stratum.

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

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

Examples

julia
using ComposableRecurrences
CR = 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 = CR.Resume())
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.

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:

where is the value entering the modifier at time , the value it passes on, the share of origin 's value realised in destination and the arrivals, kept as the state. Redistribute(K, ε) builds from a kernel and an origin intensity , a share of origin 's value moving to   and the rest staying:

The column sums are checked to within the square root of the machine epsilon.

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 is the type parameter L of Redistribute{L}: pass a literal, or call Redistribute{leak}(M) for a flag read from a variable.

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.Resume Type
julia
struct Resume

The marker that asks a Recurrence call for the ComposableRecurrences.State to resume from.

A call with record = Resume() that ends at time returns (; y, state), with

the last outputs, each modifier's state and the next time, as for ComposableRecurrences.State. A call with state continues from where it ended, as one call over both ranges would. It sits in a record tuple beside ComposableRecurrences.Pressure and ComposableRecurrences.Trace.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.5, 0.5])
R = fill(1.1, 6)
first_half = r(R; history = ones(2), stop = 3, record = CR.Resume())
rest = r(R; state = first_half.state)
vcat(first_half.y, rest) ≈ r(R; history = ones(2))

# output

true

Fields

source
ComposableRecurrences.Secondary Type
julia
struct Secondary

The default indexing of a TimeVarying coefficient: column t is read at time t.

For a kernel, the weight on lag of the output at time is

where is the kernel's weight on lag in column and is the absolute time of the output, counted from 1. A time-varying coupling or modifier parameter is likewise read as . This is the only indexing outside a kernel.

Examples

julia
using ComposableRecurrences
typeof(TimeVarying([0.8 0.7; 0.2 0.3], ComposableRecurrences.Secondary()))

# output

TimeVarying{ComposableRecurrences.Secondary, Matrix{Float64}}

Fields

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.

Keyword Arguments

  • bounded: whether a flow checks, when it is built, that a share given as a number or an array lies between 0 and 1; true by default. Share(; bounded = false) takes any share, such as a rate whose prior has no upper bound.

Examples

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

# output

(ComposableRecurrences.Share(), ComposableRecurrences.Share(bounded = false))

Fields

  • bounded::Bool: Whether a flow checks that its share lies between 0 and 1.
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(; 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.State Type
julia
struct State{H, M, T, W}

The state a Recurrence call with record = ComposableRecurrences.Resume() returns with its output, passed back as state to resume.

After a call that ended at absolute time it carries

where is the output at time (one entry per stratum), the buffer depth and the state of the -th of modifiers after the last step. The buffer depth is the number of kernel weights, or the furthest any part reads back if that is more. history holds the last outputs, states each modifier's state and t the time of the next step,  . widths holds each modifier's number of values per group, the strata ComposableRecurrences.select keeps together. owned says whether history reads a buffer that ComposableRecurrences.advance! may write in. A call with state continues exactly as one call over both ranges would (History and state). ComposableRecurrences.advance! steps a state without copying it, and vec(state) and State(like, x; t) convert it to and from one vector.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.5, 0.5])
(; state) = r(fill(1.1, 6); history = ones(2), stop = 3, record = CR.Resume())
state.t, round.(r(fill(1.1, 6); state); digits = 3)

# output

(4, [1.317, 1.407, 1.498])

Fields

  • history::Any: The last outputs, as many as the buffer depth, in the history's layout.

  • states::Any: Each modifier's state.

  • t::Any: The time of the next step.

  • widths::Any: Each modifier's values per group, the strata select keeps together.

  • owned::Bool: Whether history reads a buffer that advance! may write in.

source
ComposableRecurrences.Step Type
julia
struct Step

The role of one step of a whole-step modifier, in forward!(m, Step(), v, s, t) and pullback!(grads, m, Step(), v, s, t).

At absolute time the modifier maps the values and its state to new ones,

where holds one value per stratum, is the number of strata, is the state after the previous step and the state after this one. forward! overwrites v and s with and . pullback! overwrites the cotangents of and in grads.v and grads.s with those of and , and adds those of the modifier's parameters into grads.piece. A modifier with a ComposableRecurrences.step method has no method for this role.

Arguments

  • v: the values, one per stratum.

  • s: the state, of ComposableRecurrences.nstate entries.

  • t: the absolute time.

  • grads: (; piece, v, s), for pullback!.

Each method takes these arguments untyped and returns nothing. Steps across strata shows a modifier written with this role.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0, 3.0], [0.0, 0.0]
CR.forward!(CR.Redistribute([0.9 0.2; 0.1 0.8]), CR.Step(), v, s, 1)
round.(v; digits = 2), round.(s; digits = 2)

# output

([2.4, 2.6], [0.6, 0.2])

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. The share of a cohort that has left by each lag, its cumulative distribution, is 1 - Survival(hazard), and kernel_weights(TimeVarying(1 - Survival(hazard), Primary()), n) returns it as a table for n cohorts. 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, 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 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, whose derivatives one backend loses.

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

Fields

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

The role of a modifier's trace: the series 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

where is the modifier's map and its ComposableRecurrences.ntrace. A modifier with a ComposableRecurrences.step method defines with ComposableRecurrences.trace. A whole-step modifier defines it with forward!(m, Trace(), r, v, s, v′, s′, t), which writes into r, and reverses it with pullback!(grads, m, Trace(), v, s, t); without a method it records its state,  . A modifier declared ComposableRecurrences.isstateless records nothing. A ComposableRecurrences.Depletion with a draw records, each over the strata or groups, its pools after the step, the value it passes on and the overflow   , where is the demand and the queue (zero without one); without a draw it records the amount each flow moves, one row per flow and group. ComposableRecurrences.Redistribute records its arrivals, its state.

Arguments

  • r: the step's column of the trace, of ntrace(m, S) entries.

  • v, s: the values and state before the step.

  • v′, s′: the values and state after it.

  • t: the absolute time.

  • grads: (; piece, trace, v, s, v′, s′), for pullback!, which reads the cotangent of r in trace and adds into the others.

Traces shows a modifier with a trace of its own.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.5, 0.5]; modifiers = (CR.Depletion(100.0),))
run = r(1.2; history = ones(2), stop = 2, record = CR.Trace())
round.(only(run.trace); digits = 3)

# output

3×2 Matrix{Float64}:
 98.807  97.516
  1.193   1.291
  0.007   0.024

Fields

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

A modifier that maps each stratum's value through a function f:

where is stratum 's value when the modifier is reached, its value after and the parameter θ read at stratum and time . A tuple or NamedTuple of parameters is read entry by entry, and without θ the map is . Transform(+, b) adds, Transform(*, γ) scales and Transform(clamp, lo, hi) bounds; Order says where each goes. The reverse pass takes the map's closed-form derivative when it has one, else a local forward-mode derivative of f. Values captured by f are not in , so the AD backend differentiates the Recurrence holding such a map.

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

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
CR.step(CR.Truncate(), (; N = 100.0), 2.0, 1.5)

# output

(1.5, 0.0)

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.advance! Function
julia
advance!(
    r::Recurrence,
    state::ComposableRecurrences.State;
    ...
) -> NamedTuple
advance!(
    r::Recurrence,
    state::ComposableRecurrences.State,
    gain;
    add,
    stop,
    record
) -> NamedTuple

Run r from state to stop in the buffer state holds and return

the values of r(gain; state, add, stop, record = Resume()) with = state.t and = stop; the state passed is used up. A call that resumes from it again returns wrong values, not an error, so keep a copy, State(state, vec(state)), to resume from it twice.

Arguments

Keyword Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.5, 0.5])
R = fill(1.1, 6)
(; state) = r(R; history = ones(2), stop = 3, record = CR.Resume())
rest = CR.advance!(r, state, R; stop = 6)
rest.y ≈ r(R; history = ones(2))[4:6]

# output

true
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, and the default for a modifier with a ComposableRecurrences.step method, which gets each stratum's value and state as scalars. Any other shape is blockwise: the modifier's step gets the tuple of group g's values and the tuple of its state entries, and returns the new tuples. 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 (1, 1) for a modifier with a step method and nothing for any other. 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.contributions Function
julia
contributions(c::Convolution, x; kwargs...) -> Any

Return the terms of a Convolution before its sum over lags,

in the notation of Convolution, so that   . The output is L × T for a single series and S × L × T for S strata, lag 0 first, with a column per output time .

With indexing = Primary() a column holds the terms of one input time ,

with the length of x, and a term whose output time   is after stop is zero. stop = n + L - 1 gives every term of the inputs from start.

A kernel computed from coefficients needs them only up to stop, which is the length of x when left out; terms that land later are zero.

Arguments

Keyword Arguments

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
c = Convolution([0.5, 0.3, 0.2])
x = [1.0, 2.0, 4.0, 8.0]
by_output = CR.contributions(c, x)
by_input = CR.contributions(c, x; indexing = CR.Primary())
vec(sum(by_output; dims = 1)) ≈ c(x), by_output[:, 4], by_input[:, 4]

# output

(true, [4.0, 1.2, 0.4], [4.0, 0.0, 0.0])
source
julia
contributions(
    K::AbstractArray{<:Number};
    start,
    stop
) -> Any

Return the entries of a table held by input time,

It keeps the terms reported by stop, so an observed table is cut as contributions(c, x; indexing = Primary(), stop) cuts the expected one. It is that call for c = Convolution(TimeVarying(K, Primary())) and x all ones, and is differentiable in K.

Arguments

  • K: the table, L × n or S × L × n for S strata, lag 0 first.

Keyword Arguments

  • start: the first input time kept, 1 by default.

  • stop: the last time a term may be reported, n by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
K = [1.0 2.0 3.0 4.0; 5.0 6.0 7.0 8.0]
CR.contributions(K; stop = 3)

# output

2×3 Matrix{Float64}:
 1.0  2.0  3.0
 5.0  6.0  0.0
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 or range, and nothing for an integer, 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;
    width
) -> AbstractVector
julia
delay_masses(k, lags; width = 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, = width is the width of a lag in that unit and = lags. With the default width = 1 a lag is one unit of the delay. A delay on continuous time is censored with both windows one lag wide: its primary event is uniform over one lag and runs from the start of that lag, so four masses with width = 0.25 do not sum to the mass with width = 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 width on, and width without lags is an error. A width other than 1 suits a model whose time unit differs from the delay's unit, such as width = 7 for weekly steps and delays in days.

The method for a vector returns it as it is, whatever lags and width. 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 width as a keyword, defaulting to 1, and gives lag l the mass on  ; the operators always pass it, so a method that serves width = 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

  • width: 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;
    width
) -> 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 width units wide. A vector of masses is read as given, whatever its length and width, 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::Number,
    r::Number,
    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 gives it, and the profile over strata to scale I0 by, from a recurrence and its gain.

  • 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 with a coupling, or with a modifier whose step reads every stratum at once, define a type and add this method for its role: ComposableRecurrences.Step and ComposableRecurrences.Init for a modifier, ComposableRecurrences.Pressure for a coupling and ComposableRecurrences.Trace for a modifier's record. A modifier that acts on each stratum, or each group of strata, separately defines ComposableRecurrences.step instead, and has no method here.

Arguments

  • x: the coupling or whole-step modifier.

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

  • args: the role's arguments.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Shared{T}
    b::T
end
function CR.forward!(m::Shared, ::CR.Step, v, s, t)
    v .+= m.b * sum(v)
    return nothing
end
CR.islinear(::Shared) = true
r = Recurrence([0.5, 0.5]; modifiers = (Shared(1.0),))
r(1.0; history = ones(2), stop = 4)

# output

4-element Vector{Float64}:
 2.0
 3.0
 5.0
 8.0
source
ComposableRecurrences.gradient_routes Function

Time the gradient of the recurrence r by each route its pure steps can take, after checking that the routes agree.

The gradient is of a weighted sum of the recurrence's output,

in the recurrence's parameters, its input and its history , where holds fixed weights of the shape of . The routes are

Each route is timed through backend on host arrays. The first two are also timed as the rule's forward and reverse pass alone, on host arrays and on each device.

Before any time is taken, each step_pullback must pass the step component of ComposableRecurrences.PieceInterface at the first outputs and the starting state. The rule must pass ComposableRecurrences.test_adjoint where backend has a method, and the gradients of the routes must agree at rtol; a failed check throws.

The method is defined when ADTypes and DifferentiationInterface are loaded.

Arguments

  • backend: the AD backend, an ADTypes type.

  • r: the recurrence.

  • x: its input.

Keyword arguments

  • history: the history of the call.

  • devices: a NamedTuple of functions, each moving an operator or an array to a device, named as the rows are labelled.

  • seconds: the time spent on each row, whose fastest call is reported.

  • rtol: the relative tolerance of the gradient comparison, by default the square root of the machine epsilon of the number type of x: 1.5e-8 for Float64 and 3.5e-4 for Float32.

  • io: where the table is printed, or nothing.

Returns

A vector of rows (; route, array, via, time_ns, allocs, bytes), where via is the backend or "rule passes".

Examples

julia
using ComposableRecurrences, ADTypes, DifferentiationInterface, Mooncake
CR = ComposableRecurrences
struct Scale{A}
    a::A
end
CR.isstateless(::Scale) = true
CR.step(::Scale, θ, v, s) = (θ.a * v, nothing)
function CR.step_pullback(::Scale, θ, v, s, v̄′, s̄′)
    return θ.a * v̄′, nothing, (; a = v * v̄′)
end
r = Recurrence(fill(0.1, 10); modifiers = (Scale(0.9),))
CR.gradient_routes(
    AutoMooncake(; config = nothing), r, fill(1.1, 100); history = ones(10)
)
source
ComposableRecurrences.growth Function
julia
growth(
    r::Recurrence;
    ...
) -> NamedTuple{(:rate, :profile), <:Tuple{Any, Any}}
growth(
    r::Recurrence,
    gain;
    at
) -> NamedTuple{(:rate, :profile), <:Tuple{Any, Any}}

Return (; rate, profile): the rate per step and the profile over strata of the exponential history that the step of r at time at continues under gain,

in the notation of Recurrence. For a single series this is the Euler–Lotka equation   and profile is true. With the coupling I and a kernel that does not mix strata, rate has one value per stratum and profile is true. Strata that mix must all reach each other. The modifiers of r are not applied. An input with no rate gives NaN.

Arguments

  • r: the recurrence.

  • gain: as in a call of r; one when left out. PerStratum(R) gives one gain per stratum.

Keyword Arguments

  • at: the absolute time of the step; 1 by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.2, 0.5, 0.3]; coupling = [0.9 0.1; 0.3 0.7])
(; rate, profile) = CR.growth(r, PerStratum([1.8, 0.9]))
h = CR.exponential_history(10 .* profile, rate, 3)
y = r(PerStratum([1.8, 0.9]); history = h, stop = 2)
grows = y[:, 2] ≈ exp(rate) .* y[:, 1]
round(rate; digits = 4), round.(profile; digits = 3), grows

# output

(0.2507, [0.793, 0.207], true)
source
ComposableRecurrences.growth_gain Function
julia
growth_gain(r::Recurrence, rate; at) -> Any

Return the scale of the gain at which the recurrence r grows at rate, the inverse of ComposableRecurrences.growth:

which for a single series is . With the coupling I and a kernel that does not mix strata it has one value per stratum.

Arguments

  • r: the recurrence; its modifiers are not applied.

  • rate: the rate per step, or one per stratum when strata do not mix.

Keyword Arguments

  • at: the absolute time of the step; 1 by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.2, 0.5, 0.3])
R = CR.growth_gain(r, 0.1)
round(R; digits = 4), CR.growth(r, R).rate ≈ 0.1

# output

(1.2307, true)
source
ComposableRecurrences.init Function

Return the starting state of modifier m at one stratum, from its parameters θ and the stratum's history.

For a modifier with a ComposableRecurrences.step method it sets the state before the first step of the call,

where is the call's first time, its start, is the whole history of stratum , a vector, and the modifier's parameters read at the stratum and that time. A blockwise modifier gets the tuple of its group's histories and returns the tuple of its state entries, or one number for all of them. A modifier that keeps state has no default: a call is an ArgumentError without this method, and init(::M, θ, history) = 0 starts the state at zero. A modifier that keeps none declares ComposableRecurrences.isstateless. The method takes θ and history untyped. The reverse pass differentiates init in θ and the history with forward-mode passes.

Arguments

  • m: the modifier.

  • θ: its parameters at this stratum, or group, and the call's first time.

  • history: the stratum's history, or the tuple of a group's histories.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Carry end
CR.init(::Carry, θ, history) = sum(history)
CR.step(::Carry, θ, v, s) = (v + s, s / 2)
r = Recurrence([1.0]; modifiers = (Carry(),))
r(1.0; history = [1.0, 2.0], stop = 3)

# output

3-element Vector{Float64}:
 5.0
 6.5
 7.25
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.ismodifier Function
julia
ismodifier(m) -> Bool

Return whether m can go in the modifiers of a Recurrence.

It is true for the built-in modifiers, for a type with a ComposableRecurrences.step method and for a whole-step type with a ComposableRecurrences.forward! method for ComposableRecurrences.Step,

and false for anything else, a depletion form among them, which is a draw inside a ComposableRecurrences.Depletion. It follows from the type of m, so it costs nothing per call, and a caller can accept a user's own modifier without listing types.

Arguments

  • m: any object.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Halve end
CR.isstateless(::Halve) = true
CR.step(::Halve, θ, v, s) = (v / 2, s)
CR.ismodifier(Halve()), CR.ismodifier(CR.Depletion(9.0)), CR.ismodifier(0.5)

# output

(true, true, false)
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.LagMap, ComposableRecurrences.Derived, ComposableRecurrences.Survival}},
    n::Integer;
    stop
) -> 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. With stop, only the weights that land by stop are computed, the others are zero, and the arguments cover the times up to stop. 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.

Keyword Arguments

  • stop: the last time a weight may land; n + L - 1 when left out.

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, the rows of a trace that records its state, or none for a modifier declared 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) -> Any

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
function CR.pullback!(grads, m::Mix, ::CR.Step, v, s, t)
    ā = CR.cotangent(grads.piece, :a)
    for k in eachindex(v)
        CR.add_param!(ā, m.a, grads.v[k] * v[k], k, t)
        grads.v[k] *= CR.param(m.a, k, t)
    end
    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. A call with record = Pressure() returns the same pressure with its outputs. 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 (a number for one output of a single stratum); 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. 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 whole operator takes plain AD, unless the object is declared linear. A modifier written as a pure ComposableRecurrences.step needs no pullback!: the rule takes its local derivative.

Arguments

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

  • x: the operator, coupling or whole-step modifier.

  • role: the role.

  • args: the primal arguments forward! was given.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
C = [0.9 0.1; 0.2 0.8]
grads = (; piece = zeros(2, 2), q = [1.0, 0.0], p = zeros(2))
CR.pullback!(grads, C, CR.Pressure(), nothing, [1.0, 2.0], 1)
grads.p, grads.piece

# output

([0.9, 0.1], [1.0 2.0; 0.0 0.0])
source
ComposableRecurrences.select Function
julia
select(
    state::ComposableRecurrences.State,
    strata::AbstractVector{<:Integer};
    each
) -> ComposableRecurrences.State{_A, M} where {_A, M<:Tuple}

Return the ComposableRecurrences.State, or the parameter, whose stratum is stratum = strata[i] of the one given:

where are the last outputs the state holds and the state of its -th modifier.

Arguments

Keyword Arguments

  • each: the number of consecutive strata strata names as one block; 1 by default.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
pop = PerStratum([50.0, 80.0, 60.0])
r = Recurrence([0.5, 0.5]; modifiers = (CR.Depletion(pop),))
R = fill(1.5, 3, 6)
a = r(R; history = ones(3, 2), stop = 3, record = CR.Resume())
keep = [3, 1, 1]
rk = Recurrence([0.5, 0.5]; modifiers = (CR.Depletion(CR.select(pop, keep)),))
y = rk(R[keep, :]; state = CR.select(a.state, keep))
y ≈ r(R; state = a.state)[keep, :]

# output

true
source
ComposableRecurrences.step Function

Return the new value and state (v′, s′) of modifier m at one stratum and time, from its parameters θ, the value v and the state s.

A modifier with a step method is a pure step: at absolute time , for each stratum ,

where is the stratum's value when the modifier is reached, its state after the previous step and the modifier's parameters there. θ is a NamedTuple with one entry per field of m: a field that is a parameter is read at the stratum and time, a tuple or NamedTuple of parameters entry by entry, and any other field is passed as it is. Read parameters from θ, where the derivative is taken: inside the step a float parameter field of m holds no value, and arithmetic on it is an ArgumentError. Two kinds of modifier cannot hold that marker. A float field declared with a concrete type, such as a::Float64, reads as NaN, so a misread gives NaN output. A mutable modifier is passed as it is, and a misread there is not caught. The method takes θ, v and s untyped, allocates nothing and writes nothing, so the same method runs in the host loops, under ComposableRecurrences.Threaded and inside a device kernel.

v and s are scalars by default. With ComposableRecurrences.blocks (nv, ns) the step acts on one group of strata: v is the tuple of the group's values, s the tuple of its state entries, and θ is read at the group. A modifier declared ComposableRecurrences.isstateless gets s = nothing and returns (v′, nothing).

The reverse pass differentiates step with one forward-mode pass over (v, s, θ), or calls ComposableRecurrences.step_pullback when the modifier has one. Extending the package introduces the pure step.

Arguments

  • m: the modifier.

  • θ: its parameters at this stratum, or group, and time.

  • v: the value, or the tuple of a group's values.

  • s: the state, the tuple of a group's state entries, or nothing.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Smooth{A}
    a::A
end
CR.init(::Smooth, θ, history) = last(history)
function CR.step(::Smooth, θ, v, s)
    s′ = θ.a * s + (1 - θ.a) * v
    return s′, s′
end
r = Recurrence([0.5, 0.5]; modifiers = (Smooth(0.5),))
round.(r(1.2; history = ones(2), stop = 4); digits = 4)

# output

4-element Vector{Float64}:
 1.1
 1.18
 1.274
 1.3732
source
ComposableRecurrences.step_pullback Function

Return the cotangents (v̄, s̄, θ̄) of the inputs of ComposableRecurrences.step from the cotangents v̄′ and s̄′ of its outputs.

For the step   it computes

where and are the gradients of a scalar loss with respect to the step's outputs. θ̄ is a NamedTuple with an entry for each differentiated parameter, named as in θ and shaped as it is there; a parameter it leaves out gets no cotangent. The method is optional: without one the reverse pass takes the same cotangents from one forward-mode pass over (v, s, θ). Write one only where it is measurably faster, and check it with the step component of ComposableRecurrences.PieceInterface. v, s, v̄′ and s̄′ are shaped as in step: scalars, tuples for a blockwise modifier, and nothing for the state of a stateless one.

Arguments

  • m: the modifier.

  • θ, v, s: the arguments step was given.

  • v̄′, s̄′: the cotangents of the step's outputs.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Scale{A}
    a::A
end
CR.isstateless(::Scale) = true
CR.step(::Scale, θ, v, s) = (θ.a * v, nothing)
function CR.step_pullback(::Scale, θ, v, s, v̄′, s̄′)
    return θ.a * v̄′, nothing, (; a = v * v̄′)
end
CR.step_pullback(Scale(2.0), (; a = 2.0), 3.0, nothing, 1.0, nothing)

# output

(2.0, nothing, (a = 3.0,))
source
ComposableRecurrences.test_adjoint Function

Test the rule of the operator op on its positional arguments args with the AD backend's own rule tester.

The tester checks the pullback against finite differences of the forward map  : for random directions and cotangents ,

with from finite differences and from the pullback.

Methods come from package extensions: AutoMooncake with Mooncake loaded (Mooncake.TestUtils.test_rule) and AutoEnzyme with EnzymeTestUtils loaded (test_reverse, with the operator active and constant).

Arguments

  • backend: an AutoMooncake or AutoEnzyme from ADTypes.

  • op: the operator.

  • args: the positional arguments.

Examples

julia
using ComposableRecurrences
methods(ComposableRecurrences.test_adjoint)
source
ComposableRecurrences.trace Function

Return the values modifier m records at one stratum and step, as a tuple, from its parameters θ, the value and state before the step, v and s, and after it, v′ and s′.

For a modifier with a ComposableRecurrences.step method it is the map of the trace at stratum and absolute time ,

a tuple of numbers, with ComposableRecurrences.ntrace (m, S) declared as . A blockwise modifier gets the tuples of its group's values and state entries, and ntrace(m, S) is per group. A modifier that keeps state has no default trace: a call with record = Trace() is an ArgumentError without this method, and trace(::M, θ, v, s, v′, s′) = (s′,) records the state after the step. The method takes its arguments after the modifier untyped, allocates nothing and writes nothing. The reverse pass differentiates it with one forward-mode pass over (v, s, v′, s′, θ).

Arguments

  • m: the modifier.

  • θ: its parameters at this stratum, or group, and time.

  • v, s: the value and state before the step.

  • v′, s′: the value and state after it.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
struct Smooth{A}
    a::A
end
CR.init(::Smooth, θ, history) = last(history)
function CR.step(::Smooth, θ, v, s)
    s′ = θ.a * s + (1 - θ.a) * v
    return s′, s′
end
CR.ntrace(::Smooth, S) = 2S
CR.trace(::Smooth, θ, v, s, v′, s′) = (s′, v - s′)
r = Recurrence([0.5, 0.5]; modifiers = (Smooth(0.5),))
run = r(2.0; history = [1.0, 2.0], stop = 3, record = CR.Trace())
only(run.trace)

# output

2×3 Matrix{Float64}:
 2.5  3.5  4.75
 0.5  1.0  1.25
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