Skip to content

Commit

Permalink
simplify logic
Browse files Browse the repository at this point in the history
  • Loading branch information
gravesti committed Dec 4, 2024
1 parent 369e732 commit b36123d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 19 deletions.
20 changes: 8 additions & 12 deletions R/utilities.R
Original file line number Diff line number Diff line change
Expand Up @@ -550,12 +550,8 @@ get_session_hash <- function() {
return(hash)
}

tidy_up_models <- function(cache_dir, keep_hash = NULL) {
clear_model_cache <- function(cache_dir = getOption("rbmi.cache_dir")) {
files <- list.files(cache_dir, pattern = "(MMRM_).*(\\.stan|\\.rds)", full.names = TRUE)
if (!is.null(keep_hash)) {
keep_pattern <- paste0("(MMRM_", keep_hash, ")(\\.stan|\\.rds)")
files <- grep(keep_pattern, files, invert = TRUE, value = TRUE)
}
unlink(files)
}

Expand All @@ -576,15 +572,15 @@ get_stan_model <- function() {
}
cache_dir <- getOption("rbmi.cache_dir")
dir.create(cache_dir, showWarnings = FALSE, recursive = TRUE)
session_hash <- get_session_hash()
file_loc_cache <- file.path(cache_dir, paste0("MMRM_", session_hash, ".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)
tidy_up_models(cache_dir, keep_hash = session_hash)

rstan::stan_model(
file = file_loc_cache,
file = model_file,
auto_write = TRUE,
model_name = "rbmi_mmrm"
)
Expand Down
9 changes: 2 additions & 7 deletions tests/testthat/test-utilities.R
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ test_that("Stack", {
})


test_that("tidy_up_models", {
test_that("clear_model_cache", {
td <- tempdir()
files <- c(
file.path(td, "MMRM_123.rds"),
Expand All @@ -253,12 +253,7 @@ test_that("tidy_up_models", {
file.path(td, "MMRM_456.log")
)
expect_equal(file.create(files), rep(TRUE, 5))
tidy_up_models(td, keep_hash = "123")
expect_equal(
file.exists(files),
c(TRUE, TRUE, FALSE, FALSE, TRUE)
)
tidy_up_models(td)
clear_model_cache(td)
expect_equal(
file.exists(files),
c(FALSE, FALSE, FALSE, FALSE, TRUE)
Expand Down

0 comments on commit b36123d

Please sign in to comment.