% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/model.R
\name{rtmb_model}
\alias{rtmb_model}
\title{Create an RTMB_Model Object}
\usage{
rtmb_model(
  data,
  code,
  par_names = list(),
  init = NULL,
  view = NULL,
  fixed = NULL,
  silent = FALSE
)
}
\arguments{
\item{data}{A named list containing observation data and constants (e.g., sample size, matrices) used in the model.}

\item{code}{A model definition block generated by \code{rtmb_code(...)} (must include \code{parameters} and \code{model} blocks).}

\item{par_names}{A named list of character vectors corresponding to the dimensions of specific parameters (optional).}

\item{init}{A list or numeric vector of initial values for parameters (optional). If not specified, initialized randomly.}

\item{view}{Character vector of parameter names to be displayed preferentially at the top when outputting results like \code{summary()} (optional).}

\item{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.}

\item{silent}{Logical; if TRUE, suppresses diagnostic messages during model creation. Default is FALSE.}
}
\value{
An \code{RTMB_Model} class instance with a compiled and pre-tested automatic differentiation function.

An \code{RTMB_Model} class instance with a compiled and pre-tested automatic differentiation function.
}
\description{
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.
}
\details{
\strong{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.

\strong{Writing AD-Compatible Code (Important):}
To ensure the model is differentiable, you must follow specific syntax rules
when writing code within \code{rtmb_code}. Avoid discrete branching (\code{if}, \code{ifelse})
based on parameters and use numerically stable functions.
See \code{\link{rtmb_syntax}} for a detailed guide on Automatic Differentiation requirements.

\strong{Initial Values (\code{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 \code{init = NULL}, all parameters are initialized randomly.

\strong{Parameter Labeling (\code{par_names}):}
By default, vector or matrix parameters are displayed with numeric indices (e.g., \code{mu[1]}).
You can pass a named list of character vectors to \code{par_names} to assign meaningful
labels to specific dimensions (e.g., \code{mu[Control]}), vastly improving the readability
of summary outputs and trace plots.

\strong{Available Inference Methods on the Returned Object:}
The returned \code{RTMB_Model} instance provides the following core methods:
\itemize{
  \item \code{$optimize(...)}: Performs Maximum A Posteriori (MAP) or Maximum Likelihood estimation. Returns a \code{MAP_Fit} object.
  \item \code{$sample(...)}: Draws posterior samples using the NUTS (No-U-Turn Sampler) algorithm. Returns an \code{MCMC_Fit} object.
  \item \code{$variational(...)}: Performs Mean-field or Full-rank Automatic Differentiation Variational Inference (ADVI). Returns a \code{VB_Fit} object.
}
}
\examples{
\donttest{
# 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()
}
}
