| rtmb_model | R Documentation |
The 'rtmb_model' function acts as the core constructor for compiling and combining user-defined data with the model code (defined via 'rtmb_code'). It generates an 'RTMB_Model' (R6 class) instance, which serves as the foundation for performing Bayesian inference, including Maximum A Posteriori (MAP) estimation, Variational Inference (ADVI), and Markov Chain Monte Carlo (MCMC) sampling.
rtmb_model(
data,
code,
par_names = list(),
init = NULL,
view = NULL,
fixed = NULL,
silent = FALSE,
gr_test = FALSE
)
data |
A named list, data frame, matrix, or other object containing the
observations used in the model. The original object is available as
|
code |
A model definition block generated by |
par_names |
A named list of character vectors corresponding to the dimensions of specific parameters (optional). |
init |
A list or numeric vector of initial values for parameters (optional). If not specified, initialized randomly. |
view |
Character vector of parameter names to be displayed preferentially at the top when outputting results like |
fixed |
A named list of parameter values to fix (optional). Useful for scoring or plug-in estimation where some parameters (e.g., item parameters) are fixed to known values. |
silent |
Logical; if TRUE, suppresses diagnostic messages during model creation. Default is FALSE. |
gr_test |
Logical; if TRUE, evaluate the gradient once after the AD tape is built.
By default, model creation checks that |
Model Compilation and Pre-checking: When this function is called, it evaluates the provided data and model blocks. It performs a "sandbox execution" (pre-check) using dummy initial values to dynamically detect common structural errors, such as undefined variables, out-of-bounds indices, or incompatible matrix operations, before proceeding to the computationally expensive Automatic Differentiation (MakeADFun) phase. Cryptic backend errors are caught and translated into user-friendly hints.
Inside the setup block, the read-only reserved name .data
refers to the original object supplied to data. This allows setup code
such as Y <- as.matrix(.data) for a matrix or data frame, and
S <- as.matrix(.data$sets) for a named list.
The temporary .data binding is removed after setup has finished.
Writing AD-Compatible Code (Important):
To ensure the model is differentiable, you must follow specific syntax rules
when writing code within rtmb_code. Avoid discrete branching (if, ifelse)
based on parameters and use numerically stable functions.
See rtmb_syntax for a detailed guide on Automatic Differentiation requirements.
Initial Values (init):
Initial parameter values can be specified as a flat numeric vector or a named list.
If a partial list is provided, the unspecified parameters are automatically initialized
with random values drawn from a uniform distribution on the unconstrained scale.
If init = NULL, all parameters are initialized randomly.
Parameter Labeling (par_names):
By default, vector or matrix parameters are displayed with numeric indices (e.g., mu[1]).
You can pass a named list of character vectors to par_names to assign meaningful
labels to specific dimensions (e.g., mu[Control]), vastly improving the readability
of summary outputs and trace plots.
Available Inference Methods on the Returned Object:
The returned RTMB_Model instance provides the following core methods:
$optimize(...): Performs Maximum A Posteriori (MAP) or Maximum Likelihood estimation. Returns a MAP_Fit object.
$sample(...): Draws posterior samples using the NUTS (No-U-Turn Sampler) algorithm. Returns an MCMC_Fit object.
$variational(...): Performs Mean-field or Full-rank Automatic Differentiation Variational Inference (ADVI). Returns a VB_Fit object.
An RTMB_Model class instance with a compiled and pre-tested automatic differentiation function.
An RTMB_Model class instance with a compiled and pre-tested automatic differentiation function.
# Simulate data for 3 groups
set.seed(123)
N <- 60
group_idx <- sample(1:3, N, replace = TRUE)
group_names <- c("Control", "Treatment_A", "Treatment_B")
# True group means: Control = 0, Treatment_A = 2, Treatment_B = -1
true_means <- c(0, 2, -1)
y <- true_means[group_idx] + rnorm(N, mean = 0, sd = 0.5)
data_list <- list(N = N, K = 3, group_idx = group_idx, y = y)
# Define the model using rtmb_code
model_code <- rtmb_code(
parameters = {
mu = Dim(K) # Vector of length K (group means)
sigma = Dim(1, lower = 0) # Scalar (residual standard deviation)
},
model = {
# Priors
for (k in 1:K) mu[k] ~ normal(0, 10)
sigma ~ exponential(1)
# Likelihood
for (i in 1:N) {
y[i] ~ normal(mu[group_idx[i]], sigma)
}
}
)
# --- 1. Basic Model Creation ---
# Create the RTMB_Model object
mod_basic <- rtmb_model(
data = data_list,
code = model_code
)
# Perform Maximum A Posteriori (MAP) estimation
map_basic <- mod_basic$optimize()
# The summary displays default parameter names: mu[1], mu[2], mu[3]
map_basic$summary()
# --- 2. Optional: Adding Custom Parameter Names and initial values ---
# You can optionally use 'par_names' to assign meaningful labels
# to vector or matrix elements for easier interpretation.
mod_named <- rtmb_model(
data = data_list,
code = model_code,
init = list(mu = rep(0, 3), sigma = 1),
par_names = list(mu = group_names)
)
map_named <- mod_named$optimize()
# The summary now displays: mu[Control], mu[Treatment_A], mu[Treatment_B]
map_named$summary()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.