Functions currently supported by the C++ TMB engine for constructing expressions for defining model simulations.
Details
The quickest way to experiment with these functions is
to use the engine_eval
function, as in the
following example that calculates a force of infection.
To produce a simulation using these engine functions, one may
use simple_sims
.
Elementwise Binary Operators
Elementwise binary operators take two matrix-valued
arguments and apply a binary operator (e.g. +
, *
)
to each set of corresponding elements, and return the
corresponding matrix-valued output containing the
resulting elements. What does 'corresponding' mean? If
the two matrix-valued arguments have the same shape
(same number of rows and columns), then two elements
correspond if they occur in the same row and column
position in the two matrices. If the two matrices are
not of the same shape but there is one row and/or
one column in either matrix, then the singleton rows
and columns are recycled sufficiently many times
so that they match the shape of the other matrix. If
after recycling singleton rows and columns the
matrices are still of different shape, then an error
is thrown and the matrices are said to be incompatible.
Arguments
x
– Any matrix with dimensions compatible withy
.y
– Any matrix with dimensions compatible withx
.
Unary Elementwise Math
Functions
log(x)
– Natural logarithmexp(x)
– Exponential functioncos(x)
– Cosine functionproportions(x, limit, eps)
– matrix ofx / sum(x)
orrep(limit, length(x))
ifsum(x) < eps
Integer Sequences
Functions
from:to
– Inclusive and ordered sequence of integers between two bounds.seq(from, length, by)
– Ordered sequence of integers with equal spacing between adjacent values.
Arguments
from
– Scalar integer giving the first integer in the sequence.to
– Scalar integer giving the last integer in the sequence.length
– Number of integers in the sequence.by
– Scalar giving the difference between adjacent values in the sequence.
Details
The colon operator works much like the base R version
:
. It takes two scalar-valued integers
and returns a column vector with all integers between
the two inputs.
The seq
function is a little different from the
base R default, seq
, in that it
allows the user precise control over the length of
the output through the length
argument. The
base R function gives the user this option, but not
as the default.
Functions
rep(x, times)
– Replicate a column vector a number of times, by repeatedly stacking it on top of itself.rep_each
– Not yet developed.rep_length
– Not yet developed.
Matrix Multiplication
Parenthesis
The order of operations can be enforced in the usual
way with round parentheses, (
.
Reshaping and Combining Matrices
Functions
c(...)
– Stack columns of arguments into a single column vector.cbind(...)
– Create a matrix containing all of the columns of a group of matrices with the same number of rows.rbind(...)
– Create a matrix containing all of the rows of a group of matrices with the same number of columns.matrix(x, rows, cols)
– Reshape a matrix to haverows
rows andcols
columns. The inputx
must haverows * cols
elements.t(x)
– Standard matrix transpose.
Arguments
...
– Any number of dimensionally consistent matrices. The definition of dimensionally consistent depends on the function.x
– Can be any matrix fort
, but formatrix
it must haverows * cols
elements.rows
– Scalar integer giving the number of rows in the output.cols
– Scalar integer giving the number of columns in the output.
Details
Any number of column vectors can be combined into a bigger column vector.
Column and row vectors of the same length can be
combined using the cbind
and
rbind
functions respectively
The matrix
function can be used to redefine the
numbers of rows and columns to use for arranging
the values of a matrix. It works similarly to
the base R matrix
function in that it
takes the same arguments.
On the other hand, this function differs substantially
from the base R version in that it must be filled
by column and there is no byrow
option.
Matrices can be transposed with the usual
function, t
.
Matrix Diagonals
Functions
to_diag(x)
– Create a diagonal matrix by setting the diagonal to a column vector,x
.from_diag(x)
– Extract the diagonal from a matrix,x
, and return the diagonal as a column vector.
Arguments
x
– Any matrix (forfrom_diag
) or a column vector (forto_diag
). It is common to assume thatx
is square forfrom_diag
but this is not required.
Return
to_diag(x)
– Diagonal matrix withx
on the diagonal.from_diag(x)
– Column vector containing the diagonal ofx
. A value is considered to be on the diagonal if it has a row index equal to the column index.
Summarizing Matrix Values
Functions
sum(...)
– Sum all of the elements of all of the matrices passed to...
.col_sums(x)
– Row vector containing the sums of each column.row_sums(x)
– Column vector containing the sums of each row.group_sums(x, f, n)
– Column vector containing the sums of groups of elements inx
. The groups are determined by the integers inf
and the order of the sums in the output is determined by these integers.
Arguments
...
– Any number of matrices of any shape.x
– A matrix of any dimensions, except forgroup_sums
that expectsx
to be a column vector.f
– A column vector the same length asx
containing integers between0
andm-1
, givenm
unique groups. Elements off
refer to the indices ofx
that will be grouped and summed.n
– A column vector of lengthm
. Iff
does not contain groupk
in[0, m-1]
,group_sums
skips this group and the output at indexk+1
isn[k+1]
.
Details
The row_sums
and col_sums
are similar to the base R
rowSums
and colSums
functions,
but with slightly different behaviour. In particular, the
row_sums
function returns a column vector and the
col_sums
function returns a row vector. If a specific shape
is required then the transpose t
function must
be explicitly used.
Extracting Matrix Elements
Functions
x[i,j]
– Matrix containing a subset of the rows and columns ofx
.block(x,i,j,n,m)
– Matrix containing a contiguous subset of rows and columns ofx
https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html
Arguments
x
– Any matrix.i
– An integer column vector (for[
) or integer scalar (forblock
) containing the indices of the rows to extract (for[
) or the index of the first row to extract (forblock
).j
– An integer column vector (for[
) or integer scalar (forblock
) containing the indices of the columns to extract (for[
) or the index of the first column to extract (forblock
).n
– Number of rows in the block to return.m
– Number of columns in the block to return.
Accessing Past Values in the Simulation History
For matrices with their simulation history saved, it is possible to bind the rows or columns of past versions of such matrices into a single matrix.
Functions
rbind_lag(x, lag, t_min)
– Bind the rows of versions ofx
that were recorded at the end of all simulation iterations corresponding to time lags given by integers inlag
.rbind_time(x, t, t_min)
– Bind the rows of versions ofx
that were recorded at the end of all simulation iterations corresponding to integers int
.cbind_lag(x, lag, t_min)
– Bind the columns of versions ofx
that were recorded at the end of all simulation iterations corresponding to time lags given by integers inlag
. (TODO – cbind_lag is not developed yet)cbind_time(x, t, t_min)
– Bind the columns of versions ofx
that were recorded at the end of all simulation iterations corresponding to integers int
. (TODO – cbind_lag is not developed yet)
Arguments
x
– Any matrix with saved history such that the number of columns (forrbind_*
) or rows (forcbind_*
) does not change throughout the simulation.lag
– Integer vector giving numbers of time steps before the current step to obtain past values ofx
.t
– Integer vector giving time steps at which to obtain past values ofx
.t_min
– Integer giving the minimum time step that is allowed to be accessed. All time-steps int
or implied bylag
that are beforet_min
are ignored.
Time Indexing
Get or update the index of the current or lagged time step or the index of the current time group. A time group is a contiguous set of time steps defined by two change points.
Functions
time_step(lag)
: Get the time-step associated with a particular lag from the current time-step. If the lagged time-step is less than zero, the function returns zero.time_group(index, change_points)
: Update theindex
associated with the current time group. The current group is defined by the minimum of all elements ofchange_points
that are greater than the current time step. The time groupindex
is the index associated with this element. Please see the examples below, they are easier to understand than this explanation.time_var(x, change_points)
: An improvement totime_group
. Returns values inx
at time steps inchange_points
, return value remains constant betweenchange_points
.
Arguments
x
: Column vector representing a time series.time_var
will return the value ofx
corresponding to element inchange_points
that contains the current time.lag
: Number of time-steps to look back for the time-step to return.change_points
: Increasing column vector of time steps giving the lower bound of each time group.
Examples
simple_sims(
iteration_exprs = list(x ~ time_step(0)),
time_steps = 10,
mats = list(x = empty_matrix)
)
sims = simple_sims(
iteration_exprs = list(
j ~ time_group(j, change_points),
time_varying_parameter ~ time_variation_schedule[j]
),
mats = list(
j = 0,
change_points = c(0, 4, 7),
time_variation_schedule = c(42, pi, sqrt(2)),
time_varying_parameter = empty_matrix
),
time_steps = 10,
)
set.seed(1L)
change_points = c(0,2,5)
x_val = rnorm(length(change_points))
simple_sims(
iteration_exprs = list(x ~ time_var(x_val,change_points))
, int_vecs = list(change_points = change_points)
, mats = list(x = empty_matrix, x_val=x_val)
, time_steps = 10
)
Convolution
One may take the convolution of each element in a matrix, x, over simulation time using a kernel, k. There are two arguments of this function.
Arguments
x
– The matrix containing elements to be convolved.k
– A column vector giving the convolution kernel.
Return
A matrix the same size as x
but with the
convolutions, \(y_{ij}\), of each element,
\(x_{ij}\), given by the following.
$$y_{ij} = \sum_{\tau = 0} x_{ij}(t-\tau) k(\tau)$$
unless \(t < \tau\), in which case,
$$y_{ij} = $$
where \(y_{ij}\) is the convolution, \(x_{ij}(t)\) is the value of \(x_{ij}\) at time step, \(t\), \(k(\tau)\) is the value of the kernel at lag, \(\tau\), and \(\lambda\) is the length of the kernel.
Clamp
Smoothly clamp the elements of a matrix so that they
do not get closer to 0 than a tolerance, eps
, with
a default of 1e-12. The output of the clamp
function is as follows.
Probability Densities
All probability densities have the same first two arguments.
observed
simulated
The simulated
argument gives a matrix of means for
the observed
values at which the densities are
being evaluated. Additional arguments are other
distributional parameters such as the standard
deviation or dispersion parameter. All densities
are given as log-densities, so if you would like
the density itself you must pass the result through
the exp
function.
If the simulated
matrix or the additional parameter
matrices have either a single row or
single column, these singleton rows and columns are
repeated to match the number of rows and columns in
the observed
matrix. This feature allows one
to do things like specify a single common mean for
several values.
Functions
dpois(observed, simulated)
– Log of the Poisson density based on this dpois TMB function.dnbinom(observed, simulated, over_dispersion)
– Log of the negative binomial density based on this dnbinom TMB function. To get the variance that this function requires we use this expression,simulated + simulated^2/over_dispersion
, following p.165 in this bookdnorm(observed, simulated, standard_deviation)
– Log of the normal density based on this dnorm TMB function.
Arguments
observed
– Matrix of observed values at which the density is being evaluated.simulated
– Matrix of distributional means, with singleton rows and columns recycled to match the numbers of rows and columns inobserved
.over_dispersion
– Over-dispersion parameter given by(simulated/standard_deviation)^2 - simulated)
.standard_deviation
– Standard deviation parameter.
Pseudo-Random Number Generators
All random number generator functions have mean
as the first argument. Subsequent arguments give
additional distributional parameters.
Singleton rows and columns in the matrices passed to
the additional distributional parameters are recycled
so that all arguments have the same number of rows
and columns. All functions return a matrix the same
shape as mean
but with pseudo-random numbers
deviating from each mean in the mean
matrix.
Assign
Assign values to a subset of the elements in a matrix.
Arguments
x
– Matrix with elements that are to be updated by the values inv
.i
– Column vector of row indices pointing to the elements ofx
to be updated. These indices are paired with those inv
. If the length ofi
does not equal that ofv
, then it must have a single index that gets paired with every element ofv
. Indices are zero-based,i=0
corresponds to the first row.j
– Column vector of column indices pointing to the elements ofx
to be updated. These indices are paired with those inv
. If the length ofj
does not equal that ofv
, then it must have a single index that gets paired with every element ofv
. Indices are zero-based,j=0
corresponds to the first column.v
– Column vector of values to replace elements ofx
at locations given byi
andj
.
Return
The assign
function is not called for its return
value, which is an empty_matrix
, but
rather to modify x
but replacing some of its
components with those in v
.
Unpack
Unpack elements of a matrix into smaller matrices.
Arguments
x
– Matrix with elements to be distributed to the matrices passed through...
....
– Matrices with elements to be replaced by the values of elements inx
in column-major order. These matrices must be named matrices and not computed on the fly using expressions. Note that even subsetting (e.g.unpack(x, y[0], y[3])
) counts as an expression. This use-case would require theassign
functionassign(y, c(0, 3), 0, x)
.
Return
The unpack
function is not called for its return
value, which is an empty_matrix
, but
rather to modify the matrices in ...
by replacing
at least some of its components with those in x
.