tests/testthat/test-wrappers.R

test_that("Wrappers optimize correctly", {
  
  # rtmb_lm
  fit_lm <- rtmb_lm(mpg ~ wt, data = mtcars)
  res_lm <- fit_lm$optimize()
  expect_true(inherits(res_lm, "map_fit"))
  expect_true(all(c("status", "selected") %in% names(res_lm$opt_history)))
  expect_true(any(res_lm$opt_history$selected))
  expect_true(all(res_lm$opt_history$status %in% c("converged", "not converged") | grepl("convergence", res_lm$opt_history$status)))
  
  # rtmb_ttest
  fit_t <- rtmb_ttest(mpg ~ am, data = mtcars)
  res_t <- fit_t$optimize()
  expect_true(inherits(res_t, "map_fit"))

  # rtmb_corr
  fit_c <- rtmb_corr(mtcars[, c("mpg", "wt")])
  res_c <- fit_c$optimize()
  expect_true(inherits(res_c, "map_fit"))
  
  # rtmb_fa
  # Added a simple fallback to handle mtcars subset
  fit_f <- rtmb_fa(scale(mtcars[, c("mpg", "disp", "hp")]), nfactors = 1)
  res_f <- fit_f$optimize()
  expect_true(inherits(res_f, "map_fit"))
})

test_that("print_code hides wrapper setup environment", {
  mdl <- rtmb_lm(mpg ~ wt, data = mtcars)
  out <- capture.output(mdl$print_code())

  expect_true(any(grepl("^  setup = \\{", out)))
  expect_true(any(grepl("mf <- model.frame\\(mpg ~ wt, na.action = na.omit\\)", out)))
  expect_true(any(grepl("Y <- model.response\\(mf\\)", out)))
  expect_true(any(grepl("model.matrix\\(mpg ~ wt, mf\\)\\[, -1, drop = FALSE\\]", out)))
  expect_true(any(grepl("N <- nrow\\(mf\\)", out)))
  expect_true(any(grepl("sigma <- Dim\\(1, lower = 0\\)", out)))
  expect_false(any(grepl("setup_env", out, fixed = TRUE)))
  expect_false(any(grepl("^  list\\(", out)))
  expect_false(any(grepl("model.frame(formula, df", out, fixed = TRUE)))
  expect_false(any(grepl("X_full", out, fixed = TRUE)))
})

test_that("regression wrapper code can be rebuilt from the original data frame", {
  dat <- data.frame(
    y = c(1.1, 1.4, NA, 2.2, 2.7, 3.0),
    x = c(0, 1, 0, 1, 2, 3),
    condition = factor(c("a", "a", "b", "b", "a", "b")),
    group = factor(c("g1", "g1", "g2", "g2", "g3", "g3"))
  )

  lm_model <- rtmb_lm(y ~ x * condition, data = dat)
  lm_rebuilt <- rtmb_model(data = dat, code = lm_model$code, init = lm_model$init)
  expect_equal(lm_rebuilt$data$Y, lm_model$data$Y)
  expect_equal(lm_rebuilt$data$X, lm_model$data$X)

  glmer_model <- rtmb_glmer(y ~ x + (1 | group), data = dat)
  glmer_rebuilt <- rtmb_model(
    data = dat,
    code = glmer_model$code,
    init = glmer_model$init
  )
  expect_equal(glmer_rebuilt$data$Y, glmer_model$data$Y)
  expect_equal(glmer_rebuilt$data$X, glmer_model$data$X)
  expect_equal(glmer_rebuilt$data$Z_mat, glmer_model$data$Z_mat)

  glmer_code <- capture.output(glmer_model$print_code())
  expect_true(any(grepl(
    "make_glmer_re_terms\\(formula = y ~ x \\+ \\(1 \\| group\\)",
    glmer_code
  )))
  expect_false(any(grepl("data = df", glmer_code, fixed = TRUE)))
  expect_false(any(grepl("formula = formula", glmer_code, fixed = TRUE)))
})

test_that("formula wrapper code can be rebuilt from the original data frame", {
  dat <- data.frame(
    y = c(-1.4, -1.0, -0.5, -0.1, 0.4, 0.9, 1.3, 1.8),
    y2 = c(-0.8, -0.4, -0.2, 0.3, 0.7, 1.0, 1.5, 2.0),
    m = c(-0.9, -0.6, -0.2, 0.1, 0.5, 0.8, 1.1, 1.5),
    x = seq(-1.5, 2, length.out = 8)
  )

  mixture_model <- rtmb_mixture(y ~ x, k = 2, data = dat)
  mixture_code <- mixture_model$code
  mixture_code$setup_env <- NULL
  mixture_rebuilt <- rtmb_model(
    data = dat,
    code = mixture_code,
    init = mixture_model$init,
    silent = TRUE
  )

  expect_equal(mixture_rebuilt$data$Y, mixture_model$data$Y)
  expect_equal(mixture_rebuilt$data$X_prob, mixture_model$data$X_prob)
  expect_equal(mixture_rebuilt$data$K, 2)
  mixture_print <- capture.output(mixture_model$print_code())
  expect_true(any(grepl("model.frame(y ~ x, data = .data)", mixture_print, fixed = TRUE)))
  expect_true(any(grepl("K <- 2", mixture_print, fixed = TRUE)))

  lrt_model <- rtmb_lrt(y ~ x, k = 2, data = dat)
  lrt_code <- lrt_model$code
  lrt_code$setup_env <- NULL
  lrt_rebuilt <- rtmb_model(
    data = dat,
    code = lrt_code,
    init = lrt_model$init,
    silent = TRUE
  )

  expect_equal(lrt_rebuilt$data$Y, lrt_model$data$Y)
  expect_equal(lrt_rebuilt$data$X_prob, lrt_model$data$X_prob)
  expect_equal(lrt_rebuilt$data$rank_coords, 1:2)
  lrt_print <- capture.output(lrt_model$print_code())
  expect_true(any(grepl("model.frame(y ~ x, data = .data)", lrt_print, fixed = TRUE)))
  expect_true(any(grepl("rank_coords <- 1:2", lrt_print, fixed = TRUE)))

  mediation_model <- rtmb_mediation(
    list(m ~ x, y ~ x + m),
    data = dat
  )
  mediation_code <- mediation_model$code
  mediation_code$setup_env <- NULL
  mediation_rebuilt <- rtmb_model(
    data = dat,
    code = mediation_code,
    init = mediation_model$init,
    silent = TRUE
  )

  expect_equal(mediation_rebuilt$data$Y_1, mediation_model$data$Y_1)
  expect_equal(mediation_rebuilt$data$X_2, mediation_model$data$X_2)
  mediation_print <- capture.output(mediation_model$print_code())
  expect_true(any(grepl("model.frame(m ~ x, df)", mediation_print, fixed = TRUE)))
  expect_true(any(grepl("model.frame(y ~ x + m, df)", mediation_print, fixed = TRUE)))
})

test_that("FA and IRT wrapper code can be rebuilt from the original data", {
  set.seed(12)
  fa_dat <- data.frame(
    item1 = rnorm(12),
    item2 = rnorm(12),
    item3 = rnorm(12)
  )
  fa_dat$item2[4] <- NA_real_

  fa_model <- rtmb_fa(fa_dat, nfactors = 1)
  fa_code <- fa_model$code
  fa_code$setup_env <- NULL
  fa_rebuilt <- rtmb_model(
    data = fa_dat,
    code = fa_code,
    init = fa_model$init,
    silent = TRUE
  )

  expect_equal(fa_rebuilt$data$Y, fa_model$data$Y)
  expect_equal(fa_rebuilt$data$K, 1)
  fa_print <- capture.output(fa_model$print_code())
  expect_true(any(grepl("Y <- as.matrix\\(\\.data\\)", fa_print)))
  expect_true(any(grepl("K <- 1", fa_print, fixed = TRUE)))
  expect_false(any(grepl("nfactors <-", fa_print, fixed = TRUE)))

  irt_dat <- matrix(
    c(
      0, 1, 0,
      1, 1, 0,
      0, 0, 1,
      1, 0, 1
    ),
    nrow = 4,
    byrow = TRUE,
    dimnames = list(NULL, paste0("item", 1:3))
  )
  irt_model <- rtmb_irt(irt_dat, model = "1PL")
  irt_code <- irt_model$code
  irt_code$setup_env <- NULL
  irt_rebuilt <- rtmb_model(
    data = irt_dat,
    code = irt_code,
    init = irt_model$init,
    silent = TRUE
  )

  expect_equal(irt_rebuilt$data$Y, irt_model$data$Y)
  expect_equal(irt_rebuilt$data$Y_obs, irt_model$data$Y_obs)
  irt_print <- capture.output(irt_model$print_code())
  expect_true(any(grepl("Y <- as.matrix\\(\\.data\\)", irt_print)))
})

test_that("wrapper inputs supplied separately can be rebuilt from one data object", {
  sets <- matrix(
    c(
      1, 2, 3,
      2, 3, 4
    ),
    nrow = 2,
    byrow = TRUE
  )
  best <- matrix(
    c(
      1, 2,
      2, 3,
      3, 1
    ),
    nrow = 3,
    byrow = TRUE
  )
  mdu_model <- rtmb_mdu(
    data = list(Best = best),
    sets = sets,
    ndim = 1,
    method = "Best",
    prior = prior_normal()
  )
  mdu_code <- mdu_model$code
  mdu_code$setup_env <- NULL
  mdu_rebuilt <- rtmb_model(
    data = list(Best = best, sets = sets),
    code = mdu_code,
    init = mdu_model$init,
    silent = TRUE
  )

  expect_equal(mdu_rebuilt$data$S, mdu_model$data$S)
  expect_equal(mdu_rebuilt$data$Y_best, mdu_model$data$Y_best)
  mdu_print <- capture.output(mdu_model$print_code())
  expect_true(any(grepl("Y_best <- as.matrix(.data$Best)", mdu_print, fixed = TRUE)))
  expect_true(any(grepl("S <- as.matrix(.data$sets)", mdu_print, fixed = TRUE)))

  worst <- matrix(
    c(
      2, 3,
      3, 1,
      1, 2
    ),
    nrow = 3,
    byrow = TRUE
  )
  bw_model <- rtmb_mdu(
    data = list(Best = best, Worst = worst),
    sets = sets,
    ndim = 1,
    method = "Best-Worst"
  )
  bw_code <- bw_model$code
  bw_code$setup_env <- NULL
  bw_rebuilt <- rtmb_model(
    data = list(Best = best, Worst = worst, sets = sets),
    code = bw_code,
    init = bw_model$init,
    silent = TRUE
  )
  expect_equal(bw_rebuilt$data$Y_dif, bw_model$data$Y_dif)

  corr_dat <- data.frame(
    y1 = c(1.0, 1.3, 2.1, 2.4, 3.2, 3.6),
    y2 = c(0.8, 1.0, 1.9, 2.2, 3.0, 3.5),
    x = c(-1, NA, 0, 0.5, 1, 1.5),
    id = factor(rep(letters[1:3], each = 2))
  )
  corr_model <- rtmb_corr(
    cbind(y1, y2),
    data = corr_dat,
    covariates = "x",
    ID = id
  )
  corr_code <- corr_model$code
  corr_code$setup_env <- NULL
  corr_rebuilt <- rtmb_model(
    data = list(
      Y = as.matrix(corr_dat[c("y1", "y2")]),
      covariates = as.matrix(corr_dat["x"]),
      ID = corr_dat$id
    ),
    code = corr_code,
    init = corr_model$init,
    silent = TRUE
  )

  expect_equal(corr_rebuilt$data$Y, corr_model$data$Y)
  expect_equal(corr_rebuilt$data$group_id, corr_model$data$group_id)
  corr_print <- capture.output(corr_model$print_code())
  expect_true(any(grepl("Y <- as.matrix(.data$Y)", corr_print, fixed = TRUE)))
  expect_true(any(grepl("covariates <- as.matrix(.data$covariates)", corr_print, fixed = TRUE)))
  expect_true(any(grepl("ID <- .data$ID", corr_print, fixed = TRUE)))

  x <- c(1.1, NA, 1.8, 2.2, 2.5)
  y <- c(0.4, 0.8, 1.0, NA, 1.6)
  ttest_model <- rtmb_ttest(x, y)
  ttest_code <- ttest_model$code
  ttest_code$setup_env <- NULL
  ttest_rebuilt <- rtmb_model(
    data = list(x = x, y = y),
    code = ttest_code,
    init = ttest_model$init,
    silent = TRUE
  )

  expect_equal(ttest_rebuilt$data$Y1, ttest_model$data$Y1)
  expect_equal(ttest_rebuilt$data$Y2, ttest_model$data$Y2)
  ttest_print <- capture.output(ttest_model$print_code())
  expect_true(any(grepl("Y1 <- as.numeric(.data$x)", ttest_print, fixed = TRUE)))
  expect_true(any(grepl("Y2 <- as.numeric(.data$y)", ttest_print, fixed = TRUE)))

  paired_dat <- data.frame(
    value = c(1.0, 1.4, 1.8, 1.3, 1.9, 2.2),
    condition = factor(rep(c("pre", "post"), each = 3)),
    id = rep(1:3, 2)
  )
  paired_model <- rtmb_ttest(
    value ~ condition,
    data = paired_dat,
    paired = TRUE,
    ID = "id"
  )
  paired_code <- paired_model$code
  paired_code$setup_env <- NULL
  paired_rebuilt <- rtmb_model(
    data = list(
      response = paired_dat$value,
      group = as.integer(paired_dat$condition),
      ID = paired_dat$id
    ),
    code = paired_code,
    init = paired_model$init,
    silent = TRUE
  )
  expect_equal(paired_rebuilt$data$diffs, paired_model$data$diffs)

  table_x <- factor(c("a", "a", "b", "b", "b", "a"))
  table_y <- factor(c("c", "d", "c", "d", "d", "c"))
  table_model <- rtmb_table(table_x, table_y)
  table_code <- table_model$code
  table_code$setup_env <- NULL
  table_rebuilt <- rtmb_model(
    data = list(x = table_x, y = table_y),
    code = table_code,
    init = table_model$init,
    silent = TRUE
  )

  expect_equal(table_rebuilt$data$Y, table_model$data$Y)
  table_print <- capture.output(table_model$print_code())
  expect_true(any(grepl("tab <- table(.data$x, .data$y)", table_print, fixed = TRUE)))

  table_dat <- data.frame(first = table_x, second = table_y)
  table_data_model <- rtmb_table(first, second, data = table_dat)
  expect_equal(table_data_model$data$Y, as.vector(table(table_x, table_y)))

  table_matrix <- matrix(c(4, 2, 1, 5), nrow = 2)
  matrix_table_model <- rtmb_table(table_matrix)
  matrix_table_code <- matrix_table_model$code
  matrix_table_code$setup_env <- NULL
  matrix_table_rebuilt <- rtmb_model(
    data = table_matrix,
    code = matrix_table_code,
    init = matrix_table_model$init,
    silent = TRUE
  )
  expect_equal(matrix_table_rebuilt$data$Y, matrix_table_model$data$Y)
})

test_that("regression wrappers add design-matrix standardized coefficients", {
  dat <- data.frame(
    y = c(1.1, 1.4, 1.8, 2.2, 2.7, 3.0),
    y_bin = c(0, 0, 1, 1, 1, 0),
    x = c(0, 1, 0, 1, 2, 3),
    condition = factor(c("a", "a", "b", "b", "a", "b")),
    group = factor(c("g1", "g1", "g2", "g2", "g3", "g3"))
  )

  mdl <- rtmb_glmer(
    y ~ x * condition + (1 | group),
    data = dat,
    std = TRUE
  )
  out <- capture.output(mdl$print_code())

  expect_true(any(grepl("# Standardized coefficients", out, fixed = TRUE)))
  expect_true(any(grepl(
    "X_sd <- apply(X, 2, sd, na.rm = TRUE)",
    out,
    fixed = TRUE
  )))
  expect_true(any(grepl("Y_sd <- sd(Y, na.rm = TRUE)", out, fixed = TRUE)))
  expect_true(any(grepl("b_std <- b * X_sd/Y_sd", out, fixed = TRUE)))
  expect_equal(mdl$data$X_sd, apply(mdl$data$X, 2, sd, na.rm = TRUE))
  expect_equal(length(mdl$data$X_sd), ncol(mdl$data$X))
  expect_equal(mdl$par_names$b_std, colnames(mdl$data$X))
  expect_true(mdl$extra$std)

  glm_mdl <- rtmb_glm(
    y_bin ~ x * condition,
    data = dat,
    family = "bernoulli",
    std = TRUE
  )
  glm_out <- capture.output(glm_mdl$print_code())
  expect_true(any(grepl("b_std <- b * X_sd", glm_out, fixed = TRUE)))
  expect_false(any(grepl("Y_sd <-", glm_out, fixed = TRUE)))

  weak_mdl <- rtmb_lm(
    y ~ x,
    data = dat,
    prior = prior_weak(),
    y_range = c(0, 4),
    std = TRUE
  )
  weak_out <- capture.output(weak_mdl$print_code())
  expect_equal(sum(grepl("X_sd <- apply", weak_out, fixed = TRUE)), 1L)

  expect_error(rtmb_lm(y ~ x, data = dat, std = 1), "TRUE or FALSE")
})

test_that("mixture WAIC generated quantities use report syntax", {
  dat <- data.frame(
    y1 = c(-1.0, -0.7, 0.2, 1.1, 1.4, 2.0),
    y2 = c(0.1, -0.2, 0.4, 1.3, 1.7, 2.2)
  )
  mdl <- rtmb_mixture(
    cbind(y1, y2) ~ 1,
    k = 2,
    data = dat,
    covariance = "full_equal_corr",
    WAIC = TRUE
  )
  out <- capture.output(mdl$print_code())

  expect_true(any(grepl("lp <- rtmb_vector\\(0, 1\\)", out)))
  expect_false(any(grepl("lp <- mu\\[1\\] \\* 0", out)))
  expect_true(any(grepl("log_dens_mat <- rtmb_array\\(0, dim = c\\(N, K\\)\\)", out)))
  expect_true(any(grepl("log_dens_mat <- matrix\\(0, N, K\\)", out)))
  expect_true(any(grepl("report\\(prob_mean, corr, log_lik\\)", out)))
  expect_false(any(grepl("log_dens_mat <- matrix\\(mu\\[1\\] \\* 0, N, K\\)", out)))
  expect_false(any(grepl("return\\(list\\(prob_mean", out)))

  diag_mdl <- rtmb_mixture(
    cbind(y1, y2) ~ 1,
    k = 2,
    data = dat,
    covariance = "diagonal"
  )
  diag_code <- capture.output(diag_mdl$print_code())
  expect_true(any(grepl("ld <- rtmb_vector\\(0, N\\)", diag_code)))
  expect_false(any(grepl("ld <- Y\\[1\\] \\* 0", diag_code)))
})

test_that("FA generated quantities use report syntax", {
  mdl <- rtmb_fa(
    scale(mtcars[1:12, c("mpg", "disp", "hp")]),
    nfactors = 1,
    score = TRUE,
    WAIC = TRUE
  )
  out <- capture.output(mdl$print_code())

  expect_true(any(grepl("report\\(communality, log_lik, score\\)", out)))
  expect_false(any(grepl("out\\$|return\\(out\\)", out)))
})

test_that("FA with rotation and scores builds AD tape", {
  skip_on_cran()

  mdl <- rtmb_fa(
    scale(mtcars[1:16, c("mpg", "disp", "hp", "wt")]),
    nfactors = 2,
    rotate = "promax",
    score = TRUE
  )

  expect_s3_class(mdl, "RTMB_Model")
})

test_that("FA lower-triangular summaries avoid structural-zero reads", {
  skip_on_cran()

  mdl <- rtmb_fa(
    scale(mtcars[1:16, c("mpg", "disp", "hp", "wt")]),
    nfactors = 2,
    score = TRUE
  )
  out <- capture.output(mdl$print_code())

  expect_true(any(grepl("for \\(k in 1:min\\(j, K\\)\\)", out)))
  expect_false(any(grepl("rowSums\\(L_raw", out)))
  expect_false(any(grepl("L_raw\\^2", out)))
})

test_that("wrapper WAIC loops use AD-compatible vectors", {
  Y <- matrix(c(
    0, 1, 1,
    1, 0, 1,
    0, 1, 0,
    1, 1, 0
  ), nrow = 4, byrow = TRUE)
  mdl <- rtmb_irt(Y, model = "1PL", WAIC = TRUE)
  out <- capture.output(mdl$print_code())

  expect_true(any(grepl("log_lik <- rtmb_vector\\(0, N_obs\\)", out)))
  expect_false(any(grepl("log_lik <- numeric\\(N_obs\\)", out)))
})

test_that("IRT normal prior supplies the default discrimination prior", {
  Y <- matrix(
    c(
      0, 1, 1,
      1, 0, 1,
      0, 1, 0,
      1, 1, 0
    ),
    nrow = 4,
    byrow = TRUE
  )

  default_code <- capture.output(
    rtmb_irt(Y, model = "2PL", prior = prior_normal())$print_code()
  )
  expect_true(any(grepl("a ~ exponential\\(0.5\\)", default_code)))

  custom_code <- capture.output(
    rtmb_irt(
      Y,
      model = "2PL",
      prior = prior_normal(a_rate = 0.5)
    )$print_code()
  )
  expect_true(any(grepl("a ~ exponential\\(0.5\\)", custom_code)))

  one_pl_code <- capture.output(
    rtmb_irt(Y, model = "1PL", prior = prior_normal())$print_code()
  )
  expect_false(any(grepl("a ~ exponential", one_pl_code, fixed = TRUE)))
})

test_that("normal prior uses inverse-five rates for standard deviations", {
  normal_prior <- prior_normal()
  expect_equal(normal_prior$sigma_rate, 1 / 5)
  expect_equal(normal_prior$tau_rate, 1 / 5)

  dat <- data.frame(
    y = c(-0.4, 0.2, 0.8, 1.1, 1.7, 2.0),
    x = c(-1, 0, 1, -1, 0, 1),
    id = factor(rep(1:3, each = 2))
  )
  default_code <- capture.output(
    rtmb_glmer(
      y ~ x + (1 | id),
      data = dat,
      prior = normal_prior
    )$print_code()
  )

  expect_true(any(grepl("sigma ~ exponential\\(0.2\\)", default_code)))
  expect_true(any(grepl("sd ~ exponential\\(0.2\\)", default_code)))

  custom_code <- capture.output(
    rtmb_glmer(
      y ~ x + (1 | id),
      data = dat,
      prior = prior_normal(sigma_rate = 2, tau_rate = 3)
    )$print_code()
  )
  expect_true(any(grepl("sigma ~ exponential\\(2\\)", custom_code)))
  expect_true(any(grepl("sd ~ exponential\\(3\\)", custom_code)))
})

test_that("FA normal-prior aliases override common hyperparameters", {
  Y <- matrix(rnorm(48), nrow = 12, ncol = 4)

  alias_code <- capture.output(
    rtmb_fa(
      Y,
      nfactors = 1,
      prior = prior_normal(
        mean_sd = 7,
        sd_rate = 0.25,
        loadings_sd = 3
      )
    )$print_code()
  )
  expect_true(any(grepl("mean ~ normal\\(0, 7\\)", alias_code)))
  expect_true(any(grepl("sd ~ exponential\\(0.25\\)", alias_code)))
  expect_true(any(grepl("L_raw ~ lower_tri_normal\\(0, 3\\)", alias_code)))

  common_code <- capture.output(
    rtmb_fa(
      Y,
      nfactors = 1,
      prior = prior_normal(mu_sd = 6, sigma_rate = 0.4, b_sd = 2)
    )$print_code()
  )
  expect_true(any(grepl("mean ~ normal\\(0, 6\\)", common_code)))
  expect_true(any(grepl("sd ~ exponential\\(0.4\\)", common_code)))
  expect_true(any(grepl("L_raw ~ lower_tri_normal\\(0, 2\\)", common_code)))
})

test_that("correlation normal priors use model aliases and default LKJ priors", {
  dat <- data.frame(
    y1 = c(-1.2, -0.7, -0.1, 0.3, 0.8, 1.4),
    y2 = c(-0.8, -0.4, 0.2, 0.5, 1.1, 1.6),
    y3 = c(0.4, -0.2, 0.7, 1.0, 0.1, 1.5),
    id = factor(rep(1:3, each = 2))
  )

  default_code <- paste(
    deparse(rtmb_corr(dat[c("y1", "y2")], prior = prior_normal())$code$model),
    collapse = "\n"
  )
  expect_match(default_code, "mean ~ normal(0, 10)", fixed = TRUE)
  expect_match(default_code, "sd ~ exponential(0.2)", fixed = TRUE)
  expect_match(default_code, "corr ~ lkj_corr(1)", fixed = TRUE)

  alias_code <- paste(
    deparse(rtmb_corr(
      dat[c("y1", "y2")],
      prior = prior_normal(mean_sd = 7, sd_rate = 0.25)
    )$code$model),
    collapse = "\n"
  )
  expect_match(alias_code, "mean ~ normal(0, 7)", fixed = TRUE)
  expect_match(alias_code, "sd ~ exponential(0.25)", fixed = TRUE)
  expect_match(alias_code, "corr ~ lkj_corr(1)", fixed = TRUE)

  common_code <- paste(
    deparse(rtmb_corr(
      dat[c("y1", "y2")],
      prior = prior_normal(mu_sd = 6, sigma_rate = 0.4, lkj_eta = 2)
    )$code$model),
    collapse = "\n"
  )
  expect_match(common_code, "mean ~ normal(0, 6)", fixed = TRUE)
  expect_match(common_code, "sd ~ exponential(0.4)", fixed = TRUE)
  expect_match(common_code, "corr ~ lkj_corr(2)", fixed = TRUE)

  matrix_code <- paste(
    deparse(rtmb_corr(dat[c("y1", "y2", "y3")], prior = prior_normal())$code$model),
    collapse = "\n"
  )
  expect_match(matrix_code, "CF_corr ~ lkj_CF_corr(1)", fixed = TRUE)

  multilevel_code <- paste(
    deparse(rtmb_corr(
      cbind(y1, y2),
      data = dat,
      ID = id,
      prior = prior_normal(mean_sd = 7, sd_rate = 0.25)
    )$code$model),
    collapse = "\n"
  )
  expect_match(multilevel_code, "L_corr_between ~ lkj_CF_corr(1)", fixed = TRUE)
  expect_match(multilevel_code, "L_corr_within ~ lkj_CF_corr(1)", fixed = TRUE)
  expect_match(multilevel_code, "sigma_between ~ exponential(0.25)", fixed = TRUE)
  expect_match(multilevel_code, "sigma_within ~ exponential(0.25)", fixed = TRUE)
  expect_match(multilevel_code, "mu ~ normal(0, 7)", fixed = TRUE)

  flat_code <- paste(
    deparse(rtmb_corr(dat[c("y1", "y2")], prior = prior_flat())$code$model),
    collapse = "\n"
  )
  expect_false(grepl("corr ~ lkj_corr", flat_code, fixed = TRUE))
})

test_that("mixture and LRT weak priors scale to multivariate y_range", {
  dat <- data.frame(
    y1 = c(-2, -1, -0.5, 0.5, 1, 2),
    y2 = c(0.2, 0.8, 1.4, 2.6, 3.2, 3.8)
  )
  ranges <- matrix(
    c(-10, 10,
      0, 4),
    nrow = 2,
    byrow = TRUE,
    dimnames = list(c("y1", "y2"), c("min", "max"))
  )
  expected_rate <- matrix(
    c(0.2, 1,
      0.2, 1),
    nrow = 2,
    byrow = TRUE
  )

  mixture <- rtmb_mixture(
    cbind(y1, y2) ~ 1,
    k = 2,
    data = dat,
    y_range = ranges
  )
  expect_identical(mixture$extra$prior_type, "weak")
  expect_equal(mixture$data$prior_mean_center, matrix(c(0, 2, 0, 2), 2, byrow = TRUE))
  expect_equal(mixture$data$prior_mean_sd, matrix(c(10, 2, 10, 2), 2, byrow = TRUE))
  expect_equal(mixture$data$prior_sigma_rate, expected_rate)
  mixture_code <- capture.output(mixture$print_code())
  expect_true(any(grepl(
    "sigma ~ exponential\\(prior_sigma_rate\\)",
    mixture_code
  )))

  lrt <- rtmb_lrt(
    cbind(y1, y2) ~ 1,
    k = 2,
    data = dat,
    prior = prior_weak(),
    y_range = ranges
  )
  expect_equal(lrt$data$prior_sigma_rate, expected_rate)
  lrt_code <- capture.output(lrt$print_code())
  expect_true(any(grepl(
    "sigma ~ exponential\\(prior_sigma_rate\\)",
    lrt_code
  )))
})

test_that("mixture and LRT reject invalid y_range scaling", {
  dat <- data.frame(y = seq(-1, 1, length.out = 6))

  expect_error(
    rtmb_mixture(y ~ 1, k = 2, data = dat, y_range = c(1, 1)),
    "finite increasing range"
  )
  expect_error(
    rtmb_lrt(y ~ 1, k = 2, data = dat, y_range = matrix(1:6, nrow = 3)),
    "finite increasing range"
  )
})

test_that("wrapper loop-filled matrices use AD-compatible arrays", {
  mix_dat <- data.frame(
    y = c(-1.2, -0.8, -0.2, 0.4, 1.1, 1.8),
    x = c(-1, -0.5, 0, 0.5, 1, 1.5)
  )
  mix <- rtmb_mixture(y ~ x, k = 3, data = mix_dat, prior = prior_rhs())
  mix_code <- capture.output(mix$print_code())
  expect_true(any(grepl("b <- rtmb_array\\(0, dim = c\\(K_prob, K - 1\\)\\)", mix_code)))
  expect_true(any(grepl("b <- matrix\\(0, K_prob, K - 1\\)", mix_code)))
  expect_true(any(grepl("log_dens_mat <- rtmb_array\\(0, dim = c\\(N, K\\)\\)", mix_code)))
  expect_true(any(grepl("log_pi_mat <- rtmb_array\\(0, dim = c\\(N, K\\)\\)", mix_code)))
  expect_true(any(grepl("log_softmax(c(0, eta_prob[i, ]))", mix_code, fixed = TRUE)))
  expect_true(any(grepl("prob_mean <- softmax(c(0, X_means %*% b))", mix_code, fixed = TRUE)))
  expect_false(any(grepl("b <- matrix\\(0, K_prob, K-1\\)", mix_code)))
  expect_false(any(grepl("b <- matrix\\(0, P, K - 1\\)", mix_code)))
  expect_false(any(grepl("log_dens_mat <- matrix\\(mu\\[1\\] \\* 0, N, K\\)", mix_code)))
  expect_false(any(grepl("log_pi_mat <- matrix\\(eta_prob\\[1\\] \\* 0, N, K\\)", mix_code)))

  glmer_dat <- data.frame(
    y = ordered(c(1, 2, 3, 1, 2, 3))
  )
  glmer <- rtmb_glmer(
    y ~ 0,
    data = glmer_dat,
    family = "sequential"
  )
  glmer_code <- capture.output(glmer$print_code())
  expect_true(any(grepl("eta <- rtmb_array\\(0, dim = c\\(N, num_categories - 1\\)\\)", glmer_code)))
  expect_false(any(grepl("eta <- matrix\\(0, N, num_categories - 1\\)", glmer_code)))
})

test_that("AD-sensitive correlation matrices avoid base matrix reconstruction", {
  corr_mdl <- rtmb_corr(mtcars[, c("mpg", "wt")])
  corr_model <- paste(deparse(corr_mdl$code$model), collapse = "\n")
  expect_match(
    corr_model,
    "CF_corr <- rtmb_array(0, dim = c(2, 2), seed = corr)",
    fixed = TRUE
  )
  expect_false(grepl("CF_corr <- matrix(corr * 0", corr_model, fixed = TRUE))

  full_dat <- data.frame(
    y1 = c(-1.8, -1.2, -0.7, -0.1, 0.4, 0.9, 1.3, 1.8),
    y2 = c(-1.1, -0.9, -0.2, 0.2, 0.8, 1.0, 1.7, 2.1)
  )

  mix_mdl <- rtmb_mixture(
    cbind(y1, y2) ~ 1,
    k = 2,
    data = full_dat,
    covariance = "full",
    prior = prior_normal(lkj_eta = 1)
  )
  mix_model <- paste(deparse(mix_mdl$code$model), collapse = "\n")
  expect_match(mix_model, "L_corr_k <- rtmb_array", fixed = TRUE)
  expect_match(mix_model, "seed = L_corr[k,", fixed = TRUE)
  expect_false(grepl("matrix(L_corr[k, , ], P, P)", mix_model, fixed = TRUE))

  lrt_mdl <- rtmb_lrt(
    cbind(y1, y2) ~ 1,
    k = 2,
    data = full_dat,
    covariance = "full",
    magnitude = 1,
    smoothing = 1,
    prior = prior_normal(lkj_eta = 1)
  )
  lrt_model <- paste(deparse(lrt_mdl$code$model), collapse = "\n")
  expect_match(lrt_model, "L_mat <- rtmb_array", fixed = TRUE)
  expect_match(lrt_model, "seed = L_corr[k,", fixed = TRUE)
  expect_false(grepl("matrix(L_corr[k, , ], P, P)", lrt_model, fixed = TRUE))
})

test_that("rtmb_glmer setup capture leaves formula-like objects intact", {
  glmer_dat <- data.frame(
    y = c(0.2, 0.5, -0.1, 0.7, 0.0, 0.4),
    x = c(0, 1, 0, 1, 0, 1),
    group = factor(c(1, 1, 2, 2, 3, 3))
  )

  mdl <- rtmb_glmer(y ~ x + (1 | group), data = glmer_dat, family = "gaussian")
  expect_s3_class(mdl, "RTMB_Model")
})

test_that("Wrappers sample correctly (skip on CRAN)", {
  skip_on_cran()
  
  fit_lm <- rtmb_lm(mpg ~ wt, data = mtcars)
  # Extremely short sampling just to test code path
  res_lm <- fit_lm$sample(chains = 1, sampling = 10, warmup = 10)
  expect_true(inherits(res_lm, "mcmc_fit"))
  expect_identical(res_lm$nuts_variant, "multinomial")
  expect_identical(res_lm$metric_requested, "auto")
  expect_true(res_lm$metric_type %in% c("diag", "hybrid", "mixed"))
  expect_identical(res_lm$metric_adaptation, "stan_window")

  res_lm_dense <- suppressWarnings(fit_lm$sample(
    chains = 1, sampling = 5, warmup = 25,
    metric = "dense", metric_init = "hessian",
    metric_adaptation = "cumulative",
    nuts_variant = "multinomial", delta = 0.99
  ))
  expect_true(inherits(res_lm_dense, "mcmc_fit"))
  expect_identical(res_lm_dense$metric_type, "dense")
  expect_identical(res_lm_dense$metric_init, "hessian")
  expect_identical(res_lm_dense$metric_adaptation, "cumulative")
  expect_true(is.matrix(res_lm_dense$metric[[1]]))
  expect_true(is.list(res_lm_dense$warmup_diagnostics))
  expect_true(is.data.frame(res_lm_dense$warmup_diagnostics[[1]]))
  expect_true(all(c("phase", "window", "metric_updated") %in% names(res_lm_dense$warmup_diagnostics[[1]])))

  dat_re <- list(Y = rnorm(8), group = rep(1:4, each = 2), G = 4)
  code_re <- rtmb_code(
    parameters = {
      mu = Dim()
      sigma = Dim(lower = 0)
      tau = Dim(lower = 0)
      r = Dim(G, random = TRUE)
    },
    model = {
      Y ~ normal(mu + r[group] * tau, sigma)
      r ~ normal(0, 1)
      tau ~ exponential(1)
      sigma ~ exponential(1)
    }
  )
  res_hybrid <- suppressWarnings(rtmb_model(dat_re, code_re)$sample(
    chains = 1, sampling = 3, warmup = 20,
    metric = "hybrid", nuts_variant = "multinomial", delta = 0.99
  ))
  expect_identical(res_hybrid$metric_type, "hybrid")
  expect_true(is.list(res_hybrid$metric[[1]]))
  expect_true(length(res_hybrid$metric[[1]]$dense_idx) > 0)
  expect_true(length(res_hybrid$metric[[1]]$diag_idx) > 0)

  res_lm_stan_window <- suppressWarnings(fit_lm$sample(
    chains = 1, sampling = 3, warmup = 20,
    metric = "diag", delta = 0.99,
    metric_adaptation = "stan_window"
  ))
  expect_identical(res_lm_stan_window$metric_adaptation, "stan_window")
  expect_true(is.data.frame(res_lm_stan_window$warmup_diagnostics[[1]]))
  expect_true("metric_updated" %in% names(res_lm_stan_window$warmup_diagnostics[[1]]))
})

test_that("Wrappers reject unsupported priors and unused dots", {
  Ybin <- matrix(sample(0:1, 30, replace = TRUE), nrow = 10)
  Yfa <- scale(mtcars[1:20, c("mpg", "disp", "hp")])

  expect_error(rtmb_irt(Ybin, prior = prior_rhs()), "supports only")
  expect_error(rtmb_fa(Yfa, nfactors = 1, prior = prior_jzs()), "supports only")
  expect_error(rtmb_ttest(mpg ~ am, data = mtcars, prior = prior_rhs()), "supports only")
  expect_error(rtmb_table(matrix(c(3, 4, 5, 6), 2), prior = prior_jzs()), "supports only")

  expect_error(rtmb_lmer(mpg ~ wt + (1 | cyl), data = mtcars, typo_arg = 1), "unused argument")
  expect_error(rtmb_ttest(mpg ~ am, data = mtcars, typo_arg = 1), "unused argument")
  expect_error(rtmb_table(matrix(c(1, 2, 3, 4), 2), typo_arg = 1), "unused argument")
})

test_that("JZS t-tests include the Jeffreys prior for scale", {
  y1 <- c(-1.2, -0.3, 0.4, 1.1, 1.7)
  y2 <- c(0.1, 0.8, 1.2, 2.0, 2.4)

  equal_code <- capture.output(
    rtmb_ttest(y1, y2, prior = prior_jzs())$print_code()
  )
  expect_true(any(grepl("lp <- lp - log\\(sd\\)", equal_code)))

  paired_code <- capture.output(
    rtmb_ttest(y1, y2, paired = TRUE, prior = prior_jzs())$print_code()
  )
  expect_true(any(grepl("lp <- lp - log\\(sd_diff\\)", paired_code)))

  unequal_code <- capture.output(
    rtmb_ttest(y1, y2, var.equal = FALSE, prior = prior_jzs())$print_code()
  )
  expect_true(any(grepl("lp <- lp - sum\\(log\\(sd\\)\\)", unequal_code)))

  flat_code <- capture.output(rtmb_ttest(y1, y2)$print_code())
  expect_false(any(grepl("lp <- lp - .*log\\(sd", flat_code)))
})

test_that("rtmb_glmer cwc accepts unquoted cluster with all numeric fixed effects", {
  dat <- data.frame(
    y = c(1, 2, 3, 4, 5, 6),
    x = c(1, 2, 3, 10, 11, 12),
    z = c(2, 4, 6, 20, 22, 24),
    f = factor(c("a", "b", "a", "a", "b", "a")),
    ID = rep(c("g1", "g2"), each = 3)
  )

  mdl <- rtmb_glmer(
    y ~ x + z + f + (1 | ID),
    data = dat,
    family = "gaussian",
    cwc = list(ID, "all")
  )

  centered <- mdl$raw_data
  expect_equal(as.numeric(tapply(centered$x, centered$ID, mean)), c(0, 0), tolerance = 1e-12)
  expect_equal(as.numeric(tapply(centered$z, centered$ID, mean)), c(0, 0), tolerance = 1e-12)
  expect_identical(centered$y, dat$y)
  expect_identical(centered$f, dat$f)
})

test_that("rtmb_mdu supports hierarchical lambda for choice models", {
  sets <- matrix(
    c(1, 2, 3,
      2, 3, 4),
    nrow = 2,
    byrow = TRUE
  )
  best <- matrix(
    c(1, 2,
      2, 3,
      3, 1),
    nrow = 3,
    byrow = TRUE
  )

  mdl <- rtmb_mdu(
    list(Best = best),
    ndim = 1,
    method = "Best",
    sets = sets,
    lambda = "random",
    prior = prior_normal()
  )

  expect_equal(mdl$extra$lambda, "random")
  expect_equal(mdl$extra$distance, "euclidean")
  expect_true(all(c("lambda_mu", "sigma_lambda", "lambda_raw") %in% names(mdl$par_list)))
  expect_true("lambda_raw" %in% names(mdl$par_names))
  choice_print <- capture.output(mdl$print_code())
  expect_true(any(grepl("D <- 1", choice_print, fixed = TRUE)))
  expect_false(any(grepl("ndim <-", choice_print, fixed = TRUE)))
  expect_error(rtmb_mdu(matrix(rnorm(20), nrow = 5), lambda = "random"), "only available")
})

test_that("rtmb_mdu defaults to euclidean distance for rating models", {
  mdl <- rtmb_mdu(matrix(rnorm(20), nrow = 5), ndim = 1)

  expect_equal(mdl$extra$distance, "euclidean")
})

test_that("rating and MDS wrapper code can be rebuilt from the original data", {
  set.seed(21)
  rating_dat <- data.frame(
    item1 = rnorm(6),
    item2 = rnorm(6),
    item3 = rnorm(6),
    item4 = rnorm(6)
  )
  rating_model <- rtmb_mdu(
    rating_dat,
    ndim = 1,
    method = "rating",
    prior = prior_normal()
  )
  rating_code <- rating_model$code
  rating_code$setup_env <- NULL
  rating_rebuilt <- rtmb_model(
    data = rating_dat,
    code = rating_code,
    init = rating_model$init,
    silent = TRUE
  )

  expect_equal(rating_rebuilt$data$Y, rating_model$data$Y)
  expect_equal(rating_rebuilt$data$D, 1)
  rating_print <- capture.output(rating_model$print_code())
  expect_true(any(grepl("Y <- as.matrix\\(\\.data\\)", rating_print)))
  expect_true(any(grepl("D <- 1", rating_print, fixed = TRUE)))
  expect_false(any(grepl("ndim <-", rating_print, fixed = TRUE)))

  coords <- matrix(rnorm(10), nrow = 5, ncol = 2)
  distance_dat <- as.matrix(dist(coords))
  mds_model <- rtmb_mdu(
    distance_dat,
    ndim = 1,
    method = "MDS",
    prior = prior_normal()
  )
  mds_code <- mds_model$code
  mds_code$setup_env <- NULL
  mds_rebuilt <- rtmb_model(
    data = distance_dat,
    code = mds_code,
    init = mds_model$init,
    silent = TRUE
  )

  expect_equal(mds_rebuilt$data$Y, mds_model$data$Y)
  expect_equal(mds_rebuilt$data$D, 1)
  mds_print <- capture.output(mds_model$print_code())
  expect_true(any(grepl("D <- 1", mds_print, fixed = TRUE)))
  expect_false(any(grepl("ndim <-", mds_print, fixed = TRUE)))
})

test_that("rotate can use a principal-axis reference", {
  X <- matrix(
    c(2, 1,
      1, 2,
     -1, -2,
     -2, -1),
    ncol = 2,
    byrow = TRUE
  )

  code <- rtmb_code(
    parameters = {
      coords = Dim(c(4, 2))
    },
    model = {
      coords ~ normal(X, 0.01)
    }
  )

  fit <- rtmb_model(list(X = X), code, init = list(coords = X), silent = TRUE)$optimize(
    num_estimate = 1,
    se_method = "none"
  )
  fit$rotate("coords", principal = TRUE)

  coords_rot <- fit$generate$coords_rot
  coords_centered <- sweep(coords_rot, 2, colMeans(coords_rot), "-")
  ss <- crossprod(coords_centered)

  expect_lt(abs(ss[1, 2]), 1e-6)
  expect_true(ss[1, 1] >= ss[2, 2])
})

test_that("rotate can overwrite or save with a unique suffix", {
  X <- matrix(
    c(2, 1,
      1, 2,
     -1, -2,
     -2, -1),
    ncol = 2,
    byrow = TRUE
  )

  code <- rtmb_code(
    parameters = {
      coords = Dim(c(4, 2))
    },
    model = {
      coords ~ normal(X, 0.01)
    }
  )

  fit <- rtmb_model(list(X = X), code, init = list(coords = X), silent = TRUE)$optimize(
    num_estimate = 1,
    se_method = "none"
  )

  fit$rotate("coords", principal = TRUE)
  expect_true("coords_rot" %in% names(fit$generate))

  fit$rotate("coords", principal = TRUE)
  expect_true("coords_rot" %in% names(fit$generate))
  expect_false("coords_rot_2" %in% names(fit$generate))

  fit$rotate("coords", principal = TRUE, overwrite = FALSE)
  expect_true("coords_rot_2" %in% names(fit$generate))

  fit$rotate("coords", principal = TRUE, suffix = "principal")
  expect_true("coords_principal" %in% names(fit$generate))
})

Try the BayesRTMB package in your browser

Any scripts or data that you put into this service are public.

BayesRTMB documentation built on Nov. 24, 2026, 9:06 a.m.