Skip to contents

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

data

Named list containing observation data.

par_list

Evaluated list of parameter definitions.

log_prob

Executable function for likelihood and prior calculations.

transform

Function for calculating transformed parameters.

generate

Function for calculating generated quantities.

par_names

List of variable names corresponding to parameter dimensions.

pl_full

Complete parameter list with expanded constraints and dimension information used internally.

formula

Formula used for model generation (if created via a wrapper function).

requested_contrasts

Character; user-requested contrast setting (e.g. "treatment").

contrasts

Character; internal contrast setting used for fitting (e.g. "sum").

raw_data

Data frame; the original data used for the model.

family

Character string of the distribution family (if created via a wrapper function).

init

List or numeric vector of initial values.

view

Character vector of variable names to prioritize in summary.

code

Original model AST generated by `rtmb_code()`.

map

A list specifying parameter mappings for fixing values (e.g., via fixed_model()).

prior_correction

Numeric value for legacy or low-level marginal-likelihood correction. Fixed-parameter prior removal is handled during AD objective construction.

fixed_prior_specs

Internal specification for removing fixed-parameter prior contributions during AD evaluation.

type

Character; the type of the model (e.g. 'lmer', 'glm', 'table', 'ttest', 'corr', 'mediation').

extra

List; 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

data

Named list containing observation data.

par_list

Evaluated list of parameter definitions.

log_prob

Executable function for likelihood and prior calculations.

transform

Function for calculating transformed parameters (optional).

generate

Function for calculating generated quantities (optional).

par_names

List of variable names corresponding to parameter dimensions.

init

List or numeric vector of initial values.

view

Character vector of variable names to prioritize in summary.

code

Original model AST generated by `rtmb_code()`.


Method prepare_init()

Prepare and format initial values for the model parameters.

Usage

RTMB_Model$prepare_init(init_arg)

Arguments

init_arg

Optional list or numeric vector of initial values. If NULL, defaults to `self$init` or random generation.

Returns

A flat numeric vector of constrained initial values.


Method get_par_list()

Get the current parameters as a named list.

Usage

RTMB_Model$get_par_list(init = NULL)

Arguments

init

Optional numeric vector or list of initial values. If NULL, uses the model's current initial values.

Returns

A named list of constrained parameters.


Method get_ad_obj()

Get the RTMB automatic differentiation object.

Usage

RTMB_Model$get_ad_obj(...)

Arguments

...

Arguments passed to build_ad_obj.

Returns

A TMB objective object (ad_obj).


Method to_unconstrained()

Convert a list of constrained parameters to unconstrained space.

Usage

RTMB_Model$to_unconstrained(par_list_constrained)

Arguments

par_list_constrained

A named list of parameters in their natural space.

Returns

A named list of parameters in unconstrained space.


Method to_constrained()

Convert a list of unconstrained parameters to constrained (natural) space.

Usage

RTMB_Model$to_constrained(par_list_unconstrained)

Arguments

par_list_unconstrained

A named list of parameters in unconstrained space.

Returns

A named list of parameters in constrained space.


Method unconstrained_vector_to_list()

Convert a flat unconstrained vector to a named list.

Usage

RTMB_Model$unconstrained_vector_to_list(vec)

Arguments

vec

A numeric vector in unconstrained space.

Returns

A named list of unconstrained parameters.


Method constrained_vector_to_list()

Convert a flat constrained vector to a named list.

Usage

RTMB_Model$constrained_vector_to_list(vec)

Arguments

vec

A numeric vector in constrained space.

Returns

A named list of constrained parameters.


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_obj

An RTMB objective object at the optimum.

idx_fix_active

Integer vector; indices of active fixed parameters in the full unconstrained vector.

L_u_total

Integer; total length of the full unconstrained parameter vector.

opt_par

Optional numeric vector of optimized parameters.

max_df

Numeric; maximum allowed degrees of freedom. Default is NULL.

silent

Logical; whether to suppress informational messages. Default is FALSE.

return_sensitivities

Logical; if TRUE, returns Hessian sensitivities and V for delta method.

Returns

A numeric vector of estimated degrees of freedom (length = L_u_total). Inf for random effects.


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_obj

An RTMB objective object.

opt_par

Numeric vector of optimized variance components.

beta_idx

Integer vector; indices of fixed effects within the random effects vector.

max_df

Numeric; maximum allowed degrees of freedom. Default is NULL.

silent

Logical; whether to suppress informational messages. Default is FALSE.

return_sensitivities

Logical; if TRUE, returns Hessian sensitivities and delta-method components.

...

Additional arguments.

Returns

A numeric vector of estimated degrees of freedom for the fixed effects.


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

init

Optional numeric vector or list of initial values for the parameters. Default is NULL.

laplace

Logical; whether to use Laplace approximation to marginalize random effects. Default is FALSE.

jacobian_target

Character 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".

map

Optional list specifying parameters to fix. Passed directly to MakeADFun. Default is NULL.

.marginal_vars

Internal use for profiling marginalized parameters.

Returns

An RTMB objective object (ad_obj).


Method optimize()

Perform Maximum Likelihood or Maximum A Posteriori (MAP) estimation.

Usage

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,
  ...
)

Arguments

laplace

Logical; whether to use Laplace approximation for random effects. Default is TRUE.

init

Optional initial values for parameters (numeric vector or list).

num_estimate

Integer; Number of multi-start optimization runs. Default is 1.

control

A list of control settings passed to the optimizer.

optimizer

Character; The optimizer to use: "nlminb" (default) or "optim".

method

Character; The method for "optim" (e.g., "BFGS", "L-BFGS-B").

map

Optional list specifying parameters to fix (factors).

fixed

Optional list specifying parameter values to fix.

se_method

Character; 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_samples

Integer; number of samples to draw when se_method is "sampling". Default is 1000.

seed

Integer; random seed for sampling.

marginal

Character 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_method

Character 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.

view

Character vector of parameter names to prioritize in summary display.

...

Additional arguments.

Returns

A fitted `MAP_Fit` object.


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_method

Character; 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_method

Character; The method for CI estimation: "wald" (default) or "sampling".

num_samples

Integer; number of samples to draw when se_method is "sampling". Default is 1000.

seed

Integer; random seed for sampling.

view

Character vector of parameters to prioritize in the summary output.

map

Optional list specifying parameters to fix.

fixed

Optional list specifying parameter values to fix.

...

Additional arguments.

Returns

A `Classic_Fit` object.


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

sampling

Number of sampling iterations. Default is 1000.

warmup

Number of warmup iterations. Default is 1000.

chains

Number of MCMC chains. Default is 4.

thin

Thinning interval. Default is 1.

seed

Random seed.

delta

Target acceptance rate for HMC/NUTS. Default is 0.8.

max_treedepth

Maximum tree depth for HMC/NUTS. Default is 10.

parallel

Logical; whether to run chains in parallel. Default is FALSE.

laplace

Logical; whether to use Laplace approximation. Default is FALSE.

init

Optional initial values for parameters.

init_jitter

sd of randomize initial values for parameters.

save_csv

Optional list for saving MCMC results. e.g., list(name = "model", dir = "BayesRTMB_mcmc").

map

Optional list specifying parameters to fix (factors).

fixed

Optional list specifying parameter values to fix.

Returns

A fitted `MCMC_Fit` object.


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

iter

Integer; fixed number of iterations for the optimization. Default is 3000.

tol_rel_obj

Numeric; relative tolerance for the ELBO change to determine convergence. Default is 0.005.

window_size

Integer; window size for median smoothing in the convergence check. Default is 100.

num_samples

Integer; number of posterior samples to generate from the fitted variational distribution. Default is 1000.

num_estimate

Integer; number of times to run the VB estimation (treated as chains). Default is 4.

alpha

Numeric; learning rate for the Adam optimizer. Default is 0.01.

laplace

Logical; whether to use Laplace approximation to marginalize random effects. Default is FALSE.

print_freq

Integer; iterations interval for progress output. Set to 0 to disable. Default is 1000.

method

Character; method of Variational Inference. Default is "meanfield".

parallel

Logical; whether to run estimations in parallel. Default is FALSE.

seed

Integer; random seed for reproducibility.

init

Optional numeric vector or list for initial parameter values. Default is NULL.

save_csv

Optional list for saving VB results. e.g., list(name = "model", dir = "BayesRTMB_vb").

map

Optional list specifying parameters to fix (factors).

fixed

Optional list specifying parameter values to fix.

Returns

A fitted `VB_Fit` object containing posterior samples and diagnostic information.


Method print_code()

Print model code or model structure.

Usage

RTMB_Model$print_code()

Returns

The object itself, invisibly.


Method print_log_prob()

Print the internal log-probability function.

Usage

RTMB_Model$print_log_prob()

Returns

The object itself, invisibly.


Method print_transform()

Print the internal transformation function.

Usage

RTMB_Model$print_transform()

Returns

The object itself, invisibly.


Method print_generate()

Print the internal generation function.

Usage

RTMB_Model$print_generate()

Returns

The object itself, invisibly.


Method get_n_obs()

Automatically detect and count the number of independent data points (observations).

Usage

RTMB_Model$get_n_obs()

Returns

Integer; total number of observations, or NULL if model code is missing.


Method fixed_model()

Create a model with fixed parameters.

Usage

RTMB_Model$fixed_model(fixed = list(), silent = FALSE)

Arguments

fixed

A named list of parameter values to fix.

silent

Logical; whether to suppress informational messages. Default is FALSE.

Returns

A new RTMB_Model object.


Method clone()

The objects of this class are cloneable with this method.

Usage

RTMB_Model$clone(deep = FALSE)

Arguments

deep

Whether to make a deep clone.