tests/testthat/test-backend.R

# Tests for the Stan backends (id_estimate(backend = ))

options(cmdstanr_warn_inits = FALSE)

# a stand-in for a compiled model: only its $variables() method is used
stub_model <- function(data = list(), parameters = list()) {
  dims <- function(x) lapply(x, function(d) list(type = "real", dimensions = d))
  list(variables = function() list(data = dims(data), parameters = dims(parameters)))
}

test_that("the backend is taken from the argument, then the option", {
  old <- options(idealstan.backend = NULL)
  on.exit(options(old))

  expect_equal(.pick_backend("stanr"), "stanr")
  expect_equal(.pick_backend("cmdstanr"), "cmdstanr")
  expect_error(.pick_backend("rstan"), "backend must be one of")

  options(idealstan.backend = "stanr")
  expect_equal(.pick_backend(), "stanr")
  expect_equal(.pick_backend("cmdstanr"), "cmdstanr")

  options(idealstan.backend = "cmdstan")
  expect_error(.pick_backend(), "backend must be one of")
})

test_that("id_backend_available checks the backend id_estimate would use", {
  old <- options(idealstan.backend = NULL)
  on.exit(options(old))

  expect_identical(id_backend_available("stanr"), rlang::is_installed("stanr"))
  expect_identical(id_backend_available("cmdstanr"), .cmdstan_ready())
  expect_identical(id_backend_available(),
                   id_backend_available(.pick_backend()))
  expect_error(id_backend_available("rstan"), "backend must be one of")

  options(idealstan.backend = "stanr")
  expect_identical(id_backend_available(), rlang::is_installed("stanr"))
})

test_that("stanr data give containers of one element their dimensions", {
  model <- stub_model(data = list(N = 0, fix_high = 1, restrict_high = 1, B = 2,
                                  legis_pred = 2))
  data <- list(N = 3, fix_high = 1.5, restrict_high = c(2, 4), B = 7,
               legis_pred = matrix(NA_real_, 0, 0), not_in_model = 1)

  out <- .stanr_data(model, data)

  expect_named(out, c("N", "fix_high", "restrict_high", "B", "legis_pred"))
  expect_null(dim(out$N))
  expect_equal(dim(out$fix_high), 1)
  expect_null(dim(out$restrict_high))
  expect_equal(dim(out$B), c(1, 1))
  # covariate matrices without covariates have N rows
  expect_equal(dim(out$legis_pred), c(3, 0))
})

test_that("stanr inits are the first chain's, with dimensions", {
  model <- stub_model(parameters = list(L_free = 1, legis_x = 1, sigma = 0))
  inits <- list(list(L_free = c(1, 2), legis_x = 0.5, sigma = 1),
                list(L_free = c(3, 4), legis_x = 0.1, sigma = 2))

  out <- .stanr_init(model, inits)

  expect_equal(out$L_free, c(1, 2))
  expect_equal(dim(out$legis_x), 1)
  expect_null(dim(out$sigma))
  expect_null(.stanr_init(model, NULL))
  expect_equal(.stanr_init(model, 0.5), 0.5)
})

test_that("id_estimate fits with stanr", {
  skip_on_cran()
  skip_if_not_installed("stanr")

  set.seed(5)
  sim <- id_sim_gen(num_person = 20, num_items = 15)
  quiet <- function(x) suppressMessages(suppressWarnings(x))

  fit <- quiet(id_estimate(sim, model_type = 1, backend = "stanr", nchains = 2,
                           niters = 200, warmup = 200, ncores = 2, fixtype = "prefix",
                           restrict_ind_high = 1, restrict_ind_low = 2, seed = 1))

  expect_s3_class(fit@stan_samples, "StanMCMC")
  expect_equal(posterior::nchains(fit@stan_samples$draws("L_full")), 2)
  expect_true(all(c("rhat", "ess_bulk") %in% names(fit@summary)))
  expect_s3_class(fit@diagnostics, "draws")

  ll <- quiet(id_post_pred(fit, type = "log_lik"))
  expect_equal(dim(ll), c(400, fit@this_data$N))

  pf <- quiet(id_estimate(sim, model_type = 1, backend = "stanr", use_method = "pathfinder",
                          ncores = 2, fixtype = "vb_full", seed = 1))
  expect_s3_class(pf@stan_samples, "StanPathfinder")

  # the same model as with cmdstanr
  skip_if_not_installed("cmdstanr")
  if (is.null(cmdstanr::cmdstan_version(error_on_NA = FALSE))) skip("cmdstan not installed")

  fit_cmd <- quiet(id_estimate(sim, model_type = 1, backend = "cmdstanr", nchains = 2,
                               niters = 200, warmup = 200, ncores = 2, fixtype = "prefix",
                               restrict_ind_high = 1, restrict_ind_low = 2, seed = 1))
  ideal <- function(f) {
    s <- summary(f)
    setNames(s$`Posterior Median`, s$Person)[as.character(1:20)]
  }
  expect_gt(cor(ideal(fit), ideal(fit_cmd)), 0.98)
})

test_that("shinystan objects are built from fits of either backend", {
  skip_on_cran()
  skip_if_not_installed("shinystan", minimum_version = "2.6.0")

  set.seed(5)
  sim <- id_sim_gen(num_person = 20, num_items = 15, model_type = "ordinal_ratingscale")
  quiet <- function(x) suppressMessages(suppressWarnings(x))
  pars <- c("L_full", "sigma_reg_full", "sigma_abs_free", "A_int_free", "B_int_free",
            "steps_votes", "steps_votes_grm")

  backends <- c("stanr", "cmdstanr")[c(requireNamespace("stanr", quietly = TRUE),
                                       requireNamespace("cmdstanr", quietly = TRUE) &&
                                         !is.null(cmdstanr::cmdstan_version(error_on_NA = FALSE)))]
  if (length(backends) == 0) skip("no backend installed")

  for (backend in backends) {
    fit <- quiet(id_estimate(sim, model_type = 3, backend = backend, nchains = 2,
                             niters = 100, warmup = 100, ncores = 2, fixtype = "prefix",
                             restrict_ind_high = 1, restrict_ind_low = 2, seed = 1))
    sso <- .as_shinystan(fit, pars)
    expect_s4_class(sso, "shinystan")
    expect_equal(sso@n_chain, 2)
    # the cutpoints of the rating-scale model are selected by "steps_votes"
    expect_setequal(names(sso@param_dims),
                    c("log-posterior", "L_full", "sigma_reg_full", "sigma_abs_free",
                      "A_int_free", "B_int_free", "steps_votes3"))
    expect_equal(sso@param_dims$L_full, 20)
    # NUTS diagnostics, one matrix per chain
    expect_length(sso@sampler_params, 2)
    expect_true(all(c("divergent__", "treedepth__") %in% colnames(sso@sampler_params[[1]])))

    expect_error(.as_shinystan(fit, "nope"), "None of pars")
  }

  # draws only for approximations
  pf <- quiet(id_estimate(sim, model_type = 3, backend = backends[1], use_method = "pathfinder",
                          fixtype = "prefix", restrict_ind_high = 1, restrict_ind_low = 2,
                          seed = 1))
  expect_message(sso <- .as_shinystan(pf, "L_full"), "no sampler diagnostics")
  expect_equal(sso@n_chain, 1)
})

test_that("Pathfinder tries random starting values when it fails from those found", {
  skip_on_cran()

  set.seed(7)
  sim <- id_sim_gen(num_person = 20, num_items = 10)

  # the first run finds starting values; the second, for inference, fails as it
  # does when L-BFGS can't take its first step from them
  real_pathfinder <- .stan_pathfinder
  inits <- list()
  local_mocked_bindings(.stan_pathfinder = function(model, data, init = NULL, ...) {
    inits[[length(inits) + 1]] <<- init
    if (length(inits) == 2) stop("Optimization failed to start, pathfinder cannot be run.")
    real_pathfinder(model, data, init = init, ...)
  })

  msgs <- capture_messages(fit <- suppressWarnings(
    id_estimate(sim, model_type = 1, use_method = "pathfinder", nchains = 2, seed = 7,
                fixtype = "prefix", restrict_ind_high = 1, restrict_ind_low = 2)))

  expect_true(any(grepl("trying again from random starting values", msgs)))
  expect_length(inits, 3)
  expect_false(identical(inits[[2]], inits[[3]]))
  expect_gt(posterior::ndraws(fit@stan_samples$draws()), 0)

  # when every run fails, the error says so
  local_mocked_bindings(.stan_pathfinder = function(...) stop("Optimization failed to start"))
  expect_error(suppressMessages(suppressWarnings(
    id_estimate(sim, model_type = 1, use_method = "pathfinder", nchains = 2, seed = 7,
                fixtype = "prefix", restrict_ind_high = 1, restrict_ind_low = 2))),
    "Pathfinder failed to estimate the model")
})

Try the idealstan package in your browser

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

idealstan documentation built on Dec. 2, 2026, 5:07 p.m.