| rtmb_code | R Documentation |
rtmb_code is the primary interface for defining Bayesian or Frequentist models
within the RTMB framework. It allows you to organize model logic into functional
blocks while utilizing a Stan-like ~ operator for specifying priors and likelihoods.
rtmb_code(...)
... |
Model definition blocks. |
Key Blocks and Logic:
setup: Pre-compilation data processing.
parameters: Declaration of estimated parameters. See parameter_types for available constraints.
transform: Definition of intermediate variables. Use math_functions for stable AD calculations.
model: Likelihood and Priors. Refer to distributions for available sampling statements.
generate: Post-hoc calculation of predictions or diagnostics.
Automatic Differentiation (AD) Note:
All code within parameters, transform, and model is
automatically differentiated by RTMB. To ensure numerical stability, use
provided utility functions like log_sum_exp or inv_logit
instead of raw algebraic implementations.
A list of unevaluated code blocks.
rtmb_model for building the model object.
parameter_types for constraining parameters.
distributions for likelihood functions.
math_functions for numerical utilities.
# Simulate data for a linear regression
set.seed(123)
N <- 100
x <- rnorm(N)
y <- 2.0 + 1.5 * x + rnorm(N, mean = 0, sd = 1)
data_list <- list(N = N, x = x, y = y)
# Define the model using rtmb_code
code <- rtmb_code(
setup = {
# Center the predictor variable (executed once)
x_centered <- x - mean(x)
},
parameters = {
# Define parameters and their constraints
alpha = Dim(1)
beta = Dim(1)
sigma = Dim(1, lower = 0)
},
transform = {
# Calculate the linear predictor
mu <- alpha + beta * x_centered
},
model = {
# Priors
alpha ~ normal(0, 10)
beta ~ normal(0, 10)
sigma ~ exponential(1)
# Likelihood (Vectorized)
y ~ normal(mu, sigma)
},
generate = {
# Calculate generated quantities
y_pred <- mu
# Must return a named list
list(y_pred = y_pred)
}
)
# Create the model object
mod <- rtmb_model(data = data_list, code = code)
# Fit the model using MAP estimation
map_res <- mod$optimize()
map_res$summary(pars = c("alpha", "beta", "sigma"))
# The generated quantity 'y_pred' can also be summarized
map_res$summary("y_pred", max_rows = 5)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.