| Title: | Laplace Approximations Using Automatic Differentiation |
|---|---|
| Description: | Computes Laplace approximations for hierarchical models using automatic differentiation (CppAD) and trust-region optimization. |
| Authors: | Patrick Brown [aut, cre, cph] |
| Maintainer: | Patrick Brown <[email protected]> |
| License: | MPL-2.0 |
| Version: | 0.5.2 |
| Built: | 2026-07-17 23:38:35 UTC |
| Source: | https://github.com/eborgnine/adlaplace |
Character vector of allowed levels for the type slot on
model objects.
.type_factor_levels.type_factor_levels
An object of class character of length 3.
Build design matrices and parameter metadata from a formula
ad_data( y = missing(), A = NULL, X = NULL, beta_map = NULL, gamma_map = NULL, theta_map = NULL, elgm_matrix = NULL, ad_fun = NA_character_, ad_kind = NA_character_, package = NA_character_, precision = NULL, weights = numeric(0) ) data_setup(formula, data, verbose = FALSE)ad_data( y = missing(), A = NULL, X = NULL, beta_map = NULL, gamma_map = NULL, theta_map = NULL, elgm_matrix = NULL, ad_fun = NA_character_, ad_kind = NA_character_, package = NA_character_, precision = NULL, weights = numeric(0) ) data_setup(formula, data, verbose = FALSE)
y |
Response vector (default empty), or an existing |
A |
Random-effects design matrix ( |
X |
Fixed-effects design matrix ( |
beta_map |
Beta parameter map (any |
gamma_map |
Gamma parameter map (any |
theta_map |
Theta parameter map (any |
elgm_matrix |
Optional ELGM map (any |
ad_fun |
Registered AD density name for this shard (optional). |
ad_kind |
Shard kind ( |
package |
Package recording AD tapes for this shard (optional). |
precision |
Optional precision payload (any R object). |
weights |
Optional per-observation weights (e.g. binomial trial counts). Empty means all ones. |
formula |
Model formula or named list of term objects. |
data |
Data frame. |
verbose |
Print parsing messages. |
List with terms, y, A, X, data, info.
The info$theta data frame includes a logical transform column:
TRUE means the parameter is stored on the log scale when
config$transform_theta is TRUE (default for all rows unless a
model term sets otherwise). info$parameters stacks beta and
theta rows with the same transform column (FALSE for
fixed effects); init, lower, and upper are already on
the optimization (log) scale where transform is TRUE.
ad_data(): Construct an ad_data object
Per-shard layout for AD density evaluation
yResponse vector.
ATpTranspose of random-effects design matrix.
XTpTranspose of fixed-effects design matrix.
beta_mapBeta parameter map (ngCMatrix). nrow is the
global beta block size; column j has one structural nonzero at row
r meaning local design column j of X uses global beta
r. When ncol(X) > 0, require ncol(beta_map) == ncol(X).
gamma_mapGamma parameter map (ngCMatrix); at most one structural
nonzero per row and column. Same column convention as beta_map for
local A columns into the global gamma block.
theta_mapTheta parameter map (ngCMatrix). Column j
selects global theta row r for this shard's theta component j.
elgm_matrixOptional exposure-lag map (ngCMatrix; empty by default).
ad_funRegistered AD density name for this shard.
ad_kindShard kind ("observations", "parameters", "random").
packagePackage name whose shared library records tapes for this shard
(defaults to "adlaplace" when missing).
precisionOptional precision payload (any R object).
weightsOptional per-observation weights (e.g. binomial trial counts). Empty means all ones.
Build AD function with Hessian templates
ad_fun(x, config = NULL, num_threads = 1L, ...) ## S4 method for signature 'ad_fun_ptr' ad_fun(x, config = NULL, num_threads = 1L, ...) ## S4 method for signature 'ad_data' ad_fun(x, config = NULL, num_threads = 1L, ...) ## S4 method for signature 'list' ad_fun(x, config = NULL, num_threads = 1L, ...)ad_fun(x, config = NULL, num_threads = 1L, ...) ## S4 method for signature 'ad_fun_ptr' ad_fun(x, config = NULL, num_threads = 1L, ...) ## S4 method for signature 'ad_data' ad_fun(x, config = NULL, num_threads = 1L, ...) ## S4 method for signature 'list' ad_fun(x, config = NULL, num_threads = 1L, ...)
x |
One of: an |
config |
Model configuration list. Required for |
num_threads |
Positive integer; OpenMP thread count for |
... |
For |
Object of class ad_fun.
Constructs CppAD tapes for a single shard. The density kind and name come
from data@ad_kind and data@ad_fun. For ad_kind = "random",
data@precision is passed straight to the backend. For
random_diagonal it must be a numeric vector of diagonal precision
weights with length == ncol(gamma_map). Missing precision means the
shard is not built (e.g. diffuse rpoly with sd = Inf via
model_data()); calling ad_fun_ptr() without it is an error.
ad_fun_ptr(data, config)ad_fun_ptr(data, config)
data |
An |
config |
Model configuration list ( |
Merge handles for multiple shards with c() before calling
ad_fun.
External pointer of class ad_fun_ptr.
S4 class for a C++ AD backend handle. Objects are created by
ad_fun_ptr, combined with c.ad_fun_ptr, and
typically passed to ad_fun to attach Hessian templates.
ad_fun_ptr, ad_fun,
clone_ad_fun_ptr
AD function with Hessian templates attached
ptrRaw combined handle (ad_fun_ptr).
group_sparsityPer-group inner gradient sparsity patterns.
outerOuter Hessian template (dgCMatrix).
innerInner-gamma Hessian template (dgCMatrix).
map_outerOuter Hessian shard map.
map_innerInner Hessian shard map.
parallel_mapThread-affinity map (ngCMatrix); rows are shards,
columns are threads, with one nonzero per shard row.
chol_innerSymbolic LDL factor or empty sparse matrix.
chol_inner_listNumeric LDL list for C++ (L1, Linv,
perm, perm_inv, half_H_inv, H_inv), plus
trace_columns (per-shard column indices for trace_hinv_t).
sizesNamed numeric vector beta/gamma/theta.
infoList of parameter metadata (beta, gamma,
theta, parameters); populated from model_data()$data$info
when the handle is built from a model-data bundle, otherwise empty.
The function partitions columns into num_shards shards using
quantiles of the first right singular vector, optionally using RSpectra
for efficiency when available.
A |
Random-effects design matrix ( |
elgm_matrix |
A numeric matrix (or matrix-like object) for extended latent gaussian models. |
num_shards |
Integer giving the maximum number of shards to construct. The actual number of shards may be smaller if fewer distinct loadings are present. |
min_groups |
Integer giving the minimum number of shards. When there
are fewer distinct singular-vector loadings than |
The resulting grouping is returned as a sparse matrix whose columns correspond to shards and whose entries are the singular-vector loadings. Shards are ordered from most heterogeneous to most homogeneous.
If the RSpectra package is available, the leading singular vector
is computed using RSpectra::svds; otherwise, a full singular value
decomposition via svd is used.
Shard boundaries are defined by empirical quantiles of the loadings. Shards are subsequently reordered so that shards with larger within-shard variability appear first.
A sparse matrix of class "dgCMatrix" (from Matrix), with
one column per shard and one row per observation. Nonzero entries
correspond to singular-vector loadings.
set.seed(1) A <- matrix(rnorm(100), 20, 5) G <- ad_shards(A, num_shards = 3) Gset.seed(1) A <- matrix(rnorm(100), 20, 5) G <- ad_shards(A, num_shards = 3) G
One-call interface to the adlaplace pipeline: parse the formula with
model_data(), partition observations into AD shards with
ad_shards(), build the AD handle with ad_fun(),
maximize the Laplace-approximate marginal likelihood with
optim() using the exact profile gradient
(outer_fn / outer_gr), and return a fitted-model
object with standard accessor methods.
adlaplace( formula, data, config = list(), num_threads = 1L, num_shards = 100L, control = list(), control_inner = list(maxit = 100L, report.level = 0, report.freq = 0), method = "L-BFGS-B", hessian = TRUE, verbose = FALSE, na_omit = TRUE )adlaplace( formula, data, config = list(), num_threads = 1L, num_shards = 100L, control = list(), control_inner = list(maxit = 100L, report.level = 0, report.freq = 0), method = "L-BFGS-B", hessian = TRUE, verbose = FALSE, na_omit = TRUE )
formula |
Model formula built from model terms, e.g.
|
data |
Data frame containing the variables referenced in |
config |
List of backend options merged over the defaults
|
num_threads |
Positive integer, OpenMP thread count for the AD handle. |
num_shards |
Target number of observation shards for
|
control |
List of |
control_inner |
List of control options for the inner (random effects) trust-region optimizer. |
method |
|
hessian |
Logical. When |
verbose |
Logical, print progress. |
na_omit |
Passed to |
An object of class "adlaplace_fit": a list with components
The matched call and model formula.
Named outer parameter estimates on the optimization scale
(log scale where par_info$transform is TRUE).
Parameter metadata table (info$parameters).
Inverse of the numerically differentiated Hessian of the
negative log likelihood (optimization scale), or NULL.
Named random-effect modes at the optimum.
Laplace-approximate marginal log likelihood and the number of observations.
Full optim result, including
hessian when requested.
Result of log_lik_laplace(deriv = TRUE) at
the optimum (gradient, Cholesky factors, inner solution).
Objects needed by the accessor methods and for warm restarts.
summary.adlaplace_fit, predict.adlaplace_fit,
log_lik_laplace, model_data
## Not run: fit <- adlaplace( nbinom(y, lower = 1e-9, init = 0.15) ~ x + iid(g, init = 0.1), data = dat, num_threads = 2L ) summary(fit) confint(fit) ## End(Not run)## Not run: fit <- adlaplace( nbinom(y, lower = 1e-9, init = 0.15) ~ x + iid(g, init = 0.1), data = dat, num_threads = 2L ) summary(fit) confint(fit) ## End(Not run)
Low-level entry points exposed to R. Accept an ad_fun S4 object
(via @ptr) or a raw ad_fun_ptr.
joint_log_dens(ad_fun, x, shards = NULL, negative = TRUE) grad(ad_fun, x, shards = NULL, inner = FALSE, negative = TRUE) hessian( ad_fun, x, shards = NULL, inner = FALSE, verbose = FALSE, negative = TRUE ) trace_hinv_t(ad_fun, x, LinvPt, LinvPtColumns, verbose = FALSE) fun_obj_fdfh(ad_fun, parameters, gamma, inner = TRUE, verbose = FALSE)joint_log_dens(ad_fun, x, shards = NULL, negative = TRUE) grad(ad_fun, x, shards = NULL, inner = FALSE, negative = TRUE) hessian( ad_fun, x, shards = NULL, inner = FALSE, verbose = FALSE, negative = TRUE ) trace_hinv_t(ad_fun, x, LinvPt, LinvPtColumns, verbose = FALSE) fun_obj_fdfh(ad_fun, parameters, gamma, inner = TRUE, verbose = FALSE)
ad_fun |
An |
x |
Numeric parameter vector of length |
shards |
Optional integer vector of 0-based shard indices; |
negative |
Logical (default |
inner |
Logical; if |
verbose |
Logical; if |
LinvPt, LinvPtColumns
|
Sparse factors for |
parameters |
Numeric vector of length |
gamma |
Numeric vector of length |
See individual functions.
With default negative = TRUE, joint_log_dens(), grad(),
and hessian() match inner_opt() (negative log-density). Set
negative = FALSE for the joint log density and its derivatives at the
same x.
Standard accessor methods for objects of class "adlaplace_fit"
returned by adlaplace(). Estimates are stored on the
optimization scale (log scale for parameters with
par_info$transform = TRUE, e.g. standard deviations); methods with a
transform argument report the natural scale by exponentiating and, for
standard errors, applying the delta method.
## S3 method for class 'adlaplace_fit' coef(object, transform = TRUE, ...) ## S3 method for class 'adlaplace_fit' vcov(object, transform = FALSE, ...) ## S3 method for class 'adlaplace_fit' logLik(object, ...) ## S3 method for class 'adlaplace_fit' nobs(object, ...) ## S3 method for class 'adlaplace_fit' confint(object, parm, level = 0.95, transform = TRUE, ...) ## S3 method for class 'adlaplace_fit' fitted(object, ...) ## S3 method for class 'adlaplace_fit' predict(object, newdata, n = 500L, ...) ## S3 method for class 'adlaplace_fit' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'adlaplace_fit' summary(object, level = 0.95, ...) ## S3 method for class 'summary.adlaplace_fit' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'adlaplace_fit' plot(x, k = 200L, draws = 100L, ...)## S3 method for class 'adlaplace_fit' coef(object, transform = TRUE, ...) ## S3 method for class 'adlaplace_fit' vcov(object, transform = FALSE, ...) ## S3 method for class 'adlaplace_fit' logLik(object, ...) ## S3 method for class 'adlaplace_fit' nobs(object, ...) ## S3 method for class 'adlaplace_fit' confint(object, parm, level = 0.95, transform = TRUE, ...) ## S3 method for class 'adlaplace_fit' fitted(object, ...) ## S3 method for class 'adlaplace_fit' predict(object, newdata, n = 500L, ...) ## S3 method for class 'adlaplace_fit' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'adlaplace_fit' summary(object, level = 0.95, ...) ## S3 method for class 'summary.adlaplace_fit' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'adlaplace_fit' plot(x, k = 200L, draws = 100L, ...)
object, x
|
An |
transform |
Logical; report transformed (natural-scale) values. |
... |
Passed to downstream methods. |
parm |
Optional subset of parameter labels or indices. |
level |
Confidence level. |
newdata |
Data frame of prediction covariates. |
n |
Number of random-effect draws for |
digits |
Number of significant digits to print. |
k |
Number of evaluation points per smooth term in |
draws |
Number of simulation draws per smooth term in |
predict draws random effects from the Laplace (Gaussian)
approximation at the mode via sim_fit and returns the linear
predictor on newdata: a nrow(newdata) by n matrix of
simulated values (plus fixed-effect contributions from terms whose
variables appear in newdata). Without newdata it returns
fitted(object).
plot draws each smooth term (terms with more than one knot)
on a grid spanning its knots, showing simulated curves from the Laplace
approximation with the pointwise mean in red. With no smooth terms it
plots the random-effect modes.
When active is TRUE, logs values in cols for rows where
theta_info$transform is TRUE. Missing or NA transform
entries default to TRUE.
apply_theta_log(theta_info, cols = "init", active = TRUE)apply_theta_log(theta_info, cols = "init", active = TRUE)
theta_info |
Data frame from |
cols |
Character vector of column names to transform (e.g. |
active |
Logical; when |
A copy of theta_info with selected entries logged.
Model term for the observation-level binomial log density with
a logit link, registered as binomial_obs. For each observation with
linear predictor eta = X beta + A gamma, trial count N, and
success count y, the log density contribution is
y * eta - N * log(1 + exp(eta)) (up to a data-only constant). When
size is omitted, N = 1 (Bernoulli). There are no
observation-level hyperparameters.
Creates a response term wired to the binomial_obs AD
shard. A Bernoulli likelihood (size omitted) has no observation-level
hyperparameters. With size, trial counts are read from that column
of data and stored as observation weights.
When called with no response variable this function falls back to
stats::binomial(), so glm(..., family = binomial) and
MASS::glmmPQL(..., family = binomial) keep working with
adlaplace attached.
binomial(x, size = NULL, link = "logit")binomial(x, size = NULL, link = "logit")
x |
Outcome variable name (counts of successes; 0/1 when Bernoulli). |
size |
Optional column name for the number of trials per observation. |
link |
Link passed to |
term |
A model term object (S4 methods). |
data |
A data frame containing the variables (S4 methods). |
Binomial observation model term
A binomial object (or a stats::family when called
with no response variable).
model)ad_funCharacter scalar "binomial_obs".
ad_kindCharacter scalar "observations".
sizeOptional column name for per-observation trial counts.
Functions for creating and managing by_group objects for hierarchical model grouping information.
by_group(term, data = NULL, levels = NULL)by_group(term, data = NULL, levels = NULL)
term |
Character, the grouping variable name |
data |
A data frame. If provided and levels is missing, unique values are extracted from data[[term]] |
levels |
Character vector of unique levels for the grouping variable. If missing and data is provided, unique values are extracted from data[[term]] |
A by_group object
# Create with explicit levels bg <- by_group(term = "group", levels = c("A", "B", "C")) # Create from data dat <- data.frame(group = c("A", "B", "A", "C")) bg <- by_group(term = "group", data = dat)# Create with explicit levels bg <- by_group(term = "group", levels = c("A", "B", "C")) # Create from data dat <- data.frame(group = c("A", "B", "A", "C")) bg <- by_group(term = "group", data = dat)
A class for grouping information in hierarchical model terms. Contains the grouping variable name and its levels/labels.
termCharacter vector of length 1, the grouping variable name
levelsCharacter vector of unique levels for the grouping variable
labelsCharacter vector of formatted labels for the levels
ad_fun_ptr handlesMoves AD shards from one or more ad_fun_ptr objects into a single
handle. Inputs are cleared after the merge (ownership moves).
## S3 method for class 'ad_fun_ptr' c(x, ...)## S3 method for class 'ad_fun_ptr' c(x, ...)
x |
An |
... |
Additional |
A combined ad_fun_ptr.
ad_fun_ptr handleReturns a new ad_fun_ptr with independent C++ state (CppAD tapes and
sparsity patterns). Hessian templates are not copied; call ad_fun
on the clone to attach maps. The source handle is left unchanged, unlike
c.ad_fun_ptr which moves shards and clears the inputs.
clone_ad_fun_ptr(x)clone_ad_fun_ptr(x)
x |
An |
A new ad_fun_ptr.
Parses a formula and creates model terms by evaluating constructor calls in
the formula environment (so pkg::term(...) and terms from attached
packages on the search path work). Falls back to the adlaplace
namespace for built-in constructors.
collect_terms(formula, verbose = FALSE)collect_terms(formula, verbose = FALSE)
formula |
Model formula with constructor terms (e.g. |
verbose |
print extra information |
List of model term objects
Maps flat Laplace parameter vectors onto labeled tables from info
(as stored on ad_fun@info or model_data()$data$info).
format_parameters( info, full_parameters = NULL, parameters = NULL, gamma = NULL )format_parameters( info, full_parameters = NULL, parameters = NULL, gamma = NULL )
info |
List with |
full_parameters |
Numeric vector |
parameters |
Numeric outer vector |
gamma |
Numeric inner vector; used when |
A list with data frames parameters and gamma, or
list() when info is missing or incomplete.
Creates and manages fixed polynomial model terms.
fpoly( x, p = 2, ref_value = 0, init = .my_beta_init, lower = .my_beta_lower, upper = .my_beta_upper, parscale = .my_beta_parscale ) ## S4 method for signature 'fpoly' design(term, data) ## S4 method for signature 'fpoly' beta_info(term, data)fpoly( x, p = 2, ref_value = 0, init = .my_beta_init, lower = .my_beta_lower, upper = .my_beta_upper, parscale = .my_beta_parscale ) ## S4 method for signature 'fpoly' design(term, data) ## S4 method for signature 'fpoly' beta_info(term, data)
x |
Variable name. |
p |
Polynomial degree (default: 2). |
ref_value |
Reference value for the polynomial. |
init |
Initial values for beta parameters. |
lower |
Lower bounds for beta parameters. |
upper |
Upper bounds for beta parameters. |
parscale |
Parameter scales for optimization. |
term |
A 'fpoly' term object. |
data |
A data frame containing the variables used in the term. |
A 'fpoly' term object.
A design matrix for the fixed polynomial term, or NULL if p.order is 0.
A data frame containing beta parameter information for the fixed polynomial term.
design(fpoly): Design method for fpoly objects
beta_info(fpoly): Beta info method for fpoly objects
The following methods are available for 'fpoly' objects:
design(term, data)Creates design matrix for fpoly term
precision(term, data)Creates precision matrix for fpoly term
theta_info(term)Extracts theta parameter information
beta_info(term, data)Extracts beta parameter information
random_info(term, data)Extracts random effects information
# Create a fixed polynomial term fpoly_term <- fpoly(x = "temp", p = 3, ref_value = 15)# Create a fixed polynomial term fpoly_term <- fpoly(x = "temp", p = 3, ref_value = 15)
Simulation data for the GAMM vignette example.
A data frame dat with 500 rows and columns from
mgcv::gamSim(6, n = 500), plus simulated negative-binomial responses
used in the GAMM vignette (y, f2, mu, Z, etc.).
Generated with mgcv::gamSim() and a custom negative-binomial
response; see the regeneration comments in vignettes/gamm.Rmd.
data("gamm", package = "adlaplace") exists("dat") nrow(dat)data("gamm", package = "adlaplace") exists("dat") nrow(dat)
Model term for the observation-level Gaussian log density
registered as gaussian_obs. This is the default observation term:
a bare response symbol on the left-hand side of a formula (e.g.
y ~ x) is coerced to gaussian(y) by
collect_terms.
Creates a response term wired to the gaussian_obs AD
shard, with a single residual standard deviation parameter (log scale
during optimization).
When called with no arguments this function falls back to
stats::gaussian(), so glm(..., family = gaussian) keeps
working with adlaplace attached.
gaussian( x, init = 1, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale ) ## S4 method for signature 'gaussian' theta_info(term)gaussian( x, init = 1, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale ) ## S4 method for signature 'gaussian' theta_info(term)
x |
Outcome variable name. |
init |
Initial value for the residual standard deviation. |
lower |
Lower bound for the residual standard deviation. |
upper |
Upper bound for the residual standard deviation. |
parscale |
Parameter scale for optimization. |
term |
A model term object (S4 methods). |
data |
A data frame containing the variables (S4 methods). |
Gaussian observation model term
A gaussian object (or a stats::family when called
with no arguments).
theta_info(gaussian): Theta info for the residual standard deviation.
model)ad_funCharacter scalar "gaussian_obs".
ad_kindCharacter scalar "observations".
Disease-mapping data distributed with INLA (Besag, York, and Mollie 1991).
Counts in 544 districts follow
with a BYM spatial random
effect. The bundled ICAR precision Q_scaled is the INLA
scale.model version with sum-to-zero constraint; prec is the
random_mult precision payload (Q, log_det, rank).
germanygermany
A list with:
Observed case counts (length 544).
Expected counts (length 544).
District index (length 544).
District adjacency matrix (dgCMatrix, 544 x 544).
Scaled ICAR precision (dgCMatrix).
List passed to ad_fun = "random_mult": Q,
log_det, and rank.
District boundaries are not stored in this object (to avoid a hard
dependency on terra). They ship as
system.file("extdata", "germany_map.gpkg", package = "adlaplace")
and can be loaded with terra::vect(...) when terra is installed.
INLA Germany data and germany.graph.
Besag, J., York, J., and Mollie, A. (1991). Bayesian image restoration, with two applications in spatial statistics. Annals of the Institute of Statistical Mathematics, 43(1), 1–20.
Rue, H., Martino, S., and Chopin, N. (2009). Approximate Bayesian inference for latent Gaussian models by using integrated nested Laplace approximations. Journal of the Royal Statistical Society: Series B, 71(2), 319–392.
Whether this build was compiled with OpenMP support.
has_openmp()has_openmp()
TRUE if OpenMP was enabled at compile time, otherwise
FALSE.
Creates and manages IID (independent and identically distributed) random effects terms.
iid( x, init = .my_theta_init, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale ) ## S4 method for signature 'iid' design(term, data) ## S4 method for signature 'iid' precision(term, data) ## S4 method for signature 'iid' random_info(term, data) ## S4 method for signature 'iid' theta_info(term)iid( x, init = .my_theta_init, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale ) ## S4 method for signature 'iid' design(term, data) ## S4 method for signature 'iid' precision(term, data) ## S4 method for signature 'iid' random_info(term, data) ## S4 method for signature 'iid' theta_info(term)
x |
Variable name (typically a factor). |
init |
Initial value for theta parameter. |
lower |
Lower bound for theta parameter. |
upper |
Upper bound for theta parameter. |
parscale |
Parameter scale for optimization. |
term |
An iid term object |
data |
A data frame containing the term variable |
An 'iid' term object (in a named list).
design(iid): Creates design matrix for iid term
precision(iid): Creates precision matrix for iid term
random_info(iid): Extracts random effects information for iid term
theta_info(iid): Extracts theta parameter information for iid term
Runs the inner optimization over using the
trustOptim sparse trust-region CG solver on a pre-built
ad_fun handle.
inner_opt( parameters, gamma, ad_fun, control = NULL, deriv = FALSE, verbose = FALSE )inner_opt( parameters, gamma, ad_fun, control = NULL, deriv = FALSE, verbose = FALSE )
parameters |
Numeric vector of fixed outer parameters
( |
gamma |
Numeric vector of starting values for inner parameters
( |
ad_fun |
|
control |
List of trust-region control parameters (see trustOptim). |
deriv |
Logical; if |
verbose |
Logical; if |
Negates tape log-density values in C++ for minimization via trustOptim.
A list with log_lik, neg_log_lik, parameters,
full_parameters, opt, gradient
(list inner/outer), and hessian
(list inner/outer/chol_inner/half_log_det;
with deriv=TRUE also half_H_inv, H_inv, trace3).
Objective and derivatives use the negative log-density convention.
Creates and manages intercept model terms for fixed effects.
intercept( init = .my_beta_init, lower = .my_beta_lower, upper = .my_beta_upper, parscale = .my_beta_parscale ) ## S4 method for signature 'intercept' design(term, data) ## S4 method for signature 'intercept' beta_info(term, data)intercept( init = .my_beta_init, lower = .my_beta_lower, upper = .my_beta_upper, parscale = .my_beta_parscale ) ## S4 method for signature 'intercept' design(term, data) ## S4 method for signature 'intercept' beta_info(term, data)
init |
Initial value for beta parameter (default: 0) |
lower |
Lower bound for beta parameter (default: -Inf) |
upper |
Upper bound for beta parameter (default: Inf) |
parscale |
Parameter scale for optimization (default: 1) |
term |
A intercept term object |
data |
A data frame containing the term variable |
intercept Model Term
A intercept term object
design(intercept): Creates design matrix for intercept term
beta_info(intercept): Extracts beta parameter information for intercept term
The following methods are available for 'intercept' objects:
design(term, data)Creates design matrix for intercept term
precision(term, data)Creates precision matrix for intercept term
theta_info(term)Extracts theta parameter information
beta_info(term, data)Extracts beta parameter information
random_info(term, data)Extracts random effects information
# Create a intercept term intercept_term <- intercept(init=2)# Create a intercept term intercept_term <- intercept(init=2)
Creates an integrated Wiener process (IWP) model term.
iwp( x, p = 2, ref_value = 0, knots, range = NULL, init = .my_theta_init, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale, boundary_is_random = TRUE, include_poly = TRUE )iwp( x, p = 2, ref_value = 0, knots, range = NULL, init = .my_theta_init, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale, boundary_is_random = TRUE, include_poly = TRUE )
x |
Variable name. |
p |
Order of the integrated Wiener process (default: 2). |
ref_value |
Reference value for the basis. |
knots |
Vector of knot locations. |
range |
Range of the data (optional). |
init |
Initial values for theta parameters. |
lower |
Lower bounds for theta parameters. |
upper |
Upper bounds for theta parameters. |
parscale |
Parameter scales for optimization. |
boundary_is_random |
Whether boundary should be treated as random. |
include_poly |
Whether to include polynomial terms. |
A list containing the 'iwp' term object and optionally polynomial terms.
# Example usage: # knots <- seq(0, 1, length.out = 5) # iwp_term <- iwp(x = "age", knots = knots)# Example usage: # knots <- seq(0, 1, length.out = 5) # iwp_term <- iwp(x = "age", knots = knots)
Creates and manages integrated Wiener process (IWP) model terms.
## S4 method for signature 'iwp' design(term, data) ## S4 method for signature 'iwp' precision(term, data) ## S4 method for signature 'iwp' theta_info(term) ## S4 method for signature 'iwp' random_info(term, data)## S4 method for signature 'iwp' design(term, data) ## S4 method for signature 'iwp' precision(term, data) ## S4 method for signature 'iwp' theta_info(term) ## S4 method for signature 'iwp' random_info(term, data)
term |
An iwp term object |
data |
A data frame containing the term variable |
design(iwp): Creates design matrix for IWP term
precision(iwp): Creates precision matrix for IWP term
theta_info(iwp): Extracts theta parameter information for IWP term
random_info(iwp): Extracts random effects information for IWP term
The following methods are available for 'iwp' objects:
design(term, data)Creates design matrix for IWP term
precision(term, data)Creates precision matrix for IWP term
theta_info(term)Extracts theta parameter information
beta_info(term, data)Extracts beta parameter information
random_info(term, data)Extracts random effects information
Returns for the inner (random-effect) Hessian from the output
of log_lik_laplace. Accepts the flat half_H_inv matrix
when deriv = TRUE, or reconstructs it from hessian$chol_inner.
laplace_half_H_inv(laplace)laplace_half_H_inv(laplace)
laplace |
Output of |
A sparse or dense matrix with nrow = Ngamma.
Creates and manages linear model terms for fixed effects.
linear( x, init = .my_beta_init, lower = .my_beta_lower, upper = .my_beta_upper, parscale = .my_beta_parscale ) ## S4 method for signature 'linear' design(term, data) ## S4 method for signature 'linear' beta_info(term, data)linear( x, init = .my_beta_init, lower = .my_beta_lower, upper = .my_beta_upper, parscale = .my_beta_parscale ) ## S4 method for signature 'linear' design(term, data) ## S4 method for signature 'linear' beta_info(term, data)
x |
Variable name (character) or symbol in a formula (e.g. |
init |
Initial value for beta parameter (default: 0) |
lower |
Lower bound for beta parameter (default: -Inf) |
upper |
Upper bound for beta parameter (default: Inf) |
parscale |
Parameter scale for optimization (default: 1) |
term |
A linear term object |
data |
A data frame containing the term variable |
Linear Model Term
A linear term object
design(linear): Creates design matrix for linear term
beta_info(linear): Extracts beta parameter information for linear term
The following methods are available for 'linear' objects:
design(term, data)Creates design matrix for linear term
precision(term, data)Creates precision matrix for linear term
theta_info(term)Extracts theta parameter information
beta_info(term, data)Extracts beta parameter information
random_info(term, data)Extracts random effects information
# Create a linear term linear_term <- linear(x = "temperature")# Create a linear term linear_term <- linear(x = "temperature")
Evaluates the (profiled) log-likelihood for a hierarchical model by solving an
inner optimization problem for the latent vector gamma (e.g. random
effects) given outer parameters x (typically beta and theta).
The function delegates the inner optimization to inner_opt() from the
selected backend package (by default adlaplace).
log_lik_laplace( x, config = list(), gamma, control = list(report.level = 4, report.freq = 1), ad_fun, data, package = c(config[["package"]], "adlaplace")[1L], deriv = FALSE )log_lik_laplace( x, config = list(), gamma, control = list(report.level = 4, report.freq = 1), ad_fun, data, package = c(config[["package"]], "adlaplace")[1L], deriv = FALSE )
x |
Numeric vector of outer parameters ( |
config |
A list of backend options ( |
gamma |
Optional numeric vector of starting values for the inner
parameter |
control |
List of control parameters passed *as-is* to the backend inner
optimizer (e.g., |
ad_fun |
Optional |
data |
Optional data list used to build |
package |
Character scalar naming the backend package to use for
|
deriv |
Logical scalar. If |
The default adlaplace backend uses a single AD handle. This function
passes that handle to inner_opt(..., ad_fun = ad_fun). Parameter block
sizes are read from ad_fun@sizes; config is not required to
contain beta, gamma, or theta when ad_fun is
supplied.
When deriv=FALSE, the return value is the inner_opt() list
(profile likelihood, nested gradient and hessian, and opt).
When deriv=TRUE, the same list is augmented with grad,
deriv, and extra from the internal profile-derivative helper.
A list. With deriv=FALSE, same as inner_opt. With
deriv=TRUE, additionally:
Gradient of neg_log_lik w.r.t. outer x.
Data frame of profile derivative pieces.
Intermediate objects (dU, trace3, Cholesky factors).
The Laplace approximation assumes the inner Hessian is positive definite
at the optimum. If inner_opt fails to converge or returns a
non-invertible Hessian, log_lik_laplace() issues a warning or error.
Approximates by importance-weighted quadrature over
, using a Gaussian proposal (Laplace
covariance) and correcting with joint_log_dens.
mean_mvquad( parameters, mode, cov, ad_fun, n = 3L, type = "nHN", ndConstruction = "sparse", dec.type = 2L )mean_mvquad( parameters, mode, cov, ad_fun, n = 3L, type = "nHN", ndConstruction = "sparse", dec.type = 2L )
parameters |
Outer |
mode |
Inner mode |
cov |
|
ad_fun |
|
n |
Quadrature level passed to mvQuad |
type |
mvQuad rule (default |
ndConstruction |
mvQuad grid construction (default |
dec.type |
Cholesky decomposition flag for |
Builds a sparse nHN grid with mvQuad, rescales to the Laplace
proposal, then forms
with log-sum-exp stabilization.
Numeric vector of length n_gamma.
log_lik_laplace, inner_opt,
joint_log_dens, rmvnldl
ad_data objectsParses a formula, builds design matrices, and returns formula terms plus
ad_data shards for the observation density, parameter densities, and
each random-effect term.
model_data(formula, data, verbose = FALSE, na_omit = TRUE)model_data(formula, data, verbose = FALSE, na_omit = TRUE)
formula |
Model formula with constructor terms (e.g. |
data |
Data frame containing variables referenced in |
verbose |
Print extra information while parsing terms. |
na_omit |
When |
A list with:
termsNamed list of term objects from collect_terms.
dataOutput of data_setup, including elgm_matrix
when an observation term defines an elgm_matrix method.
observationsNamed list of observation ad_data shards.
parametersNamed list of parameter ad_data shards.
randomNamed list of random-effect ad_data shards.
## Not run: md <- model_data( y ~ x1 + iwp(x2, p = 2, knots = seq(0, 1, len = 11)), data = dat ) ## End(Not run)## Not run: md <- model_data( y ~ x1 + iwp(x2, p = 2, knots = seq(0, 1, len = 11)), data = dat ) ## End(Not run)
The base S4 class that all specific model term classes inherit from.
Subclasses that need hierarchical grouping should include a by slot
(either character or by_group type) and optionally by_levels
and by_labels slots.
termCharacter vector of length 1, the term name
labelCharacter scalar term label reused across metadata builders.
formulaFormula object for the term
knotsNumeric vector of knot locations (for spline terms)
ref_valueNumeric reference value for centering
p.orderInteger polynomial order
initNumeric vector of initial values
lowerNumeric vector of lower bounds
upperNumeric vector of upper bounds
parscaleNumeric vector of parameter scales for optimization
typeFactor indicating term type ("fixed", "random", or "response")
ad_funRegistered AD density name for ad_fun_ptr(), or NA
when the term does not map to a density shard.
ad_kindShard kind passed to ad_fun_ptr() ("observations",
"parameters", "random", or NA).
packagePackage whose .so records AD tapes for this term
(default "adlaplace" for built-in densities).
Generic functions for extracting model matrices and parameter information from model terms.
When non-NULL, model_data emits an extra
ad_kind = "parameters" shard (e.g. FEM log-determinant) alongside the
random shard. Default is NULL (no companion).
design(term, data) precision(term, data) theta_info(term) beta_info(term, data) random_info(term, data) elgm_matrix(term, data) ## S4 method for signature 'model' design(term, data) ## S4 method for signature 'model' precision(term, data) ## S4 method for signature 'model' theta_info(term) ## S4 method for signature 'model' beta_info(term, data) ## S4 method for signature 'model' random_info(term, data) extra_ad_fun(term) ## S4 method for signature 'model' extra_ad_fun(term)design(term, data) precision(term, data) theta_info(term) beta_info(term, data) random_info(term, data) elgm_matrix(term, data) ## S4 method for signature 'model' design(term, data) ## S4 method for signature 'model' precision(term, data) ## S4 method for signature 'model' theta_info(term) ## S4 method for signature 'model' beta_info(term, data) ## S4 method for signature 'model' random_info(term, data) extra_ad_fun(term) ## S4 method for signature 'model' extra_ad_fun(term)
term |
A model term object. |
data |
A data frame containing the variables. |
Method-specific return values.
Character density name, or NULL.
Model term for the observation-level negative binomial log density
registered as nbinom_obs.
Creates a response term wired to the nbinom_obs AD shard.
nbinom( x, init = .my_theta_init, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale ) ## S4 method for signature 'nbinom' theta_info(term)nbinom( x, init = .my_theta_init, lower = .my_theta_lower, upper = .my_theta_upper, parscale = .my_theta_parscale ) ## S4 method for signature 'nbinom' theta_info(term)
x |
Outcome variable name. |
init |
Initial value for the overdispersion parameter (log-SD scale). |
lower |
Lower bound for the overdispersion parameter. |
upper |
Upper bound for the overdispersion parameter. |
parscale |
Parameter scale for optimization. |
term |
A model term object (S4 methods). |
data |
A data frame containing the variables (S4 methods). |
Negative binomial observation model term
A nbinom object.
theta_info(nbinom): Theta info for the overdispersion parameter.
model)ad_funCharacter scalar "nbinom_obs".
ad_kindCharacter scalar "observations".
Convenience wrappers around log_lik_laplace for use with outer optimizers
that expect fn / gr callbacks. Both functions solve (or warm-start)
the inner problem over gamma via log_lik_laplace and update a mutable
cache environment with the latest inner solution.
outer_fn(x, config, cache, ad_fun, control_inner = list(), ...) outer_gr(x, config, cache, ad_fun, control_inner = list(), ...)outer_fn(x, config, cache, ad_fun, control_inner = list(), ...) outer_gr(x, config, cache, ad_fun, control_inner = list(), ...)
x |
Numeric outer parameter vector |
config |
Configuration list passed to |
cache |
An |
ad_fun |
|
control_inner |
A list of control options forwarded to the |
... |
Additional arguments forwarded to |
outer_fn()Returns the scalar objective negative log likelihood.
outer_gr()Returns the gradient.
outer_fn: a numeric scalar neg_log_lik.
outer_gr: gradient of neg_log_lik (same sign as outer_fn).
## Not run: cache <- new.env(parent = emptyenv()) cache$gamma <- rep(0, nrow(data$ATp)) ad_fun <- ad_fun(data, config) val <- outer_fn(x = x0, data = data, config = config, cache = cache, ad_fun = ad_fun) gr <- outer_gr(x = x0, data = data, config = config, cache = cache, ad_fun = ad_fun) ## End(Not run)## Not run: cache <- new.env(parent = emptyenv()) cache$gamma <- rep(0, nrow(data$ATp)) ad_fun <- ad_fun(data, config) val <- outer_fn(x = x0, data = data, config = config, cache = cache, ad_fun = ad_fun) gr <- outer_gr(x = x0, data = data, config = config, cache = cache, ad_fun = ad_fun) ## End(Not run)
Draws samples from where is the
precision matrix, given its LDL factorization (unit lower L1,
diagonal D, and permutation perm).
rmvnldl(n, mean = 0, chol_prec)rmvnldl(n, mean = 0, chol_prec)
n |
Number of samples. |
mean |
Mean vector |
chol_prec |
Either a |
Uses (same as reformat_chol()
in log_lik_deriv), and rnorm only:
, .
An n-by-p matrix; each row is one draw.
Creates and manages random polynomial model terms.
rpoly(x, p = 2, ref_value = 0, sd = Inf) ## S4 method for signature 'rpoly' design(term, data) ## S4 method for signature 'rpoly' precision(term, data) ## S4 method for signature 'rpoly' random_info(term, data)rpoly(x, p = 2, ref_value = 0, sd = Inf) ## S4 method for signature 'rpoly' design(term, data) ## S4 method for signature 'rpoly' precision(term, data) ## S4 method for signature 'rpoly' random_info(term, data)
x |
Variable name. |
p |
Polynomial degree (default: 2). |
ref_value |
Reference value for the polynomial. |
sd |
Standard deviation for random effects. |
term |
A 'rpoly' term object. |
data |
A data frame containing the variables used in the term. |
A 'rpoly' term object.
A design matrix for the random polynomial term.
A precision matrix for the random polynomial term.
A data frame containing random effects information for the random polynomial term.
design(rpoly): Design method for rpoly objects
precision(rpoly): Precision method for rpoly objects
random_info(rpoly): Random info method for rpoly objects
The following methods are available for 'rpoly' objects:
design(term, data)Creates design matrix for rpoly term
precision(term, data)Creates precision matrix for rpoly term
theta_info(term)Extracts theta parameter information
beta_info(term, data)Extracts beta parameter information
random_info(term, data)Extracts random effects information
Draws random effects from the Laplace approximation and evaluates the
linear predictor on x by summing fixed () and random
() contributions from each model term.
sim_fit(x, data, fit, n = 500L)sim_fit(x, data, fit, n = 500L)
x |
Data frame of prediction covariates (same variables as the fitted model).
Only terms whose variables appear in |
data |
Object returned by |
fit |
Result from |
n |
Number of draws for random-effect simulation. |
The combined linear predictor: a nrow(x) by n matrix of
simulated values (fixed-effect contributions are constant across columns).
ad_data
Parameter-block row counts for an ad_data
sizes(x, ...) ## S4 method for signature 'ad_data' sizes(x)sizes(x, ...) ## S4 method for signature 'ad_data' sizes(x)
x |
An |
... |
Unused; for S4 generic compatibility. |
Named list with n_beta, n_gamma, and n_theta.