R/Backend.R

Defines functions .as_shinystan .param_dims .fit_variables .has_draws .stan_sample .stan_laplace .stan_pathfinder .stanr_init .stanr_data .compile_stan id_backend_available .check_backend .pick_backend .cmdstan_ready .model_backend

Documented in id_backend_available

# Stan backends -------------------------------------------------------------

# idealstan runs Stan with cmdstanr (which calls a CmdStan installation) or with
# stanr (which runs Stan inside R). Their model objects have nearly the same
# $sample(), $pathfinder() and $laplace() methods, and their fit objects the same
# $draws(), $summary() and $sampler_diagnostics() methods. These helpers handle
# the differences, so that the rest of the package can use either.

#' The backends that can run Stan
#' @noRd
.backends <- c("cmdstanr", "stanr")

#' The backend of a compiled model
#' @noRd
.model_backend <- function(model) {
  if(inherits(model, "StanModel")) "stanr" else "cmdstanr"
}

#' Whether cmdstanr and a CmdStan installation are available
#' @noRd
.cmdstan_ready <- function() {
  is_installed("cmdstanr") &&
    !is.null(suppressWarnings(suppressMessages(cmdstanr::cmdstan_version(error_on_NA = FALSE))))
}

#' Choose the backend
#'
#' `backend` as given, or if `NULL`, the option `idealstan.backend`, or if that
#' isn't set either, cmdstanr if it and CmdStan are installed and stanr otherwise.
#' @noRd
.pick_backend <- function(backend=NULL) {

  if(is.null(backend)) backend <- getOption("idealstan.backend")

  if(is.null(backend)) {
    backend <- if(!.cmdstan_ready() && is_installed("stanr")) "stanr" else "cmdstanr"
  }

  if(length(backend) != 1 || !(backend %in% .backends)) {
    stop("backend must be one of ", paste0("'", .backends, "'", collapse=" or "), ".",
         call.=FALSE)
  }

  backend

}

#' Check that a backend can run models
#'
#' Returns `TRUE`, or `FALSE` with a message saying how to install it. In
#' interactive sessions, offers to install the R package.
#' @noRd
.check_backend <- function(backend) {

  if(backend == "stanr") {

    if(!is_installed("stanr") && interactive()) {
      check_installed("stanr",
                      reason="to run Stan with backend='stanr'. It is available from https://andrjohns.r-universe.dev.",
                      action=function(pkg, ...) {
                        install.packages(pkg, repos=c("https://andrjohns.r-universe.dev",
                                                      "https://cloud.r-project.org"))
                      })
    }

    if(!is_installed("stanr")) {
      message("The R package stanr is not installed so idealstan cannot estimate models with backend='stanr'. ",
              "Install it with install.packages('stanr', repos = c('https://andrjohns.r-universe.dev', ",
              "'https://cloud.r-project.org')), or use backend='cmdstanr'.")
      return(FALSE)
    }

    return(TRUE)

  }

  if(!is_installed("cmdstanr") && interactive()) {
    check_installed("cmdstanr",
                    version="0.8.1",
                    reason="idealstan requires the package cmdstanr to run (or set backend='stanr'). This package is available from an external repository, https://stan-dev.r-universe.dev.",
                    action=function(pkg, ...) {
                      install.packages(pkg, repos=c("https://stan-dev.r-universe.dev"))
                    })
  }

  if(!is_installed("cmdstanr")) {
    message("The R package cmdstanr is not installed so idealstan cannot estimate models. ",
            "Please go to https://mc-stan.org/cmdstanr/ for installation instructions for the package cmdstanr, ",
            "or install the package stanr and set backend='stanr'.")
    return(FALSE)
  }

  if(!.cmdstan_ready()) {
    message("R package cmdstanr is installed but cmdstan is not yet installed & set up. ",
            "Please load the R package cmdstanr and use function install_cmdstan() to install cmdstan ",
            "on your local machine (for more information, see https://mc-stan.org/cmdstanr/), ",
            "or install the package stanr and set backend='stanr'.")
    return(FALSE)
  }

  TRUE

}

#' Check Whether Models Can Be Estimated
#'
#' [id_estimate()] runs Stan with the 'cmdstanr' package, which needs a CmdStan
#' installation, or with the 'stanr' package. Neither is on CRAN. This function
#' says whether the backend that [id_estimate()] would use is installed, so that
#' code can estimate models only when it is (the package's examples use it this
#' way).
#'
#' @param backend `"cmdstanr"` or `"stanr"` to check that backend. If `NULL`
#'   (the default), the backend that [id_estimate()] uses when its `backend`
#'   argument isn't given: the option `idealstan.backend` if it is set, and
#'   otherwise 'cmdstanr' if it and CmdStan are installed and 'stanr' if not.
#' @return `TRUE` if the backend is installed and can run models, `FALSE` if
#'   not.
#' @examples
#' id_backend_available()
#' id_backend_available("stanr")
#' @export
id_backend_available <- function(backend=NULL) {

  backend <- .pick_backend(backend)

  if(backend == "stanr") is_installed("stanr") else .cmdstan_ready()

}

#' Compile a Stan program
#'
#' `threads` (CmdStan's `STAN_THREADS`, not set if `NULL`) and `optim`
#' (`STAN_CPP_OPTIMS`) only apply to cmdstanr: stanr always compiles with
#' threading.
#' @noRd
.compile_stan <- function(stan_file, backend, threads=NULL, optim=FALSE, force=FALSE) {

  if(backend == "stanr") {

    stanr::stan_model(stan_file=stan_file,
                      include_paths=dirname(stan_file),
                      force_recompile=force)

  } else {

    cpp_options <- list()
    if(!is.null(threads)) cpp_options$stan_threads <- threads
    if(optim) cpp_options$STAN_CPP_OPTIMS <- TRUE

    cmdstanr::cmdstan_model(stan_file,
                            include_paths=dirname(stan_file),
                            cpp_options=cpp_options,
                            force_recompile=force)

  }

}

#' Data for a stanr model
#'
#' stanr reads an R vector of length 1 as a scalar, so a container of one
#' element needs an explicit dimension (cmdstanr adds it from the model's
#' variables). Only the variables in the data block are passed.
#' @noRd
.stanr_data <- function(model, data) {

  vars <- model$variables()$data
  data <- data[intersect(names(data), names(vars))]

  for(v in names(data)) {
    num_dim <- vars[[v]]$dimensions
    if(num_dim > 0 && is.null(dim(data[[v]])) && length(data[[v]]) == 1) {
      data[[v]] <- array(data[[v]], dim=rep(1, num_dim))
    }
  }

  # stanr checks every dimension of an empty container (CmdStan accepts an empty
  # JSON array). The covariate matrices of models without covariates are
  # declared with N rows and no columns.
  for(v in intersect(c("legis_pred","srx_pred","sax_pred"), names(data))) {
    if(length(data[[v]]) == 0) data[[v]] <- matrix(numeric(0), nrow=data$N, ncol=0)
  }

  data

}

#' Initial values for stanr, which uses one set for all chains or paths
#'
#' `init` is `NULL`, a number, or as for cmdstanr a list with one list of values
#' per chain, of which the first is used. As with the data, a container
#' parameter of one element needs an explicit dimension.
#' @noRd
.stanr_init <- function(model, init) {

  if(!(is.list(init) && length(init) > 0 && is.list(init[[1]]))) return(init)

  init <- init[[1]]
  vars <- model$variables()$parameters

  for(v in intersect(names(init), names(vars))) {
    num_dim <- vars[[v]]$dimensions
    if(num_dim > 0 && is.null(dim(init[[v]])) && length(init[[v]]) == 1) {
      init[[v]] <- array(init[[v]], dim=rep(1, num_dim))
    }
  }

  init

}

#' Run Pathfinder
#' @noRd
.stan_pathfinder <- function(model, data, init=NULL, num_threads=1, ...) {

  if(.model_backend(model) == "stanr") {
    model$pathfinder(data=.stanr_data(model, data), init=.stanr_init(model, init),
                     num_threads=num_threads, ...)
  } else {
    model$pathfinder(data=data, init=init, num_threads=num_threads, ...)
  }

}

#' Run the Laplace approximation
#' @noRd
.stan_laplace <- function(model, data, init=NULL, num_threads=1, ...) {

  if(.model_backend(model) == "stanr") {
    model$laplace(data=.stanr_data(model, data), init=.stanr_init(model, init),
                  num_threads=num_threads, ...)
  } else {
    model$laplace(data=data, init=init, threads=num_threads, ...)
  }

}

#' Run Stan's MCMC sampler
#'
#' With cmdstanr, the chains run in parallel, each with
#' `floor(ncores / chains)` threads (at least one). stanr runs the chains in
#' parallel within R with `max(ncores, chains)` threads in all, and starts them
#' all from the first set of initial values. `output_dir` (where cmdstanr saves
#' its CSV files) doesn't apply to stanr.
#' @noRd
.stan_sample <- function(model, data, chains, init=NULL, ncores=1, output_dir=NULL, ...) {

  if(.model_backend(model) == "stanr") {

    if(!is.null(output_dir)) {
      warning("save_files only applies to backend='cmdstanr', so it is ignored.", call.=FALSE)
    }

    model$sample(data=.stanr_data(model, data), chains=chains, init=.stanr_init(model, init),
                 num_threads=max(ncores, chains), ...)

  } else {

    model$sample(data=data, chains=chains, parallel_chains=chains,
                 threads_per_chain=max(1, floor(ncores/chains)),
                 init=init, output_dir=output_dir, ...)

  }

}

#' Whether a fit has draws
#'
#' A failed 'cmdstanr' fit is still returned, and only fails when its draws
#' are read ("Fitting failed. Unable to retrieve the draws."); a failed 'stanr'
#' fit is an error, caught as a try-error.
#' @noRd
.has_draws <- function(fit) {
  if(inherits(fit, "try-error")) return(FALSE)
  draws <- try(fit$draws(), silent=TRUE)
  !inherits(draws, "try-error") && posterior::ndraws(draws) > 0
}

#' Names of the variables in a fit
#'
#' 'cmdstanr' lists them in the metadata, without reading the draws; 'stanr'
#' keeps the draws in memory.
#' @noRd
.fit_variables <- function(fit) {
  vars <- fit$metadata()$variables
  if(is.null(vars)) vars <- posterior::variables(fit$draws())
  vars
}

#' Dimensions of each variable, from the names of their elements
#' @noRd
.param_dims <- function(vars) {
  base <- sub("\\[.*$", "", vars)
  lapply(split(vars, factor(base, levels=unique(base))), function(v) {
    idx <- regmatches(v, regexpr("(?<=\\[).*(?=\\])", v, perl=TRUE))
    if(length(idx) == 0) return(numeric(0))
    apply(do.call(rbind, lapply(strsplit(idx, ","), as.integer)), 2, max)
  })
}

#' A shinystan object of a fitted model
#'
#' Built from the draws, so that it works with either backend and any version
#' of shinystan from 2.6.0. `pars` are matched to the variables' names, without
#' a number at the end, so that `"steps_votes"` selects the cutpoints of every
#' ordinal model type (`steps_votes3`, `steps_votes4`, ...).
#' @noRd
.as_shinystan <- function(object, pars=NULL) {

  fit <- object@stan_samples
  vars <- .fit_variables(fit)
  base <- unique(sub("\\[.*$", "", vars))
  base <- base[!grepl("__$", base) | base == "lp__"]

  if(!is.null(pars)) {
    keep <- base %in% pars | sub("[0-9]+$", "", base) %in% pars
    if(!any(keep[base != "lp__"])) {
      stop("None of pars are parameters of this model: ", paste(pars, collapse=", "),
           ".", call.=FALSE)
    }
    base <- base[keep | base == "lp__"]
  }

  draws <- posterior::as_draws_array(fit$draws(variables=base))
  mcmc <- object@use_method == "mcmc"

  sampler_params <- NULL
  max_treedepth <- NULL

  if(mcmc) {
    diagnostics <- posterior::as_draws_array(fit$sampler_diagnostics())
    sampler_params <- lapply(seq_len(posterior::nchains(diagnostics)), function(j) {
      as.matrix(posterior::as_draws_matrix(posterior::subset_draws(diagnostics, chain=j)))
    })
    max_treedepth <- fit$metadata()$max_treedepth
    if(is.null(max_treedepth)) max_treedepth <- 10
  } else {
    message("Models fitted with use_method='", object@use_method, "' have no sampler ",
            "diagnostics, so only the draws are shown.")
  }

  shinystan::as.shinystan(unclass(draws),
                          model_name=paste0("idealstan (", object@use_method, ")"),
                          param_dims=.param_dims(posterior::variables(draws)),
                          sampler_params=sampler_params,
                          algorithm=if(mcmc) "NUTS" else NULL,
                          max_treedepth=max_treedepth)

}

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.