Public Documentation
Documentation for ComposableRecurrences's public interface.
ComposableRecurrences.ComposableRecurrences Module
ComposableRecurrencesFast, 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
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.
| concept | one way |
|---|---|
| feedback recursion | Recurrence(kernel; coupling, modifiers), lag 1 first |
| convolution | Convolution(kernel), lag 0 first |
| strata | PerStratum(x), Pairwise(x) |
| time variation | TimeVarying(x), TimeVarying(x, Primary()) |
| strata and time | TimeVarying(PerStratum(x)), TimeVarying(Pairwise(x)) |
| shared across strata | Gather(p, rows) |
| batches of strata | Batched(K), an S × h × B history |
| multiplicative input | r(gain; ...) |
| additive input | add =, before the modifiers |
| seed and resume | history =, state = |
| reorder, repeat or drop strata | select(state, strata) |
| modifiers | Depletion, Redistribute, Allocate, Transform |
| pools and flows | Depletion(N, Hazard(), Flow(from => to, d); pools) |
| filling a pool | Depletion(C, Truncate(; into = :O); pools) |
| options | structs such as Hazard(), Floor(), Primary() |
| extension | a 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
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.227Contents
Index
ComposableRecurrences.ComposableRecurrencesComposableRecurrences.EXECUTORComposableRecurrences.AbstractParameterComposableRecurrences.AllocateComposableRecurrences.BatchedComposableRecurrences.ConvolutionComposableRecurrences.DepletionComposableRecurrences.DerivedComposableRecurrences.DirectComposableRecurrences.FFTMethodComposableRecurrences.FloorComposableRecurrences.FlowComposableRecurrences.GatherComposableRecurrences.HazardComposableRecurrences.IncrementsComposableRecurrences.InitComposableRecurrences.NoAdjointComposableRecurrences.NormalisedComposableRecurrences.PairwiseComposableRecurrences.ParallelComposableRecurrences.PerStratumComposableRecurrences.PieceInterfaceComposableRecurrences.PressureComposableRecurrences.PrimaryComposableRecurrences.RecentComposableRecurrences.RecurrenceComposableRecurrences.RedistributeComposableRecurrences.ResumeComposableRecurrences.SecondaryComposableRecurrences.SerialComposableRecurrences.ShareComposableRecurrences.SplitComposableRecurrences.StateComposableRecurrences.StepComposableRecurrences.SurvivalComposableRecurrences.ThreadedComposableRecurrences.TimeVaryingComposableRecurrences.TraceComposableRecurrences.TransformComposableRecurrences.TruncateComposableRecurrences.add_cotangent!ComposableRecurrences.add_param!ComposableRecurrences.blocksComposableRecurrences.contributionsComposableRecurrences.convert_floatsComposableRecurrences.cotangentComposableRecurrences.delay_massesComposableRecurrences.exponential_historyComposableRecurrences.forward!ComposableRecurrences.gradient_routesComposableRecurrences.growthComposableRecurrences.growth_gainComposableRecurrences.initComposableRecurrences.islinearComposableRecurrences.ismodifierComposableRecurrences.isstatelessComposableRecurrences.kernel_weightsComposableRecurrences.nstateComposableRecurrences.ntraceComposableRecurrences.paramComposableRecurrences.param_rowsComposableRecurrences.pressureComposableRecurrences.pullback!ComposableRecurrences.selectComposableRecurrences.stepComposableRecurrences.step_pullbackComposableRecurrences.test_adjointComposableRecurrences.traceComposableRecurrences.trace_rowsComposableRecurrences.window_sums
Public API
ComposableRecurrences.AbstractParameter Type
abstract type AbstractParameterThe supertype of a value read at each stratum
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
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.6Fields
sourceComposableRecurrences.Allocate Type
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 imports = (fraction, pattern) a fraction 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, asInt[]or3:2. They are stored flat, in the fieldsstrata(each group's strata in turn) andoffsets(where each group starts).total: each group's total.
Keyword Arguments
imports:nothing(the default), or(fraction, pattern)withfractionthe share of each group's total placed by the import pattern andpatternanS × Scoupling, orTimeVaryingof anS × S × Tarray; a bareS × S × Tarray is read as the latter.spill:nothing(the default), or aComposableRecurrences.Redistributeapplied after the pattern reads the values; it needsimports.trace_imports:Val(false)(the default), orVal(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 namedpatternandimports, afterspilledwithspill(seeComposableRecurrences.trace_rows); it needsimports.
Examples
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.0Fields
strata::Vector{Int64}: The strata of every group, group by group.offsets::Vector{Int64}: Grouppisstrata[(offsets[p] + 1):offsets[p + 1]].total::Any: Each group's total, a parameter over groups.imports::Any: The import fraction, pattern and spill, ornothing.
ComposableRecurrences.Batched Type
struct Batched{M<:(AbstractMatrix)}A coupling that mixes each batch of strata by the same K, for
Stratum
where
Arguments
K: the matrix,weighting stratum in stratum of the same batch.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
K = [0.9 0.1; 0.2 0.8]
h = ones(2, 2, 3) .* reshape([1.0, 2.0, 3.0], 1, 1, 3) # S × h × B
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, 4, 3), true)Fields
K::AbstractMatrix: The matrix that mixes the strata of each batch.
ComposableRecurrences.Convolution Type
struct Convolution{K, M<:ComposableRecurrences.ConvolutionMethod} <: ComposableRecurrences.AbstractOperatorA 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 kernel[l + 1] the weight on lag 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 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
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 Recurrence with kernel 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, lengthTorS × T, read at absolute timet. The inputs beforestartcome fromxitself, and the inputs after its end are zero. A tuple ofSseries, one per stratum and all of lengthT, is read as the rows ofS × T, and the output is then a tuple ofSseries; the keywords are as forS × T.gain: a scalar, a length-Tvector shared by every stratum, orS × T, read at timet; one when left out.add:nothing, a scalar, lengthTorS × T, read at timet.history: the inputs beforet = 1, oldest first (any lengthm, orS × m, or a number for the one input of a single series beforet = 1); earlier inputs are zero. Not with aPrimary()kernel, which has no column for them.start: the first time;1by default.stop: the last time; by default the common length of the time-indexed inputs (x,gain,add). It may pass the end ofx, butgainandaddmust cover it. Only the outputs that a lag ofxreaches are summed, so an input that is zero from some time on can be passed up to that time, as inc(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) orComposableRecurrences.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 as1:length(g), in place of the default0:(L - 1).width: for a kernel of delays only, the width of a lag in the delays' own unit;1by default.
Examples
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.4Fields
kernel::Any: The kernel, lag 0 first.
ComposableRecurrences.Depletion Type
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
where step(form, θ, v, s), and N whatever the pool starts at.
With
where weights does not name. A draw into pool into = f) fills it instead, up to Hazard() of a draw takes its hazard from the value over the population, 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
N: the population a draw reads, or the capacity a draw fills up to, a parameter read at each step's group and time, a bare matrix being groups × time; left out for aDepletionwithout a draw, or whose truncated draws from its pools do not read it.pieces: the draws and flows, in the order they act;Hazard()alone when none are given. A draw is a depletion form, such asComposableRecurrences.Hazard,ComposableRecurrences.FloororComposableRecurrences.Truncate.
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 orPerStratum, ornothingforNat time 1 in the first pool the first draw from the pools names, and zero in the others. ADepletionwithout a draw takes its pools from the history instead, so each starts atnothing. A seed drawn from the pool ispools = (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 at1by default. A weight is one value orPerStratum, constant over time; an integer weight is fixed, a float one a parameter. One pool is drawn with weight1.into: the name of the pool the draw fills, in place ofweights, ornothing.overflow: where what the draw leaves goes:nothing(the default),:stratumor:queue; one draw at most has a queue.
Examples
Depletion from a pool that starts below the population by the seed:
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.287Fields
pools::NamedTuple: Each pool's starting value by name,nothingfor its default.pieces::Tuple: The draws and the runs of flows, in the order they act.
ComposableRecurrences.Derived Type
struct Derived{F, A<:Tuple} <: ComposableRecurrences.AbstractParameterDerived(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
where 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
with each argument read at that entry:
| argument | read at entry |
|---|---|
a number c | c |
a vector p of lag weights | p[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.Survival | its own weight |
i is the lag's index in the kernel: lag Convolution and Recurrence. So a TimeVarying(x) argument is read, in both uses, at the time the value acts: the step 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
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 asf(a_1, ..., a_n)on the arguments' values.args: the arguments, at least one.
Examples
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.276Fields
f::Any: The function, called on the arguments' values.args::Tuple: The arguments.
ComposableRecurrences.Direct Type
struct Direct <: ComposableRecurrences.ConvolutionMethodThe lag sum of a Convolution taken term by term,
at
Examples
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.0Fields
sourceComposableRecurrences.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
using ComposableRecurrences
using Base.ScopedValues: with
const CR = ComposableRecurrences
with(CR.EXECUTOR => CR.Threaded()) do
CR.EXECUTOR[]
end
# output
ComposableRecurrences.Threaded(500000, 0)ComposableRecurrences.FFTMethod Type
struct FFTMethod <: ComposableRecurrences.ConvolutionMethodThe lag sum of a Convolution through the discrete Fourier transform of the zero-padded series, by overlap-add,
The 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
summed over the blocks 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
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
trueFields
sourceComposableRecurrences.Floor Type
struct Floor{A, W, I, O} <: ComposableRecurrences.ExponentFormThe floored depletion form: the value is scaled by the share of the pool left, with a floor.
For one stratum at one step,
where
Arguments
α: the heterogeneity exponent, as forComposableRecurrences.Hazard.
Keyword Arguments
weights,into,overflow: make the form a draw in aComposableRecurrences.Depletion, whose keyword arguments define them.
Examples
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 α, ornothingfor one.weights::Any: As a draw, each pool's weight by name, ornothing.into::Any: As a draw, the pool it fills, ornothing.overflow::Any: As a draw, where what it leaves goes.
ComposableRecurrences.Flow Type
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 from and into to,
with the form setting
| form | demand | |
|---|---|---|
ComposableRecurrences.Hazard (the default) | a hazard rate | |
ComposableRecurrences.Share | a share | |
ComposableRecurrences.Truncate | a count | Truncate(κ) |
ComposableRecurrences.Split | a count, from several pools | each source's part of |
The hazard rates out of one pool compete, as in the Hazard depletion form, so together they move 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
then each count flow, in the order given, moves its Derived, which is only known at each step. Shares out of one pool that sum to more than 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 to, and a negative one moves nothing. Its form is Truncate() or Truncate(κ). The derivative through
Arguments
pools:from => to, each a pool's name or its position from 1, withto = 0to leave theDepletionandfrom = 0to enter it; forSplit(),fromis a tuple of two or more pools.demand: the rate, share or count, a parameter read at each step's group and time, withPerStratumholding one per group; a bare matrix is read as groups × time.
Keyword Arguments
form:Hazard(), the default,Share(),Truncate(),Truncate(κ)orSplit().name:nothing, the default, or aSymbol. When every flow of aDepletionwithout a draw is named, its trace returns the amount each moves by name (seeComposableRecurrences.trace_rows). Named flows in aDepletionhave different names.
Examples
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 forSplit().to::Any: The one pool it enters, by name or position, or0when 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(),TruncateorSplit().
ComposableRecurrences.Gather Type
struct Gather{P, R<:(AbstractVector{<:Integer})}Gather(p, rows)A parameter read, for stratum rows[k] of the parameter p, so strata share the rows they read:
with ComposableRecurrences.param (Parameters shared across strata).
Arguments
p: a parameter with a row axis, such asPerStratum(v),TimeVarying(PerStratum(P)), aDerivedof them, or a per-stratum kernel.rows: the row ofpeach stratum reads, a vector of indices.
Examples
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.0Fields
p::Any: The parameter read.rows::AbstractVector{<:Integer}: The row ofpeach stratum reads.
ComposableRecurrences.Hazard Type
struct Hazard{A, W, I, O} <: ComposableRecurrences.ExponentFormThe 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 α > 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, ortruefor an exponent of exactly one that is not a parameter, so the step skips the power and its derivative.falseis a fixed exponent of zero. In aDepletionany other integer takes the population's float type; pass a float to differentiate the exponent.
Keyword Arguments
weights,into,overflow: make the form a draw in aComposableRecurrences.Depletion, whose keyword arguments define them.
Examples
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 α, ornothingfor one.weights::Any: As a draw, each pool's weight by name, ornothing.into::Any: As a draw, the pool it fills, ornothing.overflow::Any: As a draw, where what it leaves goes.
ComposableRecurrences.Increments Type
struct Increments{X} <: ComposableRecurrences.LagMapThe increments of a computed kernel along its lags.
Inside a kernel TimeVarying(Increments(x), Primary()), the weight on lag
where TimeVarying(x, Primary()), and 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
x: the kernel to take the increments of, aDerived, aComposableRecurrences.Survivalor another computed kernel, or a kernel's weights,TimeVarying(K, Primary()), askernel_weightsreturns them.
Examples
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.224Fields
x::Any: The kernel to take the increments of.
ComposableRecurrences.Init Type
struct InitThe 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 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, ofComposableRecurrences.nstateentries.history: the history, a vector for one stratum or a matrix of strata by time.grads:(; piece, s, history), forpullback!.
Each method takes these arguments untyped and returns nothing. Steps across strata gives the roles side by side.
Examples
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.0Fields
sourceComposableRecurrences.NoAdjoint Type
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
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
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.323Fields
op::Any: The wrapped operator.
ComposableRecurrences.Normalised Type
struct Normalised{X} <: ComposableRecurrences.LagMapThe weights of a computed kernel over their total across its lags.
Inside a kernel TimeVarying(Normalised(x), Primary()), the weight on lag
where 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 TimeVarying(h) argument needs the times up to Convolution and Recurrence.
Arguments
x: the kernel to normalise, aDerived, aComposableRecurrences.Survivalor another computed kernel, or a kernel's weights,TimeVarying(K, Primary()), askernel_weightsreturns them.
Examples
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.337Fields
x::Any: The kernel to normalise.
ComposableRecurrences.Pairwise Type
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 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,
with 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 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 Recurrence.
Examples
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.0Fields
x::AbstractArray: The pairwise kernels, lag on the last axis.
ComposableRecurrences.Parallel Type
struct Parallel{B} <: ComposableRecurrences.ExecutorAn 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
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.0Fields
backend::Any: The backend the loop's kernel runs on.min_work::Int64: The smallest loopworkthat runs as a kernel.
ComposableRecurrences.PerStratum Type
struct PerStratum{A<:AbstractArray}A coefficient given per stratum: adds a leading strata axis to its slot.
A stratum is one of Recurrence kernel it is S × L, one row of lag weights per stratum, and stratum
with x[i, l] the weight on lag 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
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.0Fields
x::AbstractArray: The coefficients, strata on the first axis.
ComposableRecurrences.PieceInterface Type
PieceInterfaceAn 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 forward! on the basis vectors, forward! on a fixed input 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 ForwardDiff: for a fixed cotangent
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
using ComposableRecurrences, Interfaces, ForwardDiff
CR = ComposableRecurrences
Interfaces.test(CR.PieceInterface, CR.Transform; show = false)
# output
trueExtended help
Mandatory keys:
forward: forward or forward! runs in its roleadjoint: uses_adjoint finds a pullback! method for the rolelinear: a type declared islinear is its matrix at every time
Optional keys:
nstate: Init and Step keep the state at nstate(m, S) entriesstateless: a type declared isstateless keeps its state in Steppullback: the step's pullback matches itsForwardDiffJacobianstep: a pure step has untyped methods, infers and matches its step_pullback
ComposableRecurrences.Pressure Type
struct PressureThe 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 λ * I gives C gives C[i, j] at every TimeVarying coupling gives C.x[i, j, t]. To add a coupling, define a type and add this method; it may compute any ComposableRecurrences.pullback! method for a rule.
Examples
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.8Fields
sourceComposableRecurrences.Primary Type
struct PrimaryThe 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 kernel[l + 1]) in column Recurrence with kernel length
where kernel[l]) in column start > m. Kernel slots only: anywhere else it is an ArgumentError.
Examples
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.603Fields
sourceComposableRecurrences.Recent Type
struct Recent{W<:(AbstractVector), C} <: ComposableRecurrences.AbstractParameterA modifier parameter read from the recurrence's own recent outputs.
At stratum
where S × S coupling, Recent(n) with an integer n sums the last n outputs,
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 ComposableRecurrences.depth. Outside a recurrence it has no outputs to read, and ComposableRecurrences.param throws.
The reverse pass sends the cotangent
with
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 integernfor the sum of the lastnoutputs. The weights are real numbers and keep their element type, so integer,Float32and traced weights are held as given.
Keyword Arguments
coupling:nothingto read each stratum's own outputs, or anS × Smatrix of real numbers mixing them.
Examples
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.273Fields
w::AbstractVector: The weights, lag 1 first.coupling::Any: The coupling,nothingor anS × Smatrix.
ComposableRecurrences.Recurrence Type
struct Recurrence{K, C, M<:Tuple, N} <: ComposableRecurrences.AbstractOperatorA recurrence over strata whose kernel starts at lag 1, stepped from a window of its own past values.
At absolute time
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 everyand unless the kernel is PerStratumorTimeVarying;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 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-Tvector,S × Tor a parameter, read at absolute timet; one when left out.history: the outputs beforestart, oldest first, lengthh,S × h, orS × h × Bfor batches; zeros when left out (History and state).state: aComposableRecurrences.Stateto resume from, in place ofhistory.add:nothing, or an input of the formsgaintakes.start,stop: the first and last times;startis1, orstate.twhen resuming, andstopthe common length ofgainandadd, required when neither has one.record:Resume(),Pressure()orTrace(), alone or in a tuple, for a named tuple ofyand those parts (What a call returns).include_history:truefor 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, anS × Smatrix, aTimeVaryingS × S × Tarray, or a struct withforward!onComposableRecurrences.Pressure.modifiers: a modifier, or a tuple of modifiers applied in order after the core of each step, or a named tuple, asmodifiers = (; pool, imports), whose names key their traces; a new modifier is a struct with aComposableRecurrences.step, or withforward!onComposableRecurrences.Stepfor 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;1by default.
Examples
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.
ComposableRecurrences.Redistribute Type
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 Redistribute(K, ε) builds
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 originqrealised in destinationp.K: in place ofM, theS × Skernel matrix,K[p, q]the weight from originqtop.ε: withK, the origin intensity: one value, a vector over origins, an origins × time matrix,PerStratumorTimeVarying(PerStratum)of these, or any other parameter, read at each step.
Keyword Arguments
leak:false(the default), ortrueto allow columns summing to less than one. It is the type parameterLofRedistribute{L}: pass a literal, or callRedistribute{leak}(M)for a flag read from a variable.
Examples
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.131Fields
M::Any: The movement matrix,M[p, q]from originqto destinationp.
ComposableRecurrences.Resume Type
struct ResumeThe marker that asks a Recurrence call for the ComposableRecurrences.State to resume from.
A call with record = Resume() that ends at time (; 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
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
trueFields
sourceComposableRecurrences.Secondary Type
struct SecondaryThe default indexing of a TimeVarying coefficient: column t is read at time t.
For a kernel, the weight on lag
where
Examples
using ComposableRecurrences
typeof(TimeVarying([0.8 0.7; 0.2 0.3], ComposableRecurrences.Secondary()))
# output
TimeVarying{ComposableRecurrences.Secondary, Matrix{Float64}}Fields
sourceComposableRecurrences.Serial Type
struct Serial <: ComposableRecurrences.ExecutorAn executor that runs every index in order on the calling task:
Examples
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.0Fields
sourceComposableRecurrences.Share Type
struct ShareThe share flow form: a ComposableRecurrences.Flow with this form moves a share
Flow
with 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;trueby default.Share(; bounded = false)takes any share, such as a rate whose prior has no upper bound.
Examples
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.
ComposableRecurrences.Split Type
struct SplitThe split flow form: a ComposableRecurrences.Flow with this form draws one count
A split flow names its sources as a tuple, (i_1, …, i_n) => to, with
or, when Truncate() count is, and to gains what they lose. Split() is a form for flows only, not a depletion form.
Examples
Discharges
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.0Fields
sourceComposableRecurrences.State Type
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
where history holds the last 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. A call with state continues exactly as one call over both ranges would (History and state).
Examples
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 strataselectkeeps together.
ComposableRecurrences.Step Type
struct StepThe 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
where forward! overwrites v and s with pullback! overwrites the cotangents of grads.v and grads.s with those of 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, ofComposableRecurrences.nstateentries.t: the absolute time.grads:(; piece, v, s), forpullback!.
Each method takes these arguments untyped and returns nothing. Steps across strata shows a modifier written with this role.
Examples
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
sourceComposableRecurrences.Survival Type
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
where Derived kernel read as there, from (0 by default) is the first lag the hazard acts at and 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
This is the Recurrence Recurrence([1]) with gain
Arguments
hazard: the hazard, any argument of aDerivedkernel.
Keyword Arguments
from: the first lag the hazard acts at,0by default.
Examples
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.29Fields
hazard::Any: The hazard.from::Int64: The first lag the hazard acts at.
ComposableRecurrences.Threaded Type
struct Threaded <: ComposableRecurrences.ExecutorAn 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
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.0Fields
min_work::Int64: The smallest loopworkthat is split across threads.ntasks::Int64: The most chunks a loop is split into;0uses the number of threads.
ComposableRecurrences.TimeVarying Type
struct TimeVarying{I, A}A coefficient that changes over time: adds a trailing time axis to its slot.
Column Primary() kernel's weight on lag
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 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 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): columntweights the inputs reaching outputt. This is the only meaning outside a kernel.ComposableRecurrences.Primary: columncis the kernel of the input at timec, which spreads forward through it. In aRecurrencethe input is the output at timec, 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, aPerStratumof them, a vector of kernel columns, or a vector ofstart => valuechange points.indexing:Secondary()(default) orPrimary().
Examples
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.0Fields
x::Any: The coefficients, time on the last axis.
ComposableRecurrences.Trace Type
struct TraceThe role of a modifier's trace: the series a call with record = Trace() records for it at each step.
At absolute time
where ComposableRecurrences.ntrace. A modifier with a ComposableRecurrences.step method defines ComposableRecurrences.trace. A whole-step modifier defines it with forward!(m, Trace(), r, v, s, v′, s′, t), which writes r, and reverses it with pullback!(grads, m, Trace(), v, s, t); without a method it records its state, 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 ComposableRecurrences.Redistribute records its arrivals, its state.
Arguments
r: the step's column of the trace, ofntrace(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′), forpullback!, which reads the cotangent ofrintraceand adds into the others.
Traces shows a modifier with a trace of its own.
Examples
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.024Fields
sourceComposableRecurrences.Transform Type
struct Transform{F, P}A modifier that maps each stratum's value through a function f:
where θ read at stratum θ 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 Recurrence holding such a map.
Arguments
f: the map, called asf(v)orf(v, θ).θ: the parameters, ornothing.lo,hi: withclamp, the lower and upper bounds, each a parameter.
Examples
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.961Fields
f::Any: The map, called asf(v)orf(v, θ).θ::Any: The parameters, ornothing.
ComposableRecurrences.Truncate Type
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
Truncate(κ) replaces the minimum by a smooth one of softness
with Truncate() is that form with no softness to differentiate.
Arguments
κ: the softness, with ; omitted for the exact minimum.
Keyword Arguments
weights,into,overflow: make the form a draw in aComposableRecurrences.Depletion, whose keyword arguments define them.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
CR.step(CR.Truncate(), (; N = 100.0), 2.0, 1.5)
# output
(1.5, 0.0)Fields
κ::Any: The softness κ, ornothingfor the exact minimum.weights::Any: As a draw, each pool's weight by name, ornothing.into::Any: As a draw, the pool it fills, ornothing.overflow::Any: As a draw, where what it leaves goes.
ComposableRecurrences.add_cotangent! Function
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, aRef,(; x),(;)ornothing.v: the cotangent to add.idx: the index into an array mirror.
Examples
using ComposableRecurrences
x̄ = zeros(2)
ComposableRecurrences.add_cotangent!(x̄, 1.5, 2)
x̄
# output
2-element Vector{Float64}:
0.0
1.5ComposableRecurrences.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 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 ofx.x: the parameter.v: the cotangent of the value read.k: the stratum.t: the absolute time.
Examples
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.0ComposableRecurrences.blocks Function
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
(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 g, so a PerStratum parameter has 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
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)ComposableRecurrences.contributions Function
contributions(c::Convolution, x; kwargs...) -> AnyReturn the terms of a Convolution before its sum over lags,
in the notation of Convolution, so that 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 x, and a term whose output time 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
c: the convolution, or itsComposableRecurrences.NoAdjoint.x: the inputs, as in a call ofc.
Keyword Arguments
gain,history,start,stop: as in a call ofc.indexing: the time a column belongs to,ComposableRecurrences.Secondary()(the default) for the output's orComposableRecurrences.Primary()for the input's.
Examples
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])contributions(
K::AbstractArray{<:Number};
start,
stop
) -> AnyReturn 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 × norS × L × nforSstrata, lag 0 first.
Keyword Arguments
start: the first input time kept,1by default.stop: the last time a term may be reported,nby default.
Examples
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.0ComposableRecurrences.convert_floats Function
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 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 asFloat32.x: an operator, a modifier, a coefficient or an array.
Examples
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
Float32ComposableRecurrences.cotangent Function
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 this returns 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 ornothing.name: the field.
Examples
using ComposableRecurrences
ComposableRecurrences.cotangent((; K = zeros(2)), :K)
# output
2-element Vector{Float64}:
0.0
0.0ComposableRecurrences.delay_masses Function
delay_masses(
k::AbstractVector,
lags;
width
) -> AbstractVectordelay_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 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 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 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
AbstractVectorof lengthlags, lag 0 first;it takes
widthas a keyword, defaulting to 1, and gives laglthe mass on ; the operators always pass it, so a method that serveswidth = 1only 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 - 1into 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;1by default.
Examples
using ComposableRecurrences
k = [0.2, 0.5, 0.3]
ComposableRecurrences.delay_masses(k, 3) === k
# output
truedelay_masses(
ds::Tuple{Any, Vararg{Any}},
lags;
width
) -> AnyReturn 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
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])ComposableRecurrences.exponential_history Function
exponential_history(
I0::Number,
r::Number,
L::Integer
) -> AnyReturn a geometric history of L steps that grows by a factor I0, to seed a Recurrence.
For one series, and for stratum
oldest first, so
Arguments
I0: the value at the last step; a vector gives one per stratum.r: the rate per step; with a vectorI0, a scalar or one per stratum.ComposableRecurrences.growthgives it, and the profile over strata to scaleI0by, from a recurrence and its gain.L: the number of steps, at least 1, usually the kernel length.
Examples
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.395ComposableRecurrences.forward! Function
Run x in role on primal arguments args, writing the outputs in place.
For the role's inputs
with ComposableRecurrences.Step a modifier step ComposableRecurrences.Init an initial state from the history, ComposableRecurrences.Pressure a coupling ComposableRecurrences.Trace a modifier's record 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()orTrace().args: the role's arguments.
Examples
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.0ComposableRecurrences.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
step_pullback: the rule with eachComposableRecurrences.step_pullbackas written, when a modifier ofrhas one;local derivative: the rule with every pureComposableRecurrences.stepdifferentiated by one forward-mode pass, anystep_pullbackhidden;plain AD:backendon the whole ofComposableRecurrences.NoAdjoint(r), without the rule.
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, anADTypestype.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 ofx:1.5e-8forFloat64and3.5e-4forFloat32.io: where the table is printed, ornothing.
Returns
A vector of rows (; route, array, via, time_ns, allocs, bytes), where via is the backend or "rule passes".
Examples
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)
)ComposableRecurrences.growth Function
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 r at time at continues under gain,
in the notation of Recurrence. For a single series this is the Euler–Lotka equation 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 ofr; one when left out.PerStratum(R)gives one gain per stratum.
Keyword Arguments
at: the absolute time of the step;1by default.
Examples
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)ComposableRecurrences.growth_gain Function
growth_gain(r::Recurrence, rate; at) -> AnyReturn the scale r grows at rate, the inverse of ComposableRecurrences.growth:
which for a single series is 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;1by default.
Examples
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)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 start, 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
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.25ComposableRecurrences.islinear Function
islinear(x) -> BoolReturn 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
for every Recurrence call builds forward! on the pullback! and the outer AD differentiates the 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
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
trueComposableRecurrences.ismodifier Function
ismodifier(m) -> BoolReturn 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
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)ComposableRecurrences.isstateless Function
isstateless(m) -> BoolReturn 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 false; a modifier declares it for its type, and the optional stateless component of ComposableRecurrences.PieceInterface checks the declaration.
Arguments
m: the modifier.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
CR.isstateless(CR.Transform(clamp, 0.0, 1.0)), CR.isstateless(CR.Depletion(9.0))
# output
(true, false)ComposableRecurrences.kernel_weights Function
kernel_weights(
kernel::TimeVarying{ComposableRecurrences.Primary, <:Union{ComposableRecurrences.LagMap, ComposableRecurrences.Derived, ComposableRecurrences.Survival}},
n::Integer;
stop
) -> AnyReturn 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
Every entry is computed, so a TimeVarying(h) argument read at the time 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())withwaDerivedor aSurvival.n: the number of cohorts.
Keyword Arguments
stop: the last time a weight may land;n + L - 1when left out.
Examples
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.734ComposableRecurrences.nstate Function
nstate(m, S) -> AnyReturn the number of state entries modifier m keeps for S strata, from its ComposableRecurrences.blocks.
The recurrence allocates each modifier's state
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, blocks nothing, an ComposableRecurrences.Allocate with imports keeps its import pattern as well.
Arguments
m: the modifier.S: the number of strata.
Examples
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)ComposableRecurrences.ntrace Function
ntrace(m, S) -> AnyReturn the number of rows of a modifier's trace for S strata, one column per step.
For a modifier with
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
using ComposableRecurrences
CR = ComposableRecurrences
CR.ntrace(CR.Transform(clamp, 0.0, 1.0), 3), CR.ntrace(CR.Depletion(100.0), 3)
# output
(0, 9)ComposableRecurrences.param Function
Return the value x at stratum k and absolute time t.
A parameter is one value PerStratum giving TimeVarying giving TimeVarying(PerStratum(x)) giving 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
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)ComposableRecurrences.param_rows Function
param_rows(m, S) -> AnyReturn 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 DimensionMismatch that names a field that fails. Pointwise and blockwise modifiers ignore it: their rows follow from ComposableRecurrences.blocks.
Arguments
m: the modifier, withblocks(m) === nothing.S: the number of strata in the call.
Examples
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 3ComposableRecurrences.pressure Function
pressure(r::Recurrence, y; kwargs...) -> AnyCompute 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. ComposableRecurrences.Pressure role writes, computed as the step computes it, for any kernel and coupling a Recurrence takes. history, as in the call. For one series with kernel
For the outputs of r(gain; history) without modifiers or an add input, 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 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, orNoAdjoint(r).y: its outputs at timesstarttostart + T - 1, lengthTfor a single series orS × T.
Keyword Arguments
history: the outputs beforestart, 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;1by default.
Examples
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
trueComposableRecurrences.pullback! Function
Accumulate the reverse pass of ComposableRecurrences.forward! for x in role.
For forward! computing outputs
grads is a NamedTuple: grads.piece holds 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, ...), withpiecethe mirror ofx's parameters.x: the operator, coupling or whole-step modifier.role: the role.args: the primal argumentsforward!was given.
Examples
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])ComposableRecurrences.select Function
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 strata[i] of the one given:
where
Arguments
state: aComposableRecurrences.Statewith strata, or a parameter with a row per stratum, returned as aComposableRecurrences.Gather.strata: the stratum each selected stratum is read from.
Keyword Arguments
each: the number of consecutive stratastratanames as one block;1by default.
Examples
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
trueComposableRecurrences.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
where θ 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 θ, not from m, as the derivative is taken in θ. 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 s the tuple of its θ 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, ornothing.
Examples
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.3732ComposableRecurrences.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
where θ̄ 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 argumentsstepwas given.v̄′,s̄′: the cotangents of the step's outputs.
Examples
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,))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
with
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: anAutoMooncakeorAutoEnzymefrom ADTypes.op: the operator.args: the positional arguments.
Examples
using ComposableRecurrences
methods(ComposableRecurrences.test_adjoint)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
a tuple of ComposableRecurrences.ntrace (m, S) declared as ntrace(m, S) is 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
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.25ComposableRecurrences.trace_rows Function
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 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
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)ComposableRecurrences.window_sums Function
window_sums(
x::AbstractVecOrMat,
ends::AbstractVector{<:Integer};
dims
) -> AnySum 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, 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 alongdims.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 ofxthat is time; the last by default.
Examples
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.0window_sums(
x::AbstractVecOrMat,
starts::AbstractVector{<:Integer},
stops::AbstractVector{<:Integer};
dims
) -> AnySum 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 alongdims.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 ofxthat is time; the last by default.
Examples
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