| RTMB_Model-class | R Documentation |
An R6 class representing a Bayesian model built with RTMB. This class stores model components and provides methods for building the automatic differentiation object, optimizing the posterior, and drawing posterior samples.
dataNamed list containing observation data.
par_listEvaluated list of parameter definitions.
log_probExecutable function for likelihood and prior calculations.
transformFunction for calculating transformed parameters.
generateFunction for calculating generated quantities.
par_namesList of variable names corresponding to parameter dimensions.
pl_fullComplete parameter list with expanded constraints and dimension information used internally.
formulaFormula used for model generation (if created via a wrapper function).
requested_contrastsCharacter; user-requested contrast setting (e.g. "treatment").
contrastsCharacter; internal contrast setting used for fitting (e.g. "sum").
raw_dataData frame; the original data used for the model.
familyCharacter string of the distribution family (if created via a wrapper function).
initList or numeric vector of initial values.
viewCharacter vector of variable names to prioritize in summary.
codeOriginal model AST generated by 'rtmb_code()'.
mapA list specifying parameter mappings for fixing values (e.g., via fixed_model()).
prior_correctionNumeric value for legacy or low-level marginal-likelihood correction. Fixed-parameter prior removal is handled during AD objective construction.
prior_correction_paramsNamed numeric vector linking marginal-likelihood corrections to the free parameters that require them.
fixed_prior_specsInternal specification for removing fixed-parameter prior contributions during AD evaluation.
typeCharacter; the type of the model (e.g. 'lmer', 'glm', 'table', 'ttest', 'corr', 'mediation').
extraList; used to store auxiliary data (like term assignments, factors, test results) needed by methods such as classic().
new()Create a new 'RTMB_Model' object.
RTMB_Model$new( data, par_list, log_prob, transform = NULL, generate = NULL, par_names = NULL, init = NULL, view = NULL, code = NULL, gr_test = FALSE )
dataNamed list containing observation data.
par_listEvaluated list of parameter definitions.
log_probExecutable function for likelihood and prior calculations.
transformFunction for calculating transformed parameters (optional).
generateFunction for calculating generated quantities (optional).
par_namesList of variable names corresponding to parameter dimensions.
initList or numeric vector of initial values.
viewCharacter vector of variable names to prioritize in summary.
codeOriginal model AST generated by 'rtmb_code()'.
gr_testLogical; if TRUE, evaluate the gradient once after the AD tape is built.
prepare_init()Prepare and format initial values for the model parameters.
RTMB_Model$prepare_init(init_arg)
init_argOptional list or numeric vector of initial values. If NULL, defaults to 'self$init' or random generation.
A flat numeric vector of constrained initial values.
get_par_list()Get the current parameters as a named list.
RTMB_Model$get_par_list(init = NULL)
initOptional numeric vector or list of initial values. If NULL, uses the model's current initial values.
A named list of constrained parameters.
get_ad_obj()Get the RTMB automatic differentiation object.
RTMB_Model$get_ad_obj(...)
...Arguments passed to build_ad_obj.
A TMB objective object (ad_obj).
to_unconstrained()Convert a list of constrained parameters to unconstrained space.
RTMB_Model$to_unconstrained(par_list_constrained)
par_list_constrainedA named list of parameters in their natural space.
A named list of parameters in unconstrained space.
to_constrained()Convert a list of unconstrained parameters to constrained (natural) space.
RTMB_Model$to_constrained(par_list_unconstrained)
par_list_unconstrainedA named list of parameters in unconstrained space.
A named list of parameters in constrained space.
unconstrained_vector_to_list()Convert a flat unconstrained vector to a named list.
RTMB_Model$unconstrained_vector_to_list(vec)
vecA numeric vector in unconstrained space.
A named list of unconstrained parameters.
constrained_vector_to_list()Convert a flat constrained vector to a named list.
RTMB_Model$constrained_vector_to_list(vec)
vecA numeric vector in constrained space.
A named list of constrained parameters.
calculate_satterthwaite_df()Calculate Satterthwaite degrees of freedom for parameters.
RTMB_Model$calculate_satterthwaite_df( ad_obj, idx_fix_active = NULL, L_u_total = NULL, opt_par = NULL, max_df = NULL, silent = FALSE, return_sensitivities = FALSE )
ad_objAn RTMB objective object at the optimum.
idx_fix_activeInteger vector; indices of active fixed parameters in the full unconstrained vector.
L_u_totalInteger; total length of the full unconstrained parameter vector.
opt_parOptional numeric vector of optimized parameters.
max_dfNumeric; maximum allowed degrees of freedom. Default is NULL.
silentLogical; whether to suppress informational messages. Default is FALSE.
return_sensitivitiesLogical; if TRUE, returns Hessian sensitivities and V for delta method.
A numeric vector of estimated degrees of freedom (length = L_u_total). Inf for random effects.
calculate_reml_satterthwaite_df()Calculate Satterthwaite degrees of freedom for integrated fixed effects (REML).
RTMB_Model$calculate_reml_satterthwaite_df( ad_obj, opt_par, beta_idx, max_df = NULL, silent = FALSE, return_sensitivities = FALSE )
ad_objAn RTMB objective object.
opt_parNumeric vector of optimized variance components.
beta_idxInteger vector; indices of fixed effects within the random effects vector.
max_dfNumeric; maximum allowed degrees of freedom. Default is NULL.
silentLogical; whether to suppress informational messages. Default is FALSE.
return_sensitivitiesLogical; if TRUE, returns Hessian sensitivities and delta-method components.
...Additional arguments.
A numeric vector of estimated degrees of freedom for the fixed effects.
build_ad_obj()Build the RTMB automatic differentiation object.
RTMB_Model$build_ad_obj( init = NULL, laplace = FALSE, jacobian_target = "none", map = NULL, .marginal_vars = NULL )
initOptional numeric vector or list of initial values for the parameters. Default is NULL.
laplaceLogical; whether to use Laplace approximation to marginalize random effects. Default is FALSE.
jacobian_targetCharacter string specifying which parameters to apply Jacobian adjustments to:
"all": Apply to all parameters (standard for Bayesian MCMC).
"random": Apply only to parameters with random = TRUE (standard for Laplace approximation/REML).
"none": No Jacobian adjustment (standard for Maximum Likelihood estimation).
Default is "none".
mapOptional list specifying parameters to fix. Passed directly to MakeADFun. Default is NULL.
.marginal_varsInternal use for profiling marginalized parameters.
An RTMB objective object (ad_obj).
optimize()Perform Maximum Likelihood or Maximum A Posteriori (MAP) estimation.
RTMB_Model$optimize(
laplace = TRUE,
init = NULL,
num_estimate = 1,
control = list(),
optimizer = "nlminb",
method = "BFGS",
map = NULL,
fixed = NULL,
se_method = c("wald", "sampling", "none"),
num_samples = 1000,
seed = 123,
marginal = "none",
df_method = "auto",
view = NULL,
...
)laplaceLogical; whether to use Laplace approximation for random effects. Default is TRUE.
initOptional initial values for parameters (numeric vector or list).
num_estimateInteger; Number of multi-start optimization runs. Default is 1.
controlA list of control settings passed to the optimizer.
optimizerCharacter; The optimizer to use: "nlminb" (default) or "optim".
methodCharacter; The method for "optim" (e.g., "BFGS", "L-BFGS-B").
mapOptional list specifying parameters to fix (factors).
fixedOptional list specifying parameter values to fix.
se_methodCharacter; method for uncertainty estimation.
"wald": Wald standard errors and Wald confidence intervals.
"sampling": Simulation-based error propagation.
"none": Do not compute standard errors, confidence intervals, or degrees of freedom.
num_samplesInteger; number of samples to draw when se_method is "sampling". Default is 1000.
seedInteger; random seed for sampling.
marginalCharacter vector or "auto" or "none"; specifies which parameters to marginalize out via Laplace approximation.
"none" (default): No additional marginalization.
"auto": Uses variables specified by the model wrapper (e.g., fixed effects in lmer).
"all": Marginalize all parameters (advanced use).
character vector: Specific parameter names to marginalize.
df_methodCharacter or numeric; method for finite degrees-of-freedom approximation. Used only when 'marginal' resolves to one or more parameters and 'se_method != "none"'.
"auto": Uses Satterthwaite approximation when marginalization is active.
"satterthwaite": Satterthwaite approximation.
"inf" or "none": Use infinite degrees of freedom.
numeric: Use the supplied fixed degrees of freedom.
viewCharacter vector of parameter names to prioritize in summary display.
...Additional arguments.
A fitted 'MAP_Fit' object.
classic()Perform frequentist inference (REML/ML) with model-appropriate degrees of freedom.
RTMB_Model$classic(
df_method = "auto",
se_method = c("wald", "sampling"),
num_samples = 1000,
seed = 123,
view = NULL,
map = NULL,
fixed = NULL,
...
)df_methodCharacter; Method for calculating degrees of freedom. Default is "auto".
"auto": Determined based on model type (e.g., Satterthwaite for mixed models).
"residual": Residual degrees of freedom.
"satterthwaite": Satterthwaite approximation (robust for mixed models).
"inf": Use z-distribution (infinite degrees of freedom).
se_methodCharacter; The method for CI estimation: "wald" (default) or "sampling".
num_samplesInteger; number of samples to draw when se_method is "sampling". Default is 1000.
seedInteger; random seed for sampling.
viewCharacter vector of parameters to prioritize in the summary output.
mapOptional list specifying parameters to fix.
fixedOptional list specifying parameter values to fix.
...Additional arguments.
A 'Classic_Fit' object.
sample()Draw posterior samples from the model.
RTMB_Model$sample(
sampling = 1000,
warmup = 1000,
chains = 4,
thin = 1,
seed = sample.int(1e+06, 1),
delta = 0.8,
max_treedepth = 10,
nuts_variant = c("multinomial", "slice"),
metric = c("auto", "diag", "dense", "hybrid"),
metric_init = c("identity", "hessian"),
metric_adaptation = c("stan_window", "cumulative", "window"),
metric_regularization = TRUE,
metric_shrinkage = 5,
metric_min = 1e-06,
metric_max = 1e+06,
parallel = FALSE,
laplace = FALSE,
init = NULL,
init_jitter = 0.1,
save_csv = NULL,
map = NULL,
fixed = NULL,
globals = FALSE,
progress = c("auto", "none", "bar", "message"),
.resume = NULL
)samplingNumber of sampling iterations. Default is 1000.
warmupNumber of warmup iterations. Default is 1000.
chainsNumber of MCMC chains. Default is 4.
thinThinning interval. Default is 1.
seedRandom seed.
deltaTarget acceptance rate for HMC/NUTS. Default is 0.8.
max_treedepthMaximum tree depth for HMC/NUTS. Default is 10.
nuts_variantNUTS proposal selection variant. '"multinomial"' uses Stan-style Hamiltonian-weighted proposal selection; '"slice"' uses the original slice-based implementation. Default is '"multinomial"'.
metricMass matrix adaptation type. '"auto"' starts from the hybrid strategy and falls back to '"diag"' during warmup when the dense covariance block is unstable or has very low correlation; '"diag"' adapts only marginal variances; '"dense"' adapts a full covariance metric for correlated parameters; '"hybrid"' uses a dense metric for fixed parameters and a diagonal metric for random parameters. Default is '"auto"'.
metric_initInitial metric source. '"identity"' starts from the unit metric; '"hessian"' starts from an inverse Hessian approximation at the chain initial value when available. Default is '"identity"'.
metric_adaptationMetric learning mode during warmup. '"stan_window"' uses the current expanding Stan-style slow window; '"cumulative"' uses all slow-window warmup draws accumulated so far; '"window"' uses only the current adaptation window. Default is '"stan_window"'.
metric_regularizationLogical; whether to shrink the adapted metric toward the unit metric during warmup. Default is TRUE.
metric_shrinkageNon-negative scalar controlling the strength of metric shrinkage. Larger values shrink more strongly toward 1. Default is 5.
metric_minMinimum allowed diagonal metric value. Default is 1e-6.
metric_maxMaximum allowed diagonal metric value. Default is 1e6.
parallelLogical; whether to run chains in parallel. Default is FALSE.
laplaceLogical; whether to use Laplace approximation. Default is FALSE.
initOptional initial values for parameters.
init_jittersd of randomize initial values for parameters.
save_csvOptional list for saving MCMC results. e.g., list(name = "model", dir = "BayesRTMB_mcmc").
mapOptional list specifying parameters to fix (factors).
fixedOptional list specifying parameter values to fix.
globalsLogical; if TRUE, let future discover globals
automatically when parallel = TRUE. If FALSE, only the model
object components required by BayesRTMB workers are exported. Default is FALSE.
progressProgress reporting style. '"auto"', '"bar"', and
'"message"' use line-based progress messages; '"none"' suppresses
detailed progress but still prints the high-level start message unless
silent = TRUE was used when creating the model. '"bar"' is
accepted for backward compatibility. Default is '"auto"'.
.resumeInternal saved sampler state used by 'MCMC_Fit$continue_sampling()'; users should leave this as 'NULL'.
A fitted 'MCMC_Fit' object.
variational()Run Automatic Differentiation Variational Inference (ADVI).
RTMB_Model$variational(
iter = 3000,
tol_rel_obj = 0.005,
window_size = 100,
num_samples = 1000,
num_estimate = 4,
alpha = 0.01,
laplace = FALSE,
print_freq = 1000,
method = c("meanfield", "fullrank", "hybrid"),
parallel = FALSE,
seed = sample.int(1e+06, 1),
init = NULL,
save_csv = NULL,
map = NULL,
fixed = NULL,
globals = FALSE,
progress = c("auto", "none", "bar", "message")
)iterInteger; fixed number of iterations for the optimization. Default is 3000.
tol_rel_objNumeric; relative tolerance for the ELBO change to determine convergence. Default is 0.005.
window_sizeInteger; window size for median smoothing in the convergence check. Default is 100.
num_samplesInteger; number of posterior samples to generate from the fitted variational distribution. Default is 1000.
num_estimateInteger; number of times to run the VB estimation (treated as chains). Default is 4.
alphaNumeric; learning rate for the Adam optimizer. Default is 0.01.
laplaceLogical; whether to use Laplace approximation to marginalize random effects. Default is FALSE.
print_freqInteger; iterations interval for progress output. Set to 0 to disable. Default is 1000.
methodCharacter; method of Variational Inference. Default is "meanfield".
parallelLogical; whether to run estimations in parallel. Default is FALSE.
seedInteger; random seed for reproducibility.
initOptional numeric vector or list for initial parameter values. Default is NULL.
save_csvOptional list for saving VB results. e.g., list(name = "model", dir = "BayesRTMB_vb").
mapOptional list specifying parameters to fix (factors).
fixedOptional list specifying parameter values to fix.
globalsLogical; if TRUE, let future discover globals
automatically when parallel = TRUE. If FALSE, only the model
object components required by BayesRTMB workers are exported. Default is FALSE.
progressProgress reporting style. '"auto"' and '"bar"' use
line-based progress messages; '"none"' suppresses detailed progress but
still prints the high-level start message unless silent = TRUE
was used when creating the model. Default is '"auto"'.
A fitted 'VB_Fit' object containing posterior samples and diagnostic information.
print_code()Print model code or model structure.
RTMB_Model$print_code()
The object itself, invisibly.
print_log_prob()Print the internal log-probability function.
RTMB_Model$print_log_prob()
The object itself, invisibly.
print_transform()Print the internal transformation function.
RTMB_Model$print_transform()
The object itself, invisibly.
print_generate()Print the internal generation function.
RTMB_Model$print_generate()
The object itself, invisibly.
get_n_obs()Automatically detect and count the number of independent data points (observations).
RTMB_Model$get_n_obs()
Integer; total number of observations, or NULL if model code is missing.
fixed_model()Create a model with fixed parameters.
RTMB_Model$fixed_model(fixed = list(), silent = FALSE)
fixedA named list of parameter values to fix.
silentLogical; whether to suppress informational messages. Default is FALSE.
A new RTMB_Model object.
clone()The objects of this class are cloneable with this method.
RTMB_Model$clone(deep = FALSE)
deepWhether to make a deep clone.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.