Skip to content

Commit

Permalink
Merge pull request #459 from insightsengineering/458-cran-crash
Browse files Browse the repository at this point in the history
458 cran crash
  • Loading branch information
gravesti authored Dec 5, 2024
2 parents f28ea91 + b36123d commit 78a74f2
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 5 deletions.
35 changes: 30 additions & 5 deletions R/utilities.R
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,29 @@ ensure_rstan <- function() {
}
}

#' Get session hash
#'
#' Gets a unique string based on the current R version and relevant packages.
#' @keywords internal
get_session_hash <- function() {
pkg_versions <- vapply(
sessionInfo(c("rbmi", "rstan", "Rcpp", "RcppEigen", "BH"))[["otherPkgs"]],
function(x) x[["Version"]],
character(1L)
)
version_string <- paste0(R.version.string, paste0(names(pkg_versions), pkg_versions, collapse = ":"))
temp_file <- tempfile()
writeLines(version_string, temp_file)
hash <- tools::md5sum(temp_file)
unlist(temp_file)
return(hash)
}

clear_model_cache <- function(cache_dir = getOption("rbmi.cache_dir")) {
files <- list.files(cache_dir, pattern = "(MMRM_).*(\\.stan|\\.rds)", full.names = TRUE)
unlink(files)
}

#' Get Compiled Stan Object
#'
#' Gets a compiled Stan object that can be used with `rstan::sampling()`
Expand All @@ -549,13 +572,15 @@ get_stan_model <- function() {
}
cache_dir <- getOption("rbmi.cache_dir")
dir.create(cache_dir, showWarnings = FALSE, recursive = TRUE)
file_loc_cache <- file.path(cache_dir, "MMRM.stan")
if (!file.exists(file_loc_cache)) {
message("Compiling Stan model please wait...")
model_file <- file.path(cache_dir, paste0("MMRM_", get_session_hash(), ".stan"))

if (!file.exists(model_file)) {
clear_model_cache()
file.copy(file_loc, model_file, overwrite = TRUE)
}
file.copy(file_loc, file_loc_cache, overwrite = TRUE)

rstan::stan_model(
file = file_loc_cache,
file = model_file,
auto_write = TRUE,
model_name = "rbmi_mmrm"
)
Expand Down
12 changes: 12 additions & 0 deletions man/get_session_hash.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions tests/testthat/test-utilities.R
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,22 @@ test_that("Stack", {
expect_equal(mstack$pop(3), list(7))
expect_error(mstack$pop(1), "items to return")
})


test_that("clear_model_cache", {
td <- tempdir()
files <- c(
file.path(td, "MMRM_123.rds"),
file.path(td, "MMRM_123.stan"),
file.path(td, "MMRM_456.stan"),
file.path(td, "MMRM_456.rds"),
file.path(td, "MMRM_456.log")
)
expect_equal(file.create(files), rep(TRUE, 5))
clear_model_cache(td)
expect_equal(
file.exists(files),
c(FALSE, FALSE, FALSE, FALSE, TRUE)
)
file.remove(files[5])
})

0 comments on commit 78a74f2

Please sign in to comment.