From b36123d72d09d83a7421bc6529e52597561706fd Mon Sep 17 00:00:00 2001 From: Isaac Gravestock <83659704+gravesti@users.noreply.github.com> Date: Wed, 4 Dec 2024 11:30:43 +0100 Subject: [PATCH] simplify logic --- R/utilities.R | 20 ++++++++------------ tests/testthat/test-utilities.R | 9 ++------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/R/utilities.R b/R/utilities.R index 51dba07d..87ae84ca 100644 --- a/R/utilities.R +++ b/R/utilities.R @@ -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) } @@ -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" ) diff --git a/tests/testthat/test-utilities.R b/tests/testthat/test-utilities.R index 7534a411..39e97cc3 100644 --- a/tests/testthat/test-utilities.R +++ b/tests/testthat/test-utilities.R @@ -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"), @@ -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)