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
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: luna
Type: Package
Title: Light-weight Universal NLME Admininstrator
Version: 0.2.3
Version: 0.2.4
Author: Ron Keizer
Maintainer: Ron Keizer <ron@insight-rx.com>
Description: Organizes model development workflows in NONMEM and nlmixr2. The
Expand Down Expand Up @@ -48,7 +48,7 @@ License: MIT + file LICENSE
URL: https://github.com/InsightRX/uno, https://insightrx.github.io/uno/, https://insightrx.github.io/luna/
LazyData: TRUE
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.3.3
Config/testthat/edition: 3
Encoding: UTF-8
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.0
23 changes: 19 additions & 4 deletions R/luna_clone.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
#' @inheritParams luna_run
#' @param new_id new run id
#' @param update_inits use the final estimates from the source model
#' as initial estimates for the cloned model. Default `FALSE`
#' as initial estimates for the cloned model. Default `FALSE`. This requires
#' the source model to have been run, i.e. `<folder>/<id>/run.mod` and its
#' results must exist. Without `update_inits`, the model file `<folder>/<id>.mod`
#' is copied.
#'
#' @export
#'
Expand All @@ -17,11 +20,21 @@ luna_clone <- function(
) {
id <- validate_id(id)
new_id <- validate_id(new_id)
is_luna_cache_available(abort = TRUE)
if(is.null(folder)) {
folder <- .luna_cache$get("project")$metadata$folder
}
old_file <- file.path(folder, paste0(id, ".mod"))
new_file <- file.path(folder, paste0(new_id, ".mod"))
if(update_inits) {
## final estimates are read from the run folder created by luna_run()
source_file <- file.path(folder, id, "run.mod")
} else {
source_file <- old_file
}
if(!file.exists(source_file)) {
cli::cli_abort("Source model file {source_file} not found.")
}
if(file.exists(new_file)) {
if(force) {
if(verbose) {
Expand All @@ -35,18 +48,21 @@ luna_clone <- function(
cli::cli_alert_info("Cloning model {id} to {new_id}")
}
if(!update_inits) {
file.copy(
copied <- file.copy(
old_file,
new_file,
overwrite = TRUE
)
if(!copied) {
cli::cli_abort("Could not copy {old_file} to {new_file}.")
}
} else {
cli::cli_alert_info("Updating parameters in cloned model")
## TODO: this currently doesn't work, due to a Pharmpy bug.
## Therefore, we'll be using PsN for now
pharmpy_works <- FALSE
if(pharmpy_works) {
model <- pharmr::read_model(old_file)
model <- pharmr::read_model(source_file)
info <- luna_info(id)
parameters <- replace_list_elements(
model$parameters$inits,
Expand Down Expand Up @@ -74,7 +90,6 @@ luna_clone <- function(
if(verbose) {
cli::cli_alert_info("Updating project YAML")
}
is_luna_cache_available(abort = TRUE)
## make sure we're up to date
name <- .luna_cache$get("project")$metadata$name
folder <- .luna_cache$get("project")$metadata$folder
Expand Down
11 changes: 8 additions & 3 deletions R/luna_gof.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ luna_gof <- function(
verbose = TRUE
) {

residual <- match.arg(residual)
residual_label <- c(
CWRES = "Conditional weighted residual (CWRES)",
NPDE = "Normalized prediction distribution error (NPDE)"
)[[residual]]
tab <- get_table_for_plots(
id = id,
folder = folder,
Expand All @@ -40,19 +45,19 @@ luna_gof <- function(
ggplot2::xlab("Prediction") +
ggplot2::ylab("Observation (DV)") +
theme()
## CWRES vs TIME / PRED
## Residual (CWRES/NPDE) vs TIME / PRED
p2 <- tab |>
dplyr::filter(MDV == 0) |>
tidyr::pivot_longer(cols = c(TIME, PRED)) |>
ggplot2::ggplot(
ggplot2::aes(x = value, y = CWRES)
ggplot2::aes(x = value, y = .data[[residual]])
) +
ggplot2::geom_point() +
ggplot2::geom_smooth(method = smooth_method, formula = y ~ x) +
ggplot2::geom_hline(yintercept = 0, linetype = "dotted") +
ggplot2::facet_wrap(~name, scales = "free") +
ggplot2::xlab("") +
ggplot2::ylab("Conditional weighted residual (CWRES)") +
ggplot2::ylab(residual_label) +
theme()

## Add log event
Expand Down
4 changes: 2 additions & 2 deletions R/luna_help.R
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ luna_help <- function(
is_luna_cache_available(abort = TRUE)
if(is.null(prompt)) {
event <- log_get_last_event()
if(verbose)
cli::cli_alert_info("Getting help on {event$event} using {model}")
if(is.null(event)) {
cli::cli_abort("No recent event found, please call `luna_help()` with a question.")
}
if(verbose)
cli::cli_alert_info("Getting help on {event$event} using {model}")
}
chat <- ellmer::chat_openai(
system_prompt = paste0(
Expand Down
4 changes: 2 additions & 2 deletions R/luna_list.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ luna_list <- function(
project <- .luna_cache$get("project")
out <- runs_as_table(project, raw = raw)

## select columns
if(!raw) {
## select columns (an empty project has no columns to select from)
if(!raw && nrow(out) > 0) {
cols <- config$general$list$columns
if(!is.null(cols)) {
sel_cols <- names(cols)[unlist(cols)]
Expand Down
6 changes: 5 additions & 1 deletion R/luna_log.R
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,9 @@ log_add <- function(
#' Get last event from log, as list object
#'
log_get_last_event <- function() {
.luna_cache$get("log")[[length(.luna_cache$get("log"))]]
luna_log <- .luna_cache$get("log", missing = NULL)
if(length(luna_log) == 0) {
return(NULL)
}
luna_log[[length(luna_log)]]
}
26 changes: 12 additions & 14 deletions R/luna_new_project.R
Original file line number Diff line number Diff line change
Expand Up @@ -57,26 +57,24 @@ luna_new_project <- function(

# create a project object from template
if(!is.null(template)) {
project <- new_project_from_template(template)
project$metadata <- list(
name = name,
folder = folder
)
project_yaml <- new_project_from_template(template)$yaml
} else {
project <- list(
yaml = list(
project = list(
)
),
metadata = list(
name = name,
folder = folder
project_yaml <- list(
project = list(
)
)
}
project <- list(
yaml = project_yaml,
metadata = list(
name = name,
folder = folder
)
)
project$yaml$project$description <- description

## Import models, if present in folder and requested
models <- character(0)
if(import_models) {
models <- stringr::str_replace_all(
dir(folder, pattern = "\\.mod$"),
Expand All @@ -86,7 +84,7 @@ luna_new_project <- function(
stringr::str_sort(numeric = TRUE)
project$yaml$runs <- list()
}
for(i in 1:length(models)) {
for(i in seq_along(models)) {
model_file <- file.path(folder, paste0(models[i], ".mod"))
if(file.exists(model_file)) {
project$yaml$runs[[i]] <- list(
Expand Down
16 changes: 9 additions & 7 deletions R/luna_note.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ luna_note <- function(
return(run[[element]])
} else { # add or clear notes/tags

if(is.null(run)) {
cli::cli_abort("Run {id} not found in project {name}.")
}

## Clear existing notes
if(clear) {
run[[element]] <- NULL
Expand All @@ -59,13 +63,11 @@ luna_note <- function(
run[[element]],
note
)
if(!is.null(note)) {
project$yaml$runs <- insert_entry(
x = project$yaml$runs,
id = id,
entry = run
)
}
project$yaml$runs <- insert_entry(
x = project$yaml$runs,
id = id,
entry = run
)

## Update cache
.luna_cache$set("project", project)
Expand Down
6 changes: 5 additions & 1 deletion R/luna_run.R
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ luna_run <- function(
}
console <- ifelse0(config$tools$modelfit$console, TRUE)
if(is.null(nmfe)) {
nmfe <- ifelse0(config$tools$modelfit$nmfe, config$tools$nonmem$nmfe)
nmfe <- ifelse0(
config$tools$modelfit$nmfe,
config$tools$nonmem$nmfe,
allow_null = TRUE
)
}
if(method == "nmfe") {
if(is.null(nmfe) || identical(trimws(nmfe), "")) {
Expand Down
5 changes: 3 additions & 2 deletions R/luna_tables.R
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ luna_tables <- function(
folder,
filename = file.path(id, paste0("run", ".mod")),
fallback = paste0(id, ".mod"),
verbose = FALSE
verbose = FALSE,
abort = FALSE
)
if(! file.exists(model_file)) {
if(is.null(model_file)) {
cli::cli_abort("Model file not found in run folder")
}
model <- pharmr::read_model(model_file)
Expand Down
13 changes: 6 additions & 7 deletions R/misc.R
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ find_file_with_fallback <- function(folder, filename, fallback, verbose = TRUE,
f <- file.path(folder, fallback)
if(! file.exists(f)) {
if(abort) {
if(verbose)
cli::cli_abort("An expected file was not found.")
cli::cli_abort("An expected file was not found.")
} else {
return(NULL)
}
Expand Down Expand Up @@ -160,14 +159,14 @@ get_flag_from_config <- function(
default = FALSE,
config = NULL
) {
out <- default
if(is.null(config)) {
config <- get_luna_config()
}
out <- isTRUE(
purrr::pluck(config, !!!flag)
)
out
value <- purrr::pluck(config, !!!flag)
if(is.null(value)) {
return(default)
}
isTRUE(value)
}

#' Replace elements in a list, based on elements in a second list
Expand Down
2 changes: 1 addition & 1 deletion R/runs_as_table.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ runs_as_table <- function(

## Print a table of models and their descriptions
models <- x$yaml$runs
model_table <- data.frame()
full_table <- data.frame()
if(length(models) > 0) {
timestamps <- .luna_cache$get("timestamps")
model_table <- data.frame(
Expand Down
10 changes: 4 additions & 6 deletions R/update_cache.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ update_cache <- function(
}

## Folders
dir_list <- stringr::str_replace_all(
list.dirs(folder, recursive = FALSE),
paste0(folder, "[\\/]"),
""
)
dir_list <- basename(list.dirs(folder, recursive = FALSE))
for(d in dir_list) {
timestamps$folders[[d]] <- get_time_last_updated_folder(d)
timestamps$folders[[d]] <- get_time_last_updated_folder(
file.path(folder, d)
)
}

if(verbose)
Expand Down
5 changes: 4 additions & 1 deletion man/luna_clone.Rd

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

25 changes: 25 additions & 0 deletions tests/testthat/test-cache.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,28 @@ test_that("update_cache records folder timestamps", {
expect_true("run1" %in% names(ts$folders))
expect_match(ts$folders$run1, "^\\d{4}-")
})

test_that("update_cache records folder timestamps outside the project folder", {
dir <- local_luna_project()
dir.create(file.path(dir, "run1"))
writeLines("x", file.path(dir, "run1", "out.txt"))
withr::local_dir(tempdir())
update_cache(.luna_cache$get("project"))
ts <- .luna_cache$get("timestamps")
expect_match(ts$folders$run1, "^\\d{4}-")
})

test_that("update_cache handles regex special characters in folder path", {
local_luna_home()
local_no_luna_cache()
parent <- normalizePath(withr::local_tempdir())
dir <- file.path(parent, "proj (v1.0)+")
dir.create(dir)
dir.create(file.path(dir, "run1"))
writeLines("x", file.path(dir, "run1", "out.txt"))
yaml::write_yaml(list(project = list(description = "d")), file.path(dir, "p.yaml"))
suppressMessages(luna_load_project(name = "p", folder = dir, verbose = FALSE))
ts <- .luna_cache$get("timestamps")
expect_true("run1" %in% names(ts$folders))
expect_match(ts$folders$run1, "^\\d{4}-")
})
25 changes: 25 additions & 0 deletions tests/testthat/test-luna_clone.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ test_that("luna_clone overwrites with force and warns when run already in YAML",

test_that("luna_clone with update_inits calls PsN update_inits", {
dir <- local_luna_project()
dir.create(file.path(dir, "run1"))
write_nm_model(file.path(dir, "run1", "run.mod"))
mockery::stub(luna_clone, "luna_edit", function(id) NULL)
psn <- mockery::mock(NULL)
mockery::stub(luna_clone, "pharmr.extra::call_psn", psn)
Expand All @@ -59,3 +61,26 @@ test_that("luna_clone with update_inits calls PsN update_inits", {
yml <- yaml::read_yaml(file.path(dir, "testproj.yaml"))
expect_equal(yml$runs[[3]]$id, "run4")
})

test_that("luna_clone aborts when source model is missing", {
dir <- local_luna_project()
mockery::stub(luna_clone, "luna_edit", function(id) NULL)
expect_error(luna_clone("run9", "run10"), "not found")
expect_false(file.exists(file.path(dir, "run10.mod")))
yml <- yaml::read_yaml(file.path(dir, "testproj.yaml"))
expect_length(yml$runs, 2)
})

test_that("luna_clone with update_inits aborts when source run folder is missing", {
dir <- local_luna_project()
mockery::stub(luna_clone, "luna_edit", function(id) NULL)
psn <- mockery::mock(NULL)
mockery::stub(luna_clone, "call_psn", psn)
expect_error(luna_clone("run1", "run4", update_inits = TRUE), "run.mod not found")
mockery::expect_called(psn, 0)
})

test_that("luna_clone aborts without luna cache", {
local_no_luna_cache()
expect_error(luna_clone("run1", "run2"), "Luna cache not found")
})
Loading
Loading