Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions R/misc.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions R/model_from_api.R
Original file line number Diff line number Diff line change
Expand Up @@ -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()]
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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"),
Expand Down
16 changes: 14 additions & 2 deletions R/new_ode_model.R
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()))
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion inst/template/R/model.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
3 changes: 3 additions & 0 deletions man/model_from_api.Rd

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

5 changes: 4 additions & 1 deletion man/new_ode_model.Rd

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

226 changes: 226 additions & 0 deletions tests/testthat/test_ferx.R
Original file line number Diff line number Diff line change
@@ -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"))
})
Loading