diff --git a/R/misc.R b/R/misc.R index 540defe4..933a1d75 100644 --- a/R/misc.R +++ b/R/misc.R @@ -55,6 +55,20 @@ search_replace_in_file <- function(files = c(), find = NULL, replacement = NULL) } +#' Convert a character vector into an R string literal +#' +#' Collapses `x` using newlines and deparses it, so that quotes and newlines +#' are escaped. Backslashes are escaped once more so the result can be used +#' as a `replacement` in [search_replace_in_file()] (which uses `gsub()`). +#' +#' @param x character vector +#' @return a single string containing R code for a string literal +#' @noRd +string_to_R_literal <- function(x) { + x <- paste0(deparse(paste(x, collapse = "\n")), collapse = "") + gsub("\\\\", "\\\\\\\\", x) +} + #' Put vector values in quotes #' #' @param x vector of string / numeric diff --git a/R/model_from_api.R b/R/model_from_api.R index 081444a7..553cb1fc 100644 --- a/R/model_from_api.R +++ b/R/model_from_api.R @@ -8,6 +8,7 @@ #' @param to_package compile to package? #' @param force force install even if same version number of model already installed. #' @param install_all force install all, even if model inactive +#' @param ferx URL or file path to FeRx file #' @param ... arguments passed to `new_ode_model()` function #' @export #' @return Model object created with [PKPDsim::new_ode_model()] @@ -20,6 +21,7 @@ model_from_api <- function(url, to_package = FALSE, force = FALSE, install_all = FALSE, + ferx = NULL, ...) { def <- read_model_json(url) if(verbose) { @@ -41,6 +43,9 @@ model_from_api <- function(url, if(!is.null(nonmem) && !is.null(def$implementations$nonmem)) { nonmem <- paste(readLines(nonmem), collapse="\n") } + if(!is.null(ferx) && !is.null(def$implementations$ferx)) { + ferx <- paste(readLines(ferx), collapse="\n") + } if(is.null(def$comments)) def$comments <- "" mod <- NULL if(isTRUE(def$build) || install_all) { @@ -85,6 +90,7 @@ model_from_api <- function(url, state_init = def$state_init, verbose = verbose, nonmem = nonmem, + ferx = ferx, int_step_size = def$simulation$int_step_size, comments = stringr::str_replace_all(def$comments, '\\"', ""), version = ifelse(!is.null(def$version), def$version, "0.1.0"), diff --git a/R/new_ode_model.R b/R/new_ode_model.R index 2a852c7f..b26349ee 100644 --- a/R/new_ode_model.R +++ b/R/new_ode_model.R @@ -45,6 +45,7 @@ #' @param definition optional, filename for the JSON file the full definition #' for the model. The definition file will be stored as `definition.json` in the #' resulting package. +#' @param ferx add FeRx code as attribute to model object #' @export #' @return If package name is NULL, returns the model object. Otherwise has no #' return value. @@ -88,7 +89,8 @@ new_ode_model <- function (model = NULL, comments = NULL, version = "0.1.0", quiet = "", - definition = NULL + definition = NULL, + ferx = NULL ) { if (is.null(model) & is.null(code) & is.null(file) & is.null(func)) { stop(paste0("Either a model name (from the PKPDsim library), ODE code, an R function, or a file containing code for the ODE system have to be supplied to this function. The following models are available:\n ", model_library())) @@ -287,6 +289,12 @@ new_ode_model <- function (model = NULL, if(!is.null(int_step_size)) { attr(sim_out, "int_step_size") <- int_step_size } + if(!is.null(nonmem)) { + attr(sim_out, "nonmem") <- paste(nonmem, collapse = "\n") + } + if(!is.null(ferx)) { + attr(sim_out, "ferx") <- paste(ferx, collapse = "\n") + } class(sim_out) <- c("PKPDsim", class(sim_out)) return(sim_out) } @@ -346,6 +354,9 @@ new_ode_model <- function (model = NULL, state_init <- add_quotes(state_init) } if(is.null(nonmem) || length(nonmem) == 0) { nonmem <- "NULL" } + nonmem <- string_to_R_literal(nonmem) + if(is.null(ferx) || length(ferx) == 0) { ferx <- "NULL" } + ferx <- string_to_R_literal(ferx) if(is.null(int_step_size)) { int_step_size <- "NULL" } pars <- vector_to_R_code(reqd) covs <- vector_to_R_code(cov_names) @@ -380,7 +391,8 @@ new_ode_model <- function (model = NULL, "\\[CMT_MAPPING\\]", paste0(deparse(cmt_mapping), collapse = ""), "\\[INT_STEP_SIZE\\]", as.character(int_step_size), "\\[COMMENTS\\]", paste0("\n", as.character(paste0(paste0(" - ", comments), collapse = "\n"))), - "\\[NONMEM\\]", as.character(nonmem) + "\\[NONMEM\\]", nonmem, + "\\[FERX\\]", ferx ), ncol=2, byrow=TRUE) if(verbose) { print(repl) diff --git a/inst/template/R/model.R b/inst/template/R/model.R index 7220675c..964be3eb 100644 --- a/inst/template/R/model.R +++ b/inst/template/R/model.R @@ -27,7 +27,8 @@ model <- function(mod = NULL) { attr(ret, "iov") <- list([IOV]) attr(ret, "development") <- list([DEVELOPMENT]) attr(ret, "cmt_mapping") <- [CMT_MAPPING] - attr(ret, "nonmem") <- "[NONMEM]" + attr(ret, "nonmem") <- [NONMEM] + attr(ret, "ferx") <- [FERX] attr(ret, "comments") <- "[COMMENTS]" attr(ret, "version") <- "[VERSION]" class(ret) <- c("PKPDsim", class(ret)) diff --git a/man/model_from_api.Rd b/man/model_from_api.Rd index aad78a8d..ed6ffda5 100644 --- a/man/model_from_api.Rd +++ b/man/model_from_api.Rd @@ -13,6 +13,7 @@ model_from_api( to_package = FALSE, force = FALSE, install_all = FALSE, + ferx = NULL, ... ) } @@ -33,6 +34,8 @@ model_from_api( \item{install_all}{force install all, even if model inactive} +\item{ferx}{URL or file path to FeRx file} + \item{...}{arguments passed to \code{new_ode_model()} function} } \value{ diff --git a/man/new_ode_model.Rd b/man/new_ode_model.Rd index f40ff6d7..37c263b5 100644 --- a/man/new_ode_model.Rd +++ b/man/new_ode_model.Rd @@ -45,7 +45,8 @@ new_ode_model( comments = NULL, version = "0.1.0", quiet = "", - definition = NULL + definition = NULL, + ferx = NULL ) } \arguments{ @@ -134,6 +135,8 @@ TRUE captures the output and saves as a file.} \item{definition}{optional, filename for the JSON file the full definition for the model. The definition file will be stored as \code{definition.json} in the resulting package.} + +\item{ferx}{add FeRx code as attribute to model object} } \value{ If package name is NULL, returns the model object. Otherwise has no diff --git a/tests/testthat/test_ferx.R b/tests/testthat/test_ferx.R new file mode 100644 index 00000000..7021765a --- /dev/null +++ b/tests/testthat/test_ferx.R @@ -0,0 +1,226 @@ +# Helper: generate (but do not install) a model package, and return the path +# to the generated R/model.R file. +generate_model_package <- function(package, ferx = NULL, nonmem = NULL) { + folder <- tempfile("ferx_pkg") + dir.create(folder) + # install = FALSE runs `R CMD build`, which writes a tarball to the working + # directory, so build from within the temp folder. + old_wd <- setwd(folder) + on.exit(setwd(old_wd), add = TRUE) + suppressMessages( + new_ode_model( + code = "dAdt[0] = -(CL/V)*A[0];", + obs = list(cmt = 1, scale = "V"), + dose = list(cmt = 1, bioav = 1), + parameters = list(CL = 5, V = 50), + as_is = TRUE, + package = package, + folder = folder, + install = FALSE, + nonmem = nonmem, + ferx = ferx, + quiet = FALSE + ) + ) + file.path(folder, package, "R", "model.R") +} + +# Helper: evaluate the generated model.R and return the model attributes, +# without needing to compile/install the package. `model()` looks up the +# compiled simulation function in the attached package, so stub that lookup. +get_generated_attributes <- function(model_file) { + env <- new.env() + env$as.environment <- function(...) emptyenv() + env$get <- function(...) function() NULL + eval(parse(model_file), envir = env) + attributes(env$model()) +} + +test_that("ferx code is stored as model attribute in generated package", { + skip_on_cran() + ferx_code <- "model 1cmt_iv\n CL = THETA(1)\n V = THETA(2)\nend" + model_file <- generate_model_package("ferxtest1", ferx = ferx_code) + expect_true(file.exists(model_file)) + model_txt <- readLines(model_file) + expect_false(any(grepl("[FERX]", model_txt, fixed = TRUE))) + attrs <- get_generated_attributes(model_file) + expect_equal(attrs$ferx, ferx_code) +}) + +test_that("ferx attribute defaults to 'NULL' when not supplied", { + skip_on_cran() + model_file <- generate_model_package("ferxtest2") + attrs <- get_generated_attributes(model_file) + expect_equal(attrs$ferx, "NULL") + expect_equal(attrs$nonmem, "NULL") +}) + +test_that("ferx attribute defaults to 'NULL' when empty vector supplied", { + skip_on_cran() + model_file <- generate_model_package("ferxtest3", ferx = character(0)) + attrs <- get_generated_attributes(model_file) + expect_equal(attrs$ferx, "NULL") +}) + +test_that("ferx and nonmem attributes are independent", { + skip_on_cran() + model_file <- generate_model_package( + "ferxtest4", + nonmem = "$PROB nonmem code", + ferx = "ferx code" + ) + attrs <- get_generated_attributes(model_file) + expect_equal(attrs$nonmem, "$PROB nonmem code") + expect_equal(attrs$ferx, "ferx code") +}) + +test_that("model_from_api reads ferx file when implementation is defined", { + def_file <- tempfile(fileext = ".json5") + ferx_file <- tempfile(fileext = ".ferx") + writeLines(c("line 1", "line 2"), ferx_file) + def <- read_model_json(test_path("sample_json", "test_1cmt_iv.json5")) + def$implementations <- list(ferx = TRUE) + writeLines(jsonlite::toJSON(def, auto_unbox = TRUE), def_file) + + captured <- NULL + local_mocked_bindings( + new_ode_model = function(...) { + captured <<- list(...) + "model" + } + ) + model_from_api( + url = def_file, + model = "test_1cmt_iv", + ferx = ferx_file, + verbose = FALSE, + force = TRUE + ) + expect_equal(captured$ferx, "line 1\nline 2") + expect_null(captured$nonmem) +}) + +test_that("model_from_api passes NULL ferx when no ferx file supplied", { + def_file <- tempfile(fileext = ".json5") + def <- read_model_json(test_path("sample_json", "test_1cmt_iv.json5")) + def$implementations <- list(ferx = TRUE) + writeLines(jsonlite::toJSON(def, auto_unbox = TRUE), def_file) + + captured <- NULL + local_mocked_bindings( + new_ode_model = function(...) { + captured <<- list(...) + "model" + } + ) + model_from_api( + url = def_file, + model = "test_1cmt_iv", + verbose = FALSE, + force = TRUE + ) + expect_true("ferx" %in% names(captured)) + expect_null(captured$ferx) +}) + +test_that("ferx attribute available on installed model package", { + skip_on_cran() + instloc <- tempfile("package") + srcloc <- file.path(instloc, "src") + dir.create(instloc) + dir.create(srcloc) + on.exit(unlink(instloc, recursive = TRUE), add = TRUE) + ferx_code <- "ferx model code" + suppressWarnings( + suppressMessages( + new_ode_model( + code = "dAdt[0] = -(CL/V)*A[0];", + obs = list(cmt = 1, scale = "V"), + dose = list(cmt = 1, bioav = 1), + parameters = list(CL = 5, V = 50), + as_is = TRUE, + package = "ferxinstalltest", + folder = srcloc, + lib_location = instloc, + ferx = ferx_code, + quiet = NULL + ) + ) + ) + expect_true("ferxinstalltest" %in% installed.packages(lib.loc = instloc)) + suppressMessages(require(ferxinstalltest, lib.loc = instloc)) + on.exit( + detach("package:ferxinstalltest", unload = TRUE), + add = TRUE, + after = FALSE + ) + mod <- ferxinstalltest::model() + expect_equal(attr(mod, "ferx"), ferx_code) + expect_equal(attr(mod, "nonmem"), "NULL") +}) + +test_that("ferx code with quotes, backslashes and newlines round-trips", { + skip_on_cran() + ferx_code <- paste( + 'label = "central"', + "path = 'C:\\models\\1cmt'", + "regex = \\1 and \\\\", + sep = "\n" + ) + model_file <- generate_model_package("ferxtest5", ferx = ferx_code) + expect_silent(parse(model_file)) + attrs <- get_generated_attributes(model_file) + expect_equal(attrs$ferx, ferx_code) +}) + +test_that("ferx code is stored as attribute on directly compiled models", { + skip_on_cran() + ferx_code <- 'model "1cmt"\nend' + mod <- new_ode_model( + code = "dAdt[0] = -(CL/V)*A[0];", + obs = list(cmt = 1, scale = "V"), + parameters = list(CL = 5, V = 50), + ferx = ferx_code + ) + expect_equal(attr(mod, "ferx"), ferx_code) + expect_null(attr(mod_1cmt_iv, "ferx")) +}) + +test_that("ferx argument does not shift existing positional arguments", { + args_api <- names(formals(model_from_api)) + expect_equal( + args_api[1:8], + c("url", "model", "nonmem", "verbose", "get_definition", + "to_package", "force", "install_all") + ) + args_ode <- names(formals(new_ode_model)) + expect_equal(args_ode[length(args_ode)], "ferx") + expect_equal(args_ode[length(args_ode) - 1], "definition") +}) + +test_that("nonmem code with quotes, backslashes and newlines round-trips", { + skip_on_cran() + nonmem_code <- paste( + "$PROB 'one cmt'", + '$INPUT ID TIME DV ; "quoted"', + "$DATA C:\\data\\nm.csv \\1", + sep = "\n" + ) + model_file <- generate_model_package("ferxtest6", nonmem = nonmem_code) + expect_silent(parse(model_file)) + attrs <- get_generated_attributes(model_file) + expect_equal(attrs$nonmem, nonmem_code) +}) + +test_that("nonmem code is stored as attribute on directly compiled models", { + skip_on_cran() + nonmem_code <- '$PROB "1cmt"\n$PK' + mod <- new_ode_model( + code = "dAdt[0] = -(CL/V)*A[0];", + obs = list(cmt = 1, scale = "V"), + parameters = list(CL = 5, V = 50), + nonmem = nonmem_code + ) + expect_equal(attr(mod, "nonmem"), nonmem_code) + expect_null(attr(mod_1cmt_iv, "nonmem")) +})