R/stanmodels.R

Defines functions compile_model_file

# This file is only intended to be used during the installation process
# nocov start

# Locate the source directory.
#
MODELS_HOME <- "src"
if (!file.exists(MODELS_HOME)) MODELS_HOME <- sub("R$", "src", getwd())

# Find the Stan model files
#
stan_files <- dir(file.path(MODELS_HOME, "stan_files"),
                  pattern = "stan$", full.names = TRUE)

# Compile a stan model file
#
compile_model_file <- function(f) {
  model_cppname <- sub("\\.stan$", "", basename(f))
  stanfit <- rstan::stanc(f, allow_undefined = TRUE,
                          obfuscate_model_name = FALSE)
  stanfit$model_cpp <- list(model_cppname = stanfit$model_name,
                            model_cppcode = stanfit$cppcode)
  return(do.call(methods::new, args = c(stanfit[-(1:3)], Class = "stanmodel",
                 mk_cppmodule = function(x) get(paste0("model_", model_cppname)))))
}

# Compile the models
#
stanmodels <- lapply(stan_files, compile_model_file)
names(stanmodels) <- sub("\\.stan$", "", basename(stan_files))

# Clean up
rm(MODELS_HOME)
# nocov end
JohnReid/DeLorean documentation built on Sept. 27, 2021, 5:45 a.m.