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.
Public fields
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.
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().
Methods
Method new()
Create a new `RTMB_Model` object.
Usage
RTMB_Model$new(
data,
par_list,
log_prob,
transform = NULL,
generate = NULL,
par_names = NULL,
init = NULL,
view = NULL,
code = NULL
)Arguments
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()`.
Method prepare_init()
Prepare and format initial values for the model parameters.
Method get_par_list()
Get the current parameters as a named list.
Method calculate_satterthwaite_df()
Calculate Satterthwaite degrees of freedom for parameters.
Usage
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
)Arguments
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.
Method calculate_reml_satterthwaite_df()
Calculate Satterthwaite degrees of freedom for integrated fixed effects (REML).
Usage
RTMB_Model$calculate_reml_satterthwaite_df(
ad_obj,
opt_par,
beta_idx,
max_df = NULL,
silent = FALSE,
return_sensitivities = FALSE
)Arguments
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.
Method build_ad_obj()
Build the RTMB automatic differentiation object.
Usage
RTMB_Model$build_ad_obj(
init = NULL,
laplace = FALSE,
jacobian_target = "none",
map = NULL,
.marginal_vars = NULL
)Arguments
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 withrandom = 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.
Method optimize()
Perform Maximum Likelihood or Maximum A Posteriori (MAP) estimation.
Arguments
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.
Method classic()
Perform frequentist inference (REML/ML) with model-appropriate degrees of freedom.
Usage
RTMB_Model$classic(
df_method = "auto",
se_method = c("wald", "sampling"),
num_samples = 1000,
seed = 123,
view = NULL,
map = NULL,
fixed = NULL,
...
)Arguments
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.
Method sample()
Draw posterior samples from the model.
Usage
RTMB_Model$sample(
sampling = 1000,
warmup = 1000,
chains = 4,
thin = 1,
seed = sample.int(1e+06, 1),
delta = 0.8,
max_treedepth = 10,
parallel = FALSE,
laplace = FALSE,
init = NULL,
init_jitter = 0.1,
save_csv = NULL,
map = NULL,
fixed = NULL
)Arguments
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.
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.
Method variational()
Run Automatic Differentiation Variational Inference (ADVI).
Usage
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
)Arguments
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.
Method get_n_obs()
Automatically detect and count the number of independent data points (observations).
Method fixed_model()
Create a model with fixed parameters.
Usage
RTMB_Model$fixed_model(fixed = list(), silent = FALSE)