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)) |
| multiplicative input | r(gain; ...) |
| additive input | add =, before the modifiers |
| seed and resume | history =, state = |
| 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 forward! method for a role |
To extend the package, define a type and add a ComposableRecurrences.forward! method, and optionally a ComposableRecurrences.pullback! method, for its role (ComposableRecurrences.Step, ComposableRecurrences.Init, ComposableRecurrences.Pressure or ComposableRecurrences.Trace).
Examples
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.AllocateComposableRecurrences.ConvolutionComposableRecurrences.DepletionComposableRecurrences.DerivedComposableRecurrences.DeviceComposableRecurrences.DirectComposableRecurrences.FFTMethodComposableRecurrences.FloorComposableRecurrences.FlowComposableRecurrences.GatherComposableRecurrences.HazardComposableRecurrences.IncrementsComposableRecurrences.InitComposableRecurrences.LocalComposableRecurrences.NoAdjointComposableRecurrences.NormalisedComposableRecurrences.PairwiseComposableRecurrences.ParallelComposableRecurrences.PerStratumComposableRecurrences.PieceInterfaceComposableRecurrences.PressureComposableRecurrences.PrimaryComposableRecurrences.RecentComposableRecurrences.RecurrenceComposableRecurrences.RedistributeComposableRecurrences.SerialComposableRecurrences.ShareComposableRecurrences.SplitComposableRecurrences.StepComposableRecurrences.SurvivalComposableRecurrences.ThreadedComposableRecurrences.TimeVaryingComposableRecurrences.TraceComposableRecurrences.TransformComposableRecurrences.TruncateComposableRecurrences.add_cotangent!ComposableRecurrences.add_param!ComposableRecurrences.blocksComposableRecurrences.convert_floatsComposableRecurrences.cotangentComposableRecurrences.delay_massesComposableRecurrences.exponential_historyComposableRecurrences.forward!ComposableRecurrences.growth_rateComposableRecurrences.islinearComposableRecurrences.isstatelessComposableRecurrences.kernel_weightsComposableRecurrences.nstateComposableRecurrences.ntraceComposableRecurrences.paramComposableRecurrences.param_rowsComposableRecurrences.pressureComposableRecurrences.pullback!ComposableRecurrences.trace_rowsComposableRecurrences.window_sums
Public API
ComposableRecurrences.Allocate Type
struct Allocate{T, I}A modifier that rescales each group of strata to a total fixed outside the model: the strata of a group keep their shares of the group's value and the group takes its total. With imports, a fraction of each total is shared instead by an import pattern that reads the values before an optional within-group spill.
At absolute time
with imports = (fraction, pattern) and spill, the shares come from the spilled values
where ComposableRecurrences.Redistribute (the identity without spill) and spill only when the pattern must read the values from before the spill; otherwise place the Redistribute before Allocate in the modifier tuple. It is meant for non-negative values: a group sum at or below zero is floored to ArgumentError. A group may be empty, given as Int[] or a range such as 3:2 (an untyped [] holds Any and is rejected): it holds no strata, so its total and import fraction are not used and their gradients are zero. The groups are stored flat, in the fields strata (each group's strata in turn) and offsets (where each group starts), so the rule sees only integer arrays and the parameters. total and fraction are parameters over groups, not strata: PerStratum holds one value per group, and a bare matrix is read as groups × time. It reads every stratum of a group, so it is not pointwise, and its groups differ in size and are set by the value, so it is not blockwise (ComposableRecurrences.blocks is nothing). It has no state without imports; with them the state holds (Allocate(groups, total), Transform(+, b)) adds b after the split. Its reverse pass, with
and on the floor (imports,
where
Arguments
groups: a vector of index ranges or vectors, one per group, partitioning the strata.total: each group's total.
Keyword Arguments
imports:nothing(the default), or(fraction, pattern)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 namedspilled,patternandimports(seeComposableRecurrences.trace_rows); it needsimports. Without it the trace is the state after each step, which costs less to record. It is aVal, not aBool, so the choice is part of the type even when the model is built inside a gradient.
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.0Allocate with imports adds an import pattern and a spill.
Fields
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.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 vector kernel is shared by every stratum, a PerStratum kernel is S × L, and a TimeVarying kernel is L × T or TimeVarying(PerStratum(G)) with G S × L × T, all lag 0 first. A TimeVarying kernel's indexing sets which time its column belongs to: with ComposableRecurrences.Secondary (the default) column ComposableRecurrences.Primary column
To weight lags from 1, as a renewal's infection pressure does, prepend a zero: Convolution(vcat(0, g)) recomputes Recurrence with kernel c', which transpose sets out.
Called as c(x; gain = 1, add, history = nothing, start = 1, stop), the call covers the absolute times start:stop:
x: the inputs, 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); 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.Auto(the default),ComposableRecurrences.DirectorComposableRecurrences.FFTMethod.lags: for a kernel of delays only, the number of lags from lag 0.step: for a kernel of delays only, the width of a lag in the delays' own unit;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 forward!(form, Step(), v, s, N), and N whatever the pool starts at.
With
where weights does not name. When weights names alone. A draw into pool into = f) fills it instead, up to Truncate() or Truncate(κ), and its capacity overflow = :stratum to the group's second value, overflow = :queue to a queue held after the pools in the state, whose content joins the draw's value at the next step. Each draw takes the value the parts before it pass on.
The flows act on the pools where they stand among the parts, as when patients leave before the step's admissions or an allowance is granted at the start of a period. Hazard and share flows given one after another act together, then each count flow in the order given; a count flow from 0 brings its demand in from outside.
A draw is a form, Hazard(), Floor(), Truncate(), Truncate(κ) or a new type with a forward!(form, Step(), v, s, N) method, which draws from the first pool alone. A built-in form given weights, into or overflow, such as Hazard(; weights = (S = 1, V = σ)) or Truncate(; into = :O), is a draw with them. The draw's Hazard() takes its hazard from the value over the population, Hazard() flow's demand is the rate itself. A form without a pullback! is differentiated by a local step when its float parameters are scalars, and by plain AD otherwise.
One pool, with draws that leave nothing over, is a pointwise step, blocks (1, 1), whose state is the pool. Any other is blockwise: each group has one value, or two with overflow = :stratum, value Depletion covers every stratum, so a stratum without a cap takes an infinite N. With overflow = :stratum group ComposableRecurrences.Redistribute after the Depletion, with K sending each to the shared one, moves their values into it.
Without a draw the pools are the step's values: the values hold blocks is (n, n)), so value Recurrence with kernel [1.0] the core carries the previous step's pools forward, and the Depletion applies the step's flows,
Depletion in practice builds births and deaths, leaky protection, beds, allowances and a ward from these parts. A Depletion holds the fields pools (each pool's starting value, nothing for its default) and pieces: the draws, each with N and its pools named by position, and the flows given one after another as one tuple. Each part is a modifier on the pools it shares with the others: its group step forward!(piece, Step(), v, s, t, g) takes the group's values and its pools, then the queue, as tuples of one-entry views, with pullback! and ComposableRecurrences.Trace alike, and the Depletion runs them in order. A draw's trace is the value it passes on and what it leaves, and a run of flows' the amount each moves.
Arguments
N: the population a draw reads, or the capacity a draw fills up to, a parameter read at each step's group and time, a bare matrix being groups × time; left out for 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.
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}Derived(f, args...)A value computed from at least one argument args by a function f: a modifier parameter, or the weights of a cohort kernel.
As a modifier parameter, at stratum
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, which needs the dual-number extension loaded. Values captured inside f (a closure, or a callable struct with float fields) are not arguments: an operator with such a map is differentiated by the AD backend instead, so they keep their gradients.
Arithmetic with a Derived on either side builds another Derived, so κ * x, x + c, x - c, x / N, x ^ p and -x all work when x is a Derived, with a number, a vector, PerStratum or TimeVarying on the other side. +, -, * and / also work with a ComposableRecurrences.Survival on either side. Wrap a plain parameter as Derived(identity, x) to start such an expression.
Arguments
f: the function, called 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.276A delay pmf whose mass is scaled down for cohorts from time 3 on:
using ComposableRecurrences
CR = ComposableRecurrences
p = [0.5, 0.3, 0.2]
scale = TimeVarying([1.0, 1.0, 0.5, 0.5], CR.Primary())
K = TimeVarying(CR.Derived(*, p, scale), CR.Primary())
round.(Convolution(K)(ones(4)); digits = 3)
# output
4-element Vector{Float64}:
0.5
0.8
0.75
0.6Fields
f::Any: The function, called on the arguments' values.args::Tuple: The arguments.
ComposableRecurrences.Device Type
Device(backend)Another name for the type Parallel.
Arguments
backend: aKernelAbstractionsbackend, such asCUDABackend().min_work: the smallest loopworkthat runs as a kernel, as forParallel;0by default.
Examples
using ComposableRecurrences, KernelAbstractions
const CR = ComposableRecurrences
CR.Device(KernelAbstractions.CPU()) isa CR.Parallel
# output
trueComposableRecurrences.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 ComposableRecurrences.Auto takes it; time both on the sizes of a model before choosing it. The reverse pass uses the same transforms.
It runs once the weak dependency of the FFT extension is loaded; without it, a call with this method is refused. It runs for a fixed kernel (a vector or PerStratum) on Float32 or Float64 arrays; a TimeVarying kernel, any other number type (dual numbers, say) and other arrays (device or traced) take ComposableRecurrences.Direct. It does not use the set ComposableRecurrences.EXECUTOR.
The transform's error in each sum is about the machine epsilon times the size of the inputs and kernel in its block, not times the sum itself. So each sum is checked against an estimate
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}The floored depletion form: the value is scaled by the share of the pool left, with a floor.
For one stratum at one step,
where
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
v, s = [2.0], [80.0]
CR.forward!(CR.Floor(), CR.Step(), v, s, 100.0)
v, s
# output
([1.6], [78.4])Fields
α::Any: The heterogeneity exponent α, 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.Share, ComposableRecurrences.Split, ComposableRecurrences.Truncate{<:Any, Nothing, Nothing, ComposableRecurrences._Drop}}, E, P, G, N}A flow from pool from into pool to of a ComposableRecurrences.Depletion, out of it with to = 0 or into it with from = 0, that moves its demand by a form.
Each step it moves an amount 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.Share, ComposableRecurrences.Split, 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 a value given per group is read by each stratum of its group:
with ComposableRecurrences.param. Strata that share a row add their cotangents into it. p is a parameter with a row axis, such as PerStratum(v), TimeVarying(PerStratum(P)) or a Derived of them; rows past the end of a Derived are found when read. A Gather is a modifier parameter, an argument of a Derived, a Recurrence's gain or add, or a Depletion's population.
Examples
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}The hazard depletion form: the value is drawn from the pool as a hazard, so the pool never goes negative.
For one stratum at one step,
where α > 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 = [2.0], [80.0]
CR.forward!(CR.Hazard(), CR.Step(), v, s, 100.0)
round.(v; digits = 3), round.(s; digits = 3)
# output
([1.584], [78.416])Fields
α::Any: The heterogeneity exponent α, 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}The 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.
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 a modifier's initial state: forward!(m, Init(), s, history) writes the state s (one entry per stratum, or one per pool for a ComposableRecurrences.Depletion with several, allocated by the operator at its buffer eltype) from the full history, and returns nothing.
It sets the state before the first step of the call at
where
Examples
using ComposableRecurrences
CR = ComposableRecurrences
s = zeros(2)
CR.forward!(CR.Depletion(PerStratum([100.0, 50.0])), CR.Init(), s, ones(2, 3))
s
# output
2-element Vector{Float64}:
100.0
50.0Fields
sourceComposableRecurrences.Local Type
struct LocalThe role of a map's local derivative at one entry: the partial derivatives of a Derived map or a ComposableRecurrences.Transform map at its arguments, given its value there.
For a map pullback!(grads, f, Local(), y, x...) returns the partial derivatives
one per argument and shaped as it is: a Transform map f(v, θ) with a tuple or NamedTuple θ returns (∂f/∂v, ∂f/∂θ), the second shaped as θ. y is the map's value there, from the forward pass. grads holds no cotangents for this role. The operators look for the method with Float64 arguments, so it should accept any Real arguments. Without one the partials come from a local forward-mode derivative, which needs ForwardDiff loaded. The package's rules for min and max give the first argument the cotangent on a tie, so a tie can differ from ForwardDiff's convention, which also varies between its versions.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
# A logistic hazard of the sum of its arguments, whose derivative reads its
# value.
struct LogisticSum end
(::LogisticSum)(a, b) = inv(1 + exp(-(a + b)))
function CR.pullback!(grads, ::LogisticSum, ::CR.Local, y, a, b)
d = y * (1 - y)
return d, d
end
h = CR.Derived(LogisticSum(), [-2.0, -1.0], 0.5)
cdf = TimeVarying(1 - CR.Survival(h), CR.Primary())
round.(CR.kernel_weights(cdf, 1); digits = 3)
# output
2×1 Matrix{Float64}:
0.182
0.491Fields
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}The 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 not finite or is at most eps is replaced by eps, so a cohort whose weights are all zero keeps weights of zero. Every lag of each cohort enters its total, so for 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.0using ComposableRecurrences
using SparseArrays: sparse
community = [0.9 0.1; 0.1 0.9]
funeral = sparse([0.0 0.4; 0.4 0.0]) # funerals in the other place
routes = Pairwise(community => [0.5, 0.3, 0.2], funeral => [0.0, 0.0, 0.0, 1.0])
y = Recurrence(routes)(fill(1.2, 2, 6); history = ones(2, 4))
round.(y; digits = 3)
# output
2×6 Matrix{Float64}:
1.68 2.088 2.578 3.181 4.144 5.253
1.68 2.088 2.578 3.181 4.144 5.253Fields
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 (:pointwise, :blocks, :nstate, :stateless, :pullback).
An operator, coupling, modifier or depletion form with forward or forward! for a role.
The mandatory forward component checks that forward (for Run()) or forward! (for the other roles) runs and keeps to its role's conventions (outputs written into the leading arrays and nothing returned, inputs unchanged). The mandatory adjoint component checks that a pullback! method for the type and role is found by ComposableRecurrences.uses_adjoint: a method with a typed grads or typed arguments after the role is not, apart from a blockwise group step's with v::Tuple, s::Tuple, and needs a uses_adjoint method, and one with the wrong number of arguments fails too. The mandatory linear component checks a type declared linear (ComposableRecurrences.islinear): for a coupling's Pressure(), or a whole-step modifier's Step(), built as the matrix 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 pointwise component checks that a pointwise modifier's step on the whole vectors equals its step on a one-entry view of each stratum,
where Init() it checks that a pointwise modifier writes each blocks component checks the same for a blockwise modifier (ComposableRecurrences.blocks), group by group, and passes any other modifier. The optional nstate component checks the state length against ComposableRecurrences.nstate. The optional stateless component checks that a modifier declared ComposableRecurrences.isstateless leaves its state as it was in Step(), and passes any other modifier and role. The optional pullback component checks a pullback! for a modifier's or a depletion form's Step(), or a coupling's Pressure(), against the Jacobian forward! from ForwardDiff: for a fixed cotangent rtol = 1e-8. It needs using ForwardDiff, and passes with a note without it; it passes any other role and a type without a pullback!.
Test objects are Arguments(; piece, role, args), with kwargs for Run() and pullback = false for an object the pullback component passes without a check.
Examples
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:
pointwise: a Step and an Init work stratum by stratumblocks: a vector Step matches the group Step on each groupnstate: Init and Step keep the state at nstate(m, S) entriesstateless: a type declared isstateless keeps its state in Steppullback: pullback! matches theForwardDiffJacobian of forward!
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}A 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, B, 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 kernel[l] weights L vector shared by every stratum, a PerStratum S × L matrix, or a TimeVarying L × T or TimeVarying(PerStratum(G)) with G S × L × T. A TimeVarying kernel with ComposableRecurrences.Primary indexing reads the column of each output's own time, Pairwise S × S × L kernel (or TimeVarying(Pairwise(A))) weights every pair of strata and already mixes them, so its coupling is I. A Pairwise(K₁ => k₁, K₂ => k₂) kernel sums routes, each a kernel with its own coupling, so its coupling is I too; the keyword constructor folds routes that have a cheaper equivalent form. The coupling is I (or a scaled λ * I), any S × S matrix (dense, sparse, Diagonal), a TimeVarying S × S × T array, or any struct with forward! on ComposableRecurrences.Pressure. A bare S × S × T array is read as TimeVarying: its third axis is time, not lags. Modifiers are structs with forward! on ComposableRecurrences.Step and, for an initial state, ComposableRecurrences.Init.
Called as r(gain = 1; history, state, add, start, stop, record), the call covers the absolute times start:stop:
gain: a scalar, a length-Tvector shared by every stratum, orS × T, read at absolute timet; one when left out. It may instead be a parameter, such asPerStratum,TimeVaryingor aDerivedof them, read at each stratum and absolute time. A parameter has no length, so givestopunlessaddsets it.history: the outputs at timesstart - htostart - 1, oldest first, lengthhfor a single series orS × h; zeros when left out. The recursion reads the lastoutputs, with at least Land at least theComposableRecurrences.depthof each part, and a shorter history is zero-padded. A modifier'sInitsees all of it.state: aComposableRecurrences.Stateto resume from, in place ofhistory;record = (:state,)returns the next one.add:nothing, a scalar, lengthTorS × T, read at timet, or a parameter, as forgain.start: the first time;1, orstate.twhen resuming. Withstart = h + 1the seed sits at times1:h, and the time-indexed inputs cover it.stop: the last time; by default the common length of the time-indexed inputs (gain,add), required without one.record: a tuple of what to return beside the outputy, which makes the call return a named tuple with fields in the ordery,state,trace::state, theComposableRecurrences.Stateafter the last step;:trace, withtrace.modifiersholding each modifier's series per step, aComposableRecurrences.ntracebyTmatrix of itsComposableRecurrences.Tracerecords, andtrace.pressurethe pressureeach step drew against, laid out as y, asComposableRecurrences.pressurereturns it; both differentiable as the output is. Named modifiers givetrace.modifiersas a named tuple keyed by their names, and a tuple of modifiers gives a tuple;:pressure, or a modifier's name, for that part of the trace alone, read as above, astrace.pressureortrace.modifiers.name;:force, fortrace.force, the value of each step before the modifiers, laid out asyand differentiable as it is. It is built only when named, so:tracealone leaves it empty; record(:trace, :force)for both. The parts not named are not built: they come back empty, so the call returns the type a whole trace has, and add no cotangent.
record = ()returns(; y), and withoutrecordthe call returnsy. Pass the tuple as a literal, or in aVal, asrecord = Val((:trace,)), where it reaches the call as a variable or the call is compiled from its argument types alone; the return type then infers from the argument types.include_history: whentrue,yis the history followed by the run, and each trace has zero columns over the history, so the output and the trace share their times;falseby default. The state is unchanged. It needshistory, notstate.
Every time-indexed array, kernels, couplings and modifier parameters included, must cover stop. Only a kernel takes Primary() indexing; the constructor rejects it in the coupling or a modifier. The output is length stop - start + 1 for a single series or S rows of it; the history sets which, and the number of strata. The output number type follows the inputs and fields; see Output number type. The constructor checks once whether the local step can rebuild every part it differentiates and stores the result in the field rebuilds; see Rules and plain AD.
Arguments
kernel: the kernel, lag 1 first, or a kernel of delays.
Keyword Arguments
coupling: how the strata's kernel convolutions mix;Iby default.modifiers: a tuple of modifiers applied after the core of each step, or a named tuple, asmodifiers = (; pool, imports), whose names key their traces andrecordreads.lags: for a kernel of delays only, the number of lags from lag 0.step: for a kernel of delays only, the width of a lag in the delays' own unit;1by default.
Examples
using ComposableRecurrences
g = [0.6, 0.3, 0.1] # weights on lags 1, 2, 3
K = [0.9 0.1; 0.2 0.8]
R = fill(1.1, 2, 10)
r = Recurrence(g; coupling = K)
y = r(R; history = ones(2, 3))
# The seed followed by the run, with the seed at times 1 to 3: the seed's
# 3 columns, then the run's 10.
h = ones(2, 3)
whole = r(hcat(h, R); history = h, start = 4, include_history = true)
# Resume from the returned state over the same inputs.
fit = r(R; history = ones(2, 3), stop = 5, record = (:state,))
size(whole), y ≈ hcat(fit.y, r(R; state = fit.state))
# output
((2, 13), true)Fields
kernel::Any: The kernel, lag 1 first.coupling::Any: How the strata's kernel convolutions mix.modifiers::Tuple: The modifiers, applied in order after the core of each step.rebuilds::Any: Whether the local step rebuilds the parts that use it.
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.
For each stratum
where M[i, j] the share of origin Init to within the square root of the machine epsilon. With leak = true a column may sum to less than one, for a share lost on the way. M is an S × S matrix, or TimeVarying of an S × S × T array for movement that changes over time; its entries are its parameters, and a gradient with respect to anything they are built from flows through that construction.
Redistribute(K, ε) builds
so ε is one value or a vector over origins, which gives a matrix, or an origins × time matrix, which gives an S × S × T movement. PerStratum(ε) and TimeVarying(PerStratum(E)) are read as the vector and the matrix they hold. Any other parameter, such as TimeVarying(ε) or one built with Derived or Recent, is read at each step as
Place it before a ComposableRecurrences.Depletion to deplete each stratum's pool by what it realises; a modifier sees add values move too. The step is the coupling product
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 sets the type parameterLofRedistribute{L}, so pass it as a literal, which is folded at compile time. For a flag read from a variable,Redistribute{leak}(M)names the type directly.
Examples
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.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.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
CR.Flow(1 => 0, 0.15; form = CR.Share()).form
# output
ComposableRecurrences.Share()Fields
sourceComposableRecurrences.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([true]; modifiers = (d,))(; history = [6.0; 2.0;;], stop = 2)
# output
2×2 Matrix{Float64}:
1.5 0.0
4.5 1.0Fields
sourceComposableRecurrences.Step Type
struct StepThe role of one step of a modifier, or of a depletion form inside its ComposableRecurrences.Depletion.
A modifier
where
forward!(m, Step(), v, s, t)updates the step's valuesvand the modifier's statesin place (one entry per stratum, or one per pool for aComposableRecurrences.Depletionwith several) and returnsnothing. A pointwise modifier, withComposableRecurrences.blocks(1, 1), writes entrykfrom entrykonly, and may be called on a one-entry view of stratumk.forward!(m, Step(), v, s, t, g)is the group step of a blockwise modifier (ComposableRecurrences.blocks), withvandstuples of one-entry views of groupg's values and state.forward!(form, Step(), v, s, N)drawsvfrom poolsin place for a depletion form, withvandsviews andNa number.
A step writes its outputs and returns nothing; one that returns anything else is an error. The matching ComposableRecurrences.pullback! takes grads first and then the same arguments, as pullback!(grads, m, Step(), v, s, t).
Examples
using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0], [80.0]
CR.forward!(CR.Hazard(), CR.Step(), v, s, 100.0)
round.(v; digits = 3), round.(s; digits = 3)
# output
([1.584], [78.416])Fields
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. 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 or a tracked real, counts as one word, as do the floats of an AD backend that carries its tangents or shadows beside the arrays rather than in them. Loops split every step count each multiply-add once whatever the type.
The default min_work of 500 000 comes from whole-loss timings (benchmark/threshold.jl). Strata that mix split only with a pairwise kernel over a few hundred strata or a coupling over tens of thousands. Results are identical to Serial because each index writes only its own slots. A reverse pass sums per chunk the cotangents of parameters that chunks of strata share, such as a scalar modifier parameter, so those agree with Serial up to rounding. Errors inside a split loop arrive wrapped in a CompositeException: an error in a chunk on a new task as a TaskFailedException, and one in the chunk the calling task runs as an exception that shows it with its backtrace. On arrays that live on a GPU, Threaded runs a call as Parallel on the arrays' own backend, as Serial does: host threads cannot index them.
Examples
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, columns of tracked numbers and columns on a device are stacked into one vector instead, as is a kernel that adapt moves to a device. A Recurrence coupling is S × S × T. A modifier parameter is length T, or TimeVarying(PerStratum(B)) with B S × T.
A coefficient that changes at a few times is given by its change points, [t_1 => c_1, t_2 => c_2, ..., t_J => c_J] with
so the last value holds at every later time and the coefficient covers any stop. Each value has the form of one column: a number for a parameter, a vector of lag weights for a kernel (shorter ones padded with zero weights), an S × S matrix for a coupling, or a PerStratum of these. Only the Pairwise values are not taken; a pairwise kernel is the dense TimeVarying(Pairwise(A)). Values and gradients equal those of the dense array that repeats each value over its segment. Inside a differentiated function, build the pairs as Pair.(starts, values) or a comma-separated literal, not by vcat (one backend loses their derivatives).
The indexing sets which time a kernel's column belongs to, and is held as a type parameter so nothing branches on it:
ComposableRecurrences.Secondary(the default): 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.0A delay pmf per input time, truncated at the horizon:
using ComposableRecurrences
ks = [[0.5, 0.5], [0.75, 0.25], [1.0]]
Convolution(TimeVarying(ks, ComposableRecurrences.Primary()))(ones(3))
# output
3-element Vector{Float64}:
0.5
1.25
1.25A generation interval that shortens from time 6, given by its change points, against the dense array that repeats each kernel:
using ComposableRecurrences
long_gi, short_gi = [0.2, 0.5, 0.3], [0.6, 0.4]
r = Recurrence(TimeVarying([1 => long_gi, 6 => short_gi]))
y = r(1.2; history = ones(3), start = 4, stop = 8)
G = hcat([t < 6 ? long_gi : [short_gi; 0.0] for t in 1:8]...)
dense = Recurrence(TimeVarying(G))(1.2; history = ones(3), start = 4, stop = 8)
y ≈ dense, round.(y; digits = 3)
# output
(true, [1.2, 1.248, 1.475, 1.661, 1.904])Fields
x::Any: The coefficients, time on the last axis.
ComposableRecurrences.Trace Type
struct TraceThe role of a modifier's trace: what a call with record = (:trace,) records for it at each step.
At absolute time
with ComposableRecurrences.Transform, records nothing. A ComposableRecurrences.Depletion with a draw records its pools after the step, the value it passes on ComposableRecurrences.Redistribute records its arrivals, its state. A modifier records its trace with forward!(m, Trace(), r, v, s, v′, s′, t), writing into r, which takes the shape of v for its kind of step: for a pointwise modifier (ComposableRecurrences.ispointwise) a tuple of vectors, one per trace value, indexed by stratum as v is, their kth entries filling row (j - 1) * S + k; for a blockwise modifier (ComposableRecurrences.blocks), as forward!(m, Trace(), r, v, s, v′, s′, t, g) for group g, a tuple of one-entry views filling rows (j - 1) * G + g for v, s, v′ and s′ tuples of one-entry views; for any other modifier the step's column of ComposableRecurrences.ntrace rows. Its pullback, pullback!(grads, m, Trace(), v, s, t) (with g for a group), is given grads = (; piece, trace, v, s, v′, s′): trace holds the cotangent of r, in its shape, and the pullback adds the cotangents of the step's inputs and outputs into v, s, v′ and s′ and those of the modifier's parameters into piece.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
r = ([0.0], [0.0], [0.0])
CR.forward!(CR.Depletion(100.0), CR.Trace(), r, [2.0], [80.0], [1.6], [78.4], 1)
r
# output
([78.4], [1.6], [0.3999999999999999])Fields
sourceComposableRecurrences.Transform Type
struct Transform{F, P}A modifier that maps each stratum's value through a function f, with optional parameters θ.
At time
where θ read at stratum f receives a tuple or NamedTuple of scalars. Without θ the map is
The reverse pass, for output cotangent
with the partial derivatives from the map's local rule, a ComposableRecurrences.pullback! method for f in the ComposableRecurrences.Local role, when it has one, or else from a local forward-mode derivative of f. The local rule receives the step's output f (a closure, or a callable struct with float fields) are not in Recurrence holding such a map.
Three maps have their own pullbacks. Transform(+, b) adds ComposableRecurrences.Depletion, the added values are neither scaled by nor drawn from the pool. Alone, Transform(+, TimeVarying(PerStratum(B))) gives the values of passing B as add. Transform(clamp, lo, hi) bounds each value to lo and hi, with Transform(*, γ) scales each value by add values with the kernel's, so the gain acts on both before an ComposableRecurrences.Allocate or a draw. A γ that is a plain number has no cotangent, so its pullback adds none.
It acts on a Recurrence and is pointwise. Its rule takes the map's local rule or the local forward-mode derivative, or a hand-written pullback for +, clamp and *.
Arguments
f: the map, called 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.961Each partial derivative of G contains G itself, so a local rule for it can read the output:
using ComposableRecurrences
CR = ComposableRecurrences
struct NBPGF end
(::NBPGF)(s, θ) = (θ.p / (1 - (1 - θ.p) * s))^θ.r
function CR.pullback!(grads, ::NBPGF, ::CR.Local, y, s, θ)
D = 1 - (1 - θ.p) * s
return y * θ.r * (1 - θ.p) / D,
(; r = y * log(θ.p / D), p = y * θ.r * (1 - s) / (θ.p * D))
end
q = CR.Transform(NBPGF(), (; r = 0.5, p = 0.4))
y = Recurrence([1.0]; modifiers = (q,))(; history = [0.0], stop = 3)
round.(y; digits = 3)
# output
3-element Vector{Float64}:
0.632
0.803
0.879Fields
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
v, s = [2.0, 2.0], [80.0, 1.5]
CR.forward!(CR.Truncate(), CR.Step(), v, s, 100.0)
v, s
# output
([2.0, 1.5], [78.0, 0.0])using ComposableRecurrences
CR = ComposableRecurrences
v, s = [2.0], [2.0]
CR.forward!(CR.Truncate(0.1), CR.Step(), v, s, 100.0)
round.(v; digits = 3), round.(s; digits = 3)
# output
([1.866], [0.134])Fields
κ::Any: The softness κ, 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: it implements forward!(m, Step(), v, s, t) writing entry k of v and s from entry k only, for each k in eachindex(v). The operator may call it on a one-entry view of stratum k, whose axes are k:k, so a parameter read at k through ComposableRecurrences.param reads the right entry; a broadcast against a field with one entry per stratum, such as v .*= m.w, cannot run on such a view. Any other shape is blockwise: the modifier implements forward!(m, Step(), v, s, t, g) with v and s tuples of one-entry views of group g's pullback!(grads, m, Step(), v, s, t, g) with grads.v and grads.s tuples of views, overwritten with the input cotangents. Both return nothing, and the default vector ComposableRecurrences.Step loops the groups. The group step reads parameters at group g, so a PerStratum parameter has blocks should follow from the type of m, not from the value of a field, so the loops are compiled for its shape; a shape read from a field is known only at run time. ComposableRecurrences.ispointwise and ComposableRecurrences.nstate follow from it. The default is nothing. Groups of different sizes, such as the patches of ComposableRecurrences.Allocate, are a value of the modifier, so its blocks is nothing.
Arguments
m: the modifier.
Examples
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.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, and nothing for an 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;
step
) -> AbstractVectordelay_masses(k, lags; step = 1)Return the masses of a delay k on lags 0 to lags - 1, lag 0 first, as a vector of length lags:
where step is the width of a lag in that unit and lags. With the default step = 1 a lag is one unit of the delay. A delay on continuous time is censored with both windows one step wide: its primary event is uniform over one step and step = 0.25 do not sum to the mass with step = 1. A Convolution kernel is this vector. A Recurrence kernel starts at lag 1, so it is the vector without lags has no default: a kernel of delays without lags is an error, and so is lags on a kernel with no delays. Both operators pass step on, and step without lags is an error. A step other than 1 suits a model whose time unit differs from the delay's unit, such as step = 7 for weekly steps and delays in days.
The method for a vector returns it as it is, whatever lags and step. A package that owns a delay type adds a method for that type:
it returns an
AbstractVectorof lengthlags, lag 0 first;it takes
stepas a keyword, defaulting to 1, and gives laglthe mass on ; the operators always pass it, so a method that servesstep = 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
step: 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; step) -> 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 step units wide. A vector of masses is read as given, whatever its length and step, so it must already be on lags of that width.
A chain of discretised delays and a sum of continuous delays discretised once are different models.
Examples
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::Real, r::Real, 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.growth_rategives it from a reproduction number and generation interval.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, define a type and add this method for its role: ComposableRecurrences.Step and ComposableRecurrences.Init for a modifier or depletion form, ComposableRecurrences.Pressure for a coupling and ComposableRecurrences.Trace for a modifier's record.
A pointwise step runs under ComposableRecurrences.Parallel when it reads and writes only eachindex(v) entries, and allocates nothing.
Arguments
x: the coupling, modifier or depletion form.role:Step(),Init(),Pressure()orTrace().args: the role's arguments.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
struct Offset{T}
b::T
end
CR.blocks(::Offset) = (1, 1)
function CR.forward!(m::Offset, ::CR.Step, v, s, t)
for k in eachindex(v)
v[k] += m.b
end
return nothing
end
r = Recurrence([0.5, 0.5]; modifiers = (Offset(1.0),))
r(1.0; history = ones(2), stop = 4)
# output
4-element Vector{Float64}:
2.0
2.5
3.25
3.875ComposableRecurrences.growth_rate Function
growth_rate(R::Real, g::AbstractVector{<:Real}) -> AnyReturn the growth rate per step R and generation interval g, from the Euler–Lotka equation
where g[l], the weight on lag Recurrence kernel. It gives the rate that ComposableRecurrences.exponential_history needs for a seed that grows as the renewal does.
The derivative in R and g is exact under every automatic differentiation backend, without a rule.
Arguments
R: the reproduction number, positive.g: the generation interval, withg[1]the weight on lag 1; its weights are non-negative with a positive sum.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
g = [0.2, 0.5, 0.3]
r = CR.growth_rate(1.5, g)
residual = 1.5 * sum(g[l] * exp(-r * l) for l in 1:3)
round(r; digits = 4), round(residual; digits = 8)
# output
(0.1977, 1.0)ComposableRecurrences.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.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.Derived, ComposableRecurrences.Increments, ComposableRecurrences.Normalised, ComposableRecurrences.Survival}},
n::Integer
) -> 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. 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.
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, its state after each step, or none for a modifier whose state never changes (ComposableRecurrences.isstateless).
Arguments
m: the modifier.S: the number of strata.
Examples
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)Return how many rows each top-level parameter field of a whole-step modifier m has in a call over S strata, or nothing to skip the check.
A row is one entry of a PerStratum or one row of a TimeVarying(PerStratum(x)). Before its ComposableRecurrences.Init, each call checks
where 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
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. For outputs from a traced call, trace.pressure is the same pressure. It is differentiable in the outputs, the history, the kernel and the coupling. pressure(NoAdjoint(r), y) gives the same values with the rule turned off, as ComposableRecurrences.NoAdjoint does for the call.
Arguments
r: the recurrence, 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; 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. A pointwise or blockwise Step gets the same views as its forward!, with grads.v and grads.s views of the same entries. The mirror grads.piece has one entry per field: a Ref for a float scalar, an array of the same shape for a float array and nothing for a field held constant. An operator's native rule calls a method whose grads and arguments after the role are untyped, as only such a method sets ComposableRecurrences.uses_adjoint. Without one, the object is differentiated by a local dual-number step inside the rule where that is cheap, and the whole operator takes plain AD otherwise.
Arguments
grads: the cotangents,(; piece, ...), withpiecethe mirror ofx's parameters.x: the operator, coupling, modifier or depletion form.role: the role.args: the primal argumentsforward!was given.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
m = CR.Transform(clamp, 0.0, 1.0)
grads = (; piece = (; θ = (Ref(0.0), Ref(0.0))), v = [1.0], s = [0.0])
CR.pullback!(grads, m, CR.Step(), [2.0], [0.0], 1)
grads.v, grads.piece.θ[2][]
# output
([0.0], 1.0)ComposableRecurrences.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