tests/testthat/helper-stan.R

# One Stan compilation for the whole suite
# ========================================
#
# Every `*_lpdf_expose()` in the package wraps its own `functions {}` block in a
# throwaway model and compiles it. That is the right interface for a user
# exposing one density, but the suite checks nine of them against their R
# counterparts, and on Windows each compilation costs far more than every test
# it serves put together.
#
# The Stan those functions wrap is generated by `.cogmod_<name>_lpdf()`, which
# is just a string, and no two families declare a function of the same name. So
# all of them go into one `functions {}` block, compiled once on first use and
# shared from there on.
#
# `stan_fun("cogmod_lba1")` returns exactly what `cogmod_lba1_lpdf_expose()`
# would. That the two agree is itself checked, once, in
# test-cogmod_generics.R - so the shortcut cannot quietly diverge from the
# interface it stands in for.

# Every family with an lpdf to expose, and the internal that generates it. The
# betadiscrete one is an lpmf; everything else is an lpdf.
.STAN_LPDF_FAMILIES <- c(
  "cogmod_lognormal", "cogmod_logstudent", "cogmod_loggamma", "cogmod_invgaussian", "cogmod_gamma",
  "cogmod_invgamma", "cogmod_weibull", "cogmod_invweibull", "cogmod_logweibull",
  "cogmod_exwald", "cogmod_bisa", "cogmod_lba1", "cogmod_lnr", "cogmod_rdm", "cogmod_ddm", "cogmod_lba2",
  "cogmod_betagate", "cogmod_choco", "cogmod_exgaussian", "cogmod_geg",
  "cogmod_betadiscrete"
)

# The cache lives in an option rather than in this file's environment, because
# testthat re-sources the helpers for every test file. A per-file environment
# would therefore be empty each time, and the second call would hand
# `cmdstan_model()` a stan file whose executable already exists - which returns
# a *pre-compiled* model, and `expose_functions()` refuses to work on one of
# those ("Exporting standalone functions is not possible with a pre-compiled
# Stan model!"). An option outlives the file, so the model really is built once
# per session. This is the same trap the RDM tests used to work around with a
# cache of their own.
.stan_cached <- function() getOption("cogmod.test.stan_model")

# The generated Stan for one family, whichever suffix its generator carries.
.stan_lpdf_code <- function(name) {
  for (suffix in c("_lpdf", "_lpmf")) {
    f <- tryCatch(
      getFromNamespace(paste0(".", name, suffix), "cogmod"),
      error = function(e) NULL
    )
    if (!is.null(f)) return(f())
  }
  stop("No Stan generator found for '", name, "'.", call. = FALSE)
}

# One family's Stan code carries its whole `prelude` with it, which is right for
# `cogmod_<family>_stanvars()`: a model uses one family, and its code has to
# stand alone. Concatenating every family into a single `functions {}` block, as
# this helper does and nothing else in the package does, is the one situation
# where that bites - cogmod_lba1() and cogmod_lba2() share `.LBA_STAN_PRELUDE`,
# so its two kernels would be defined twice and Stan would refuse to compile.
#
# The shared preludes are therefore stripped from every copy after the first.
# Their names are read off the registries rather than listed here, so a family
# added later with a shared prelude needs no change.
.stan_prelude_name <- function(e) if (is.null(e$prelude)) "" else e$prelude

.stan_dedupe_preludes <- function(codes) {
  named <- c(
    vapply(cogmod:::.SHIFTED, .stan_prelude_name, character(1)),
    vapply(cogmod:::.CHOICE, .stan_prelude_name, character(1)),
    # cogmod_exgaussian() and cogmod_geg() are not in either registry - they are
    # plain families with an lpdf generator each - so their shared prelude is
    # named here. The GEG needs the ex-Gaussian's log CDF inside its own
    # density, not just for cens().
    ".EXGAUSSIAN_STAN_PRELUDE"
  )
  # One level down: cogmod_log_Phi() is pasted into the front of more than one
  # prelude (the LogNormal's, the Wald's, the LBA's, the RDM's and the
  # ex-Gaussian's), so once the family preludes are deduplicated it is still
  # defined once per family that carries it. It goes last, after the family
  # preludes have been stripped, so that the copy kept is the one inside the
  # first surviving prelude - and so that a prelude is still matchable in full
  # while its own copy is intact.
  named <- c(named, ".LOG_PHI_STAN_PRELUDE")
  for (nm in unique(named[nzchar(named)])) {
    pre <- getFromNamespace(nm, "cogmod")
    hits <- which(vapply(codes, grepl, logical(1), pattern = pre, fixed = TRUE))
    for (i in hits[-1]) codes[i] <- sub(pre, "", codes[i], fixed = TRUE)
  }
  codes
}

.stan_model <- function() {
  mod <- .stan_cached()
  if (!is.null(mod)) return(mod)

  code <- paste0(
    "functions {\n",
    paste(.stan_dedupe_preludes(
      vapply(.STAN_LPDF_FAMILIES, .stan_lpdf_code, character(1))
    ), collapse = "\n"),
    "\n}"
  )
  file <- cmdstanr::write_stan_file(code)
  mod <- cmdstanr::cmdstan_model(file)
  # Belt and braces: should the executable ever survive from an earlier session
  # in the same tempdir, the model comes back pre-compiled and cannot export its
  # functions. Rebuilding is the only way out, and it costs nothing in the
  # normal case because it never runs there.
  ok <- tryCatch({ mod$expose_functions(); TRUE }, error = function(e) FALSE)
  if (!ok) {
    mod <- cmdstanr::cmdstan_model(file, force_recompile = TRUE)
    mod$expose_functions()
  }
  options(cogmod.test.stan_model = mod)
  mod
}

# The exposed Stan lpdf for `name`, from the shared model. Skips the calling
# test when cmdstanr is not installed, so the callers do not each have to.
stan_fun <- function(name, suffix = "_lpdf") {
  testthat::skip_if_not_installed("cmdstanr")
  fun <- .stan_model()$functions[[paste0(name, suffix)]]
  if (is.null(fun)) {
    stop("'", name, suffix, "' is not in the shared Stan model. Add '", name,
         "' to .STAN_LPDF_FAMILIES in helper-stan.R.", call. = FALSE)
  }
  fun
}

Try the cogmod package in your browser

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

cogmod documentation built on Nov. 28, 2026, 1:08 a.m.