diff --git a/DESCRIPTION b/DESCRIPTION index 8c8a3a9..542b6d8 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: irxforge Title: Forging data for pharmacometric analyses -Version: 0.0.0.9048 +Version: 0.0.0.9049 Authors@R: c( person("Ron", "Keizer", email = "ron@insight-rx.com", role = c("cre", "aut")), person("Michael", "McCarthy", email = "michael.mccarthy@insight-rx.com", role = "ctb"), diff --git a/NEWS.md b/NEWS.md index 48e75b2..9daca81 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,17 @@ # irxforge (development version) +* `anonymize_dataset()`: a covariate that the model references under a spelling + that differs only by case from its data column (e.g. `CONC0` for a `conc0` + column) is now bridged with an added `[data]` rename (`CONC0 = conc0`) in the + simulation copy of `model_file`, since FeRx matches covariate names + case-sensitively. The model's covariate references are checked before any + covariate is sampled: a reference that matches several columns + case-insensitively fails with an error naming the columns, and a reference to + a column of `data` in neither `covariates` nor `design_cols` raises a warning, + instead of the simulation failing partway through with `E_MISSING_COVARIATE`. + FeRx grammar words (e.g. the `pk` keyword) and ODE state names are not treated as + covariate references, and a column the model references under its exact + spelling is never renamed (#43). * `anonymize_dataset()`: new `design_cols` argument for study-design columns (e.g. `DVID`, `OCC`, L2 `PAIR` indices, carried dose history, model row filters) that are cloned verbatim from the matched source design instead of being dropped diff --git a/R/anonymize_dataset.R b/R/anonymize_dataset.R index 0147e32..44189ba 100644 --- a/R/anonymize_dataset.R +++ b/R/anonymize_dataset.R @@ -24,7 +24,14 @@ #' the structural columns (e.g. `AMT = DOSE`, `DV = lndv`) are dropped, #' because the anonymized dataset already uses the canonical names `ID`, #' `TIME`, `EVID`, `AMT`, `DV` and `RATE` (plus `CMT`, `MDV`, `ADDL`, `II` -#' and `SS` when present in `data`). A relative `[priors]` `from_fit` path is +#' and `SS` when present in `data`). FeRx matches covariate names +#' case-sensitively, so when the model references a covariate under a +#' spelling that differs only by case from its column (e.g. `CONC0` for a +#' `conc0` column) and the `[data]` block does not map it, a rename such as +#' `CONC0 = conc0` is added. This is checked before any covariate is sampled: +#' a reference that matches several columns case-insensitively is an error, +#' and a reference to a column of `data` that is in neither `covariates` nor +#' `design_cols` raises a warning. A relative `[priors]` `from_fit` path is #' made absolute against the directory of `model_file`, so it keeps resolving #' from the copy. Comments (`#` and `//`) are handled as FeRx handles them. #' @param dictionary named list mapping expected NONMEM column names to columns @@ -185,6 +192,13 @@ anonymize_dataset <- function( loq = loq, design_cols = design_cols ) + check_anonymize_model_covariates( + model_file = model_file, + data = data, + covariates = covariates, + dictionary = dictionary, + design_cols = design_cols + ) id_var <- dictionary$ID time_var <- dictionary$TIME check_anonymize_monotone_time( @@ -1106,7 +1120,10 @@ anonymized_structural_columns <- function() { #' its target does not collide with a column left in place by the retained #' renames (see `retain_data_maps()`). Maps onto (or from) the #' structural columns are dropped, because the anonymized frame already uses -#' the canonical names (`ID`, `TIME`, `EVID`, `AMT`, `DV`, ...). +#' the canonical names (`ID`, `TIME`, `EVID`, `AMT`, `DV`, ...). A covariate +#' the model references under a spelling that differs only by case from its +#' column gets an added rename (see `ferx_covariate_case_bridges()`); if no +#' `[data]` block exists, one is appended for it. #' #' * a relative `[priors]` `from_fit` path, which FeRx resolves against the #' model file's directory, is made absolute against the directory of @@ -1132,19 +1149,10 @@ prepare_simulation_model_file <- function( ) { lines <- readLines(model_file, warn = FALSE) model_dir <- dirname(normalizePath(model_file, winslash = "/", mustWork = FALSE)) - # Comments are stripped the way FeRx does (`#` and `//`) before any line is - # classified, so a commented header or key is read as FeRx reads it. - stripped <- strip_ferx_comment(lines) - header_re <- "^\\s*\\[\\s*([A-Za-z_][A-Za-z0-9_]*)(\\s+[^]]*)?\\]\\s*$" - is_header <- grepl(header_re, stripped) - block <- rep(NA_character_, length(lines)) - current <- NA_character_ - for (i in seq_along(lines)) { - if (is_header[i]) { - current <- tolower(sub(header_re, "\\1", stripped[i])) - } - block[i] <- current - } + parsed <- parse_ferx_model_lines(lines) + stripped <- parsed$stripped + is_header <- parsed$is_header + block <- parsed$block split_key_value <- function(i) { content <- trimws(stripped[i]) if (!nzchar(content) || !grepl("=", content, fixed = TRUE)) return(NULL) @@ -1181,6 +1189,7 @@ prepare_simulation_model_file <- function( map_idx <- integer(0) map_target <- character(0) map_source <- character(0) + map_key <- character(0) for (i in data_body) { kv <- split_key_value(i) if (is.null(kv)) next @@ -1192,6 +1201,7 @@ prepare_simulation_model_file <- function( } else { lines[i] <- paste0(indent_of(i), "path = \"", abs_data_path, "\"") path_written <- TRUE + path_idx <- i } next } @@ -1199,28 +1209,321 @@ prepare_simulation_model_file <- function( map_idx <- c(map_idx, i) map_target <- c(map_target, toupper(key)) map_source <- c(map_source, toupper(value)) + map_key <- c(map_key, key) } else { keep[i] <- FALSE } } - keep[map_idx[!retain_data_maps(map_target, map_source, toupper(columns))]] <- FALSE + retained <- retain_data_maps(map_target, map_source, toupper(columns)) + keep[map_idx[!retained]] <- FALSE + map_key <- map_key[retained] + map_source <- map_source[retained] + } else { + map_key <- character(0) + map_source <- character(0) + } + + # Columns as FeRx will see them once the retained `[data]` renames are + # applied (FeRx resolves rename sources case-insensitively). + renamed <- columns + for (j in seq_along(map_key)) { + renamed[toupper(columns) == map_source[j]] <- map_key[j] + } + # FeRx matches the model's covariate references to data columns + # case-sensitively, so a covariate the model spells `CONC0` is not found in a + # `conc0` column. Bridge case-only differences with extra `[data]` renames. + bridges <- ferx_covariate_case_bridges( + stripped = stripped, + block = block, + is_header = is_header, + columns = renamed, + renamable = setdiff( + columns[!toupper(columns) %in% map_source], + anonymized_structural_columns() + ) + ) + bridge_lines <- if (length(bridges) > 0) { + paste0(" ", names(bridges), " = ", unname(bridges)) + } else { + character(0) + } + + if (length(data_body) > 0) { + insert_at <- if (path_written) path_idx else which(is_header & block == "data")[1] if (!path_written) { # A `[data]` block without `path` fails to parse; add the simulation path # right after the block header. - header_idx <- which(is_header & block == "data")[1] - lines <- append( - lines, - paste0(" path = \"", abs_data_path, "\""), - after = header_idx - ) - keep <- append(keep, TRUE, after = header_idx) + bridge_lines <- c(paste0(" path = \"", abs_data_path, "\""), bridge_lines) } + lines <- append(lines, bridge_lines, after = insert_at) + keep <- append(keep, rep(TRUE, length(bridge_lines)), after = insert_at) + } else if (length(bridge_lines) > 0) { + abs_data_path <- normalizePath(data_path, winslash = "/", mustWork = FALSE) + lines <- c(lines, "", "[data]", paste0(" path = \"", abs_data_path, "\""), bridge_lines) + keep <- c(keep, rep(TRUE, 3 + length(bridge_lines))) } writeLines(lines[keep], path) invisible(path) } +#' Identifiers a FeRx model file references and defines +#' +#' A lightweight, conservative scan of a FeRx model file (it does not +#' reimplement the FeRx parser). Identifiers are collected from the model's +#' expression blocks, i.e. every block except `[parameters]`, `[data]`, +#' `[data_selection]`, `[initial_values]`, `[fit_options]`, `[priors]`, +#' `[simulation]` and `[output]`, after stripping comments and quoted strings. +#' An identifier is *defined* when it is assigned (`NAME =`, including named +#' arguments such as `cl = CL`) or declared in `[parameters]`, and a *call* when +#' it is followed by `(`. Everything else is a candidate covariate reference. +#' +#' @param stripped model-file lines with comments stripped. +#' @param block lower-cased block name of each line (`NA` before the first +#' header). +#' @param is_header logical, whether each line is a block header. +#' +#' @returns a list with character vectors `referenced` (candidate covariate +#' references, not defined anywhere in the model) and `defined`. +#' +#' @noRd +ferx_model_identifiers <- function(stripped, block, is_header) { + ident_re <- "(? = )` of the renames +#' to add (possibly empty). +#' +#' @noRd +ferx_covariate_case_bridges <- function(stripped, block, is_header, columns, + renamable) { + all_refs <- ferx_model_identifiers(stripped, block, is_header)$referenced + # only references that no column carries under the model's exact spelling, + # and that some column carries under another case + refs <- all_refs[!all_refs %in% columns & toupper(all_refs) %in% toupper(columns)] + # a column the model references under its exact spelling is never renamed + # away: a case-variant reference to it is then most likely not a covariate + # reference at all (the identifier scan is heuristic), and renaming would + # break the exact reference + refs <- refs[!vapply(refs, function(ref) { + any(columns[toupper(columns) == toupper(ref)] %in% all_refs) + }, logical(1))] + if (length(refs) == 0) return(character(0)) + structural <- toupper(anonymized_structural_columns()) + refs <- refs[!toupper(refs) %in% structural] + bridges <- character(0) + problems <- character(0) + for (ref in refs) { + matches <- columns[toupper(columns) == toupper(ref)] + variants <- refs[toupper(refs) == toupper(ref)] + if (length(matches) > 1) { + problems <- c(problems, paste0( + "`", ref, "` matches several columns that differ only by case (", + paste0("`", matches, "`", collapse = ", "), ")" + )) + } else if (length(variants) > 1) { + if (identical(ref, variants[[1]])) { + problems <- c(problems, paste0( + paste0("`", variants, "`", collapse = ", "), + " differ only by case but must all resolve to column `", matches, "`" + )) + } + } else if (matches %in% renamable) { + bridges[[ref]] <- matches + } else { + problems <- c(problems, paste0( + "`", ref, "` matches column `", matches, "` only case-insensitively, ", + "and that column is already renamed in the `[data]` block" + )) + } + } + if (length(problems) > 0) { + stop( + "The model references covariate(s) whose spelling matches the ", + "anonymized dataset's columns only case-insensitively, which FeRx does ", + "not resolve: ", paste(problems, collapse = "; "), ". Spell the ", + "covariates in the model as they are spelled in `data`, or map them in ", + "the model's `[data]` block (e.g. `CONC0 = conc0`).", + call. = FALSE + ) + } + bridges +} + +#' Classify the lines of a FeRx model file by block +#' +#' Comments are stripped the way FeRx does (`#` and `//`) before any line is +#' classified, so a commented header or key is read as FeRx reads it. +#' +#' @param lines raw model-file lines. +#' +#' @returns a list with `stripped` (lines without comments), `is_header` +#' (logical) and `block` (lower-cased name of the block each line belongs +#' to, `NA` before the first header). +#' +#' @noRd +parse_ferx_model_lines <- function(lines) { + stripped <- strip_ferx_comment(lines) + header_re <- "^\\s*\\[\\s*([A-Za-z_][A-Za-z0-9_]*)(\\s+[^]]*)?\\]\\s*$" + is_header <- grepl(header_re, stripped) + block <- rep(NA_character_, length(lines)) + current <- NA_character_ + for (i in seq_along(lines)) { + if (is_header[i]) { + current <- tolower(sub(header_re, "\\1", stripped[i])) + } + block[i] <- current + } + list(stripped = stripped, is_header = is_header, block = block) +} + +#' Check the model's covariate references against the anonymized frame +#' +#' Runs before any covariate is sampled, so a column-naming problem is reported +#' as such instead of surfacing from inside the FeRx simulation. It prepares +#' the simulation copy of `model_file` (see `prepare_simulation_model_file()`) +#' for the columns the anonymized frame will carry, which bridges covariates +#' the model spells in another case and errors on references that cannot be +#' bridged. It also warns about model references that match a column of +#' `data` that is in neither `covariates` nor `design_cols` (and so not in the +#' anonymized frame). +#' +#' @param model_file path to the FeRx model file. +#' @param data original data.frame. +#' @param covariates covariates to sample. +#' @param dictionary normalized column dictionary. +#' @param design_cols design columns cloned verbatim into the anonymized frame. +#' +#' @returns `invisible(TRUE)`. +#' +#' @noRd +check_anonymize_model_covariates <- function(model_file, data, covariates, dictionary, + design_cols = NULL) { + optional <- c("CMT", "MDV", "ADDL", "II", "SS") + # mirrors the columns of `build_anonymized_simulation_input()`: design + # columns are cloned under their own names + event_cols <- unique(c( + unlist(dictionary[c("ID", "TIME", "EVID", "AMT", "RATE")], use.names = FALSE), + optional + )) + design_cols <- setdiff(unique(design_cols), event_cols) + frame_cols <- unique(c( + "ID", "TIME", "EVID", "AMT", + if (dictionary$RATE %in% names(data)) "RATE", + "DV", + intersect(optional, names(data)), + design_cols, + covariates + )) + sim_model <- tempfile(fileext = ".ferx") + on.exit(unlink(sim_model), add = TRUE) + prepare_simulation_model_file( + model_file = model_file, + data_path = tempfile(fileext = ".csv"), + columns = frame_cols, + path = sim_model + ) + + parsed <- parse_ferx_model_lines(readLines(sim_model, warn = FALSE)) + refs <- ferx_model_identifiers(parsed$stripped, parsed$block, parsed$is_header)$referenced + data_maps <- parsed$stripped[!parsed$is_header & parsed$block %in% "data"] + data_maps <- trimws(sub("=.*$", "", data_maps[grepl("=", data_maps, fixed = TRUE)])) + available <- toupper(c(frame_cols, data_maps)) + structural <- unique(c( + toupper(anonymized_structural_columns()), + toupper(unlist(dictionary, use.names = FALSE)) + )) + dropped <- setdiff( + names(data), + c(covariates, design_cols, unlist(dictionary, use.names = FALSE)) + ) + dropped <- dropped[!toupper(dropped) %in% structural] + refs <- refs[!toupper(refs) %in% c(available, structural)] + missing <- dropped[toupper(dropped) %in% toupper(refs)] + if (length(missing) > 0) { + warning( + "The model appears to reference column(s) of `data` that are not in ", + "`covariates` or `design_cols`, so they are not part of the anonymized ", + "dataset: ", paste0("`", missing, "`", collapse = ", "), ". Add them to ", + "`covariates` (sampled) or `design_cols` (cloned from the source design) ", + "if the model needs them, or the simulation will fail.", + call. = FALSE + ) + } + invisible(TRUE) +} + #' Strip a trailing FeRx line comment #' #' FeRx ends a model-file line at the first `#` or `//`, whichever comes first diff --git a/man/anonymize_dataset.Rd b/man/anonymize_dataset.Rd index 297681e..5d66e65 100644 --- a/man/anonymize_dataset.Rd +++ b/man/anonymize_dataset.Rd @@ -46,7 +46,14 @@ simultaneous, so \code{HTCM = WT} with \code{WT = HT} is kept). Maps onto or fro the structural columns (e.g. \code{AMT = DOSE}, \code{DV = lndv}) are dropped, because the anonymized dataset already uses the canonical names \code{ID}, \code{TIME}, \code{EVID}, \code{AMT}, \code{DV} and \code{RATE} (plus \code{CMT}, \code{MDV}, \code{ADDL}, \code{II} -and \code{SS} when present in \code{data}). A relative \verb{[priors]} \code{from_fit} path is +and \code{SS} when present in \code{data}). FeRx matches covariate names +case-sensitively, so when the model references a covariate under a +spelling that differs only by case from its column (e.g. \code{CONC0} for a +\code{conc0} column) and the \verb{[data]} block does not map it, a rename such as +\code{CONC0 = conc0} is added. This is checked before any covariate is sampled: +a reference that matches several columns case-insensitively is an error, +and a reference to a column of \code{data} that is in neither \code{covariates} nor +\code{design_cols} raises a warning. A relative \verb{[priors]} \code{from_fit} path is made absolute against the directory of \code{model_file}, so it keeps resolving from the copy. Comments (\verb{#} and \verb{//}) are handled as FeRx handles them.} diff --git a/tests/testthat/test-anonymize_dataset.R b/tests/testthat/test-anonymize_dataset.R index 17e0426..d29ce4e 100644 --- a/tests/testthat/test-anonymize_dataset.R +++ b/tests/testthat/test-anonymize_dataset.R @@ -1445,6 +1445,234 @@ test_that("anonymize_dataset forwards accepted `...` arguments to the sampler", expect_equal(received, list(maxit = 7)) }) +test_that("ferx_model_identifiers separates references from definitions and calls", { + lines <- c( + "[parameters]", + " theta TVCL(0.1, 0.001, 10)", + " omega ETA_CL ~ 0.1", + "[individual_parameters]", + " CL = TVCL * (WT / 70)^0.75 * exp(ETA_CL) # uses Wt in a comment", + " V = 1e-3 * if (SEX == 1) 2 else 1", + "[initial_conditions]", + " CENT = CONC0 * V", + "[structural_model]", + " pk one_cpt_oral(cl = CL, v = V)", + "[data]", + " path = data.csv", + " ASA = asa", + "[fit_options]", + " method = foce" + ) + parsed <- parse_ferx_model_lines(lines) + ids <- ferx_model_identifiers(parsed$stripped, parsed$block, parsed$is_header) + expect_setequal(ids$referenced, c("WT", "SEX", "CONC0")) + expect_true(all(c("TVCL", "ETA_CL", "CL", "V", "CENT", "cl", "v") %in% ids$defined)) +}) + +test_that("prepare_simulation_model_file bridges a covariate named in another case (#43)", { + model <- tempfile(fileext = ".ferx") + writeLines(c( + "[individual_parameters]", + " CL = TVCL * (WT / 70) * (1 + ASA)", + "[initial_conditions]", + " CENT = CONC0", + "[data]", + " path = ../data/original.csv", + " ODV = dv", + " DV = lndv", + " ASA = asa", + " WT = wt" + ), model) + data_path <- tempfile(fileext = ".csv") + out <- prepare_simulation_model_file( + model, data_path, + c("ID", "TIME", "EVID", "AMT", "DV", "wt", "asa", "sex", "conc0") + ) + abs_path <- normalizePath(data_path, winslash = "/", mustWork = FALSE) + lines <- readLines(out) + data_lines <- lines[(which(lines == "[data]") + 1):length(lines)] + expect_equal( + data_lines, + c(paste0(" path = \"", abs_path, "\""), " CONC0 = conc0", " ASA = asa", " WT = wt") + ) +}) + +test_that("prepare_simulation_model_file adds a [data] block for a bridge when absent", { + model <- tempfile(fileext = ".ferx") + writeLines(c("[individual_parameters]", " CL = TVCL * WT"), model) + data_path <- tempfile(fileext = ".csv") + out <- prepare_simulation_model_file(model, data_path, c("ID", "TIME", "DV", "wt")) + abs_path <- normalizePath(data_path, winslash = "/", mustWork = FALSE) + expect_equal( + readLines(out), + c( + "[individual_parameters]", " CL = TVCL * WT", "", + "[data]", paste0(" path = \"", abs_path, "\""), " WT = wt" + ) + ) +}) + +test_that("prepare_simulation_model_file does not bridge exact or structural matches", { + model <- tempfile(fileext = ".ferx") + src <- c( + "[individual_parameters]", " CL = TVCL * WT * Time", + "[data]", " path = x.csv" + ) + writeLines(src, model) + data_path <- tempfile(fileext = ".csv") + out <- prepare_simulation_model_file(model, data_path, c("ID", "TIME", "DV", "WT", "wt2")) + expect_false(any(grepl("WT =|Time =", readLines(out)))) +}) + +test_that("prepare_simulation_model_file names covariate case mismatches it cannot bridge", { + model <- tempfile(fileext = ".ferx") + writeLines(c("[individual_parameters]", " CL = TVCL * WT"), model) + expect_error( + prepare_simulation_model_file(model, tempfile(fileext = ".csv"), c("ID", "wt", "Wt")), + "`WT` matches several columns that differ only by case \\(`wt`, `Wt`\\)" + ) + writeLines(c("[individual_parameters]", " CL = TVCL * WT * Wt"), model) + expect_error( + prepare_simulation_model_file(model, tempfile(fileext = ".csv"), c("ID", "wt")), + "`WT`, `Wt` differ only by case but must all resolve to column `wt`" + ) +}) + +test_that("anonymize_dataset reports an unbridgeable covariate spelling before sampling", { + dat <- data.frame( + ID = c(1, 1, 2, 2), TIME = c(0, 1, 0, 1), EVID = c(1, 0, 1, 0), + AMT = c(100, 0, 100, 0), DV = c(0, 4, 0, 5), + wt = c(70, 70, 80, 80), Wt = c(1, 1, 2, 2) + ) + model <- tempfile(fileext = ".ferx") + writeLines(c("[individual_parameters]", " CL = TVCL * WT"), model) + local_mocked_bindings( + sample_covariates_mice_timevarying = function(...) stop("sampler reached") + ) + expect_error( + anonymize_dataset(dat, covariates = c("wt", "Wt"), model_file = model), + "matches several columns that differ only by case" + ) +}) + +test_that("anonymize_dataset warns up front about model references left out of `covariates`", { + dat <- data.frame( + ID = c(1, 1, 2, 2), TIME = c(0, 1, 0, 1), EVID = c(1, 0, 1, 0), + AMT = c(100, 0, 100, 0), DV = c(0, 4, 0, 5), + WT = c(70, 70, 80, 80), conc0 = c(1, 1, 2, 2) + ) + model <- tempfile(fileext = ".ferx") + writeLines(c( + "[individual_parameters]", " CL = TVCL * WT", + "[initial_conditions]", " CENT = CONC0" + ), model) + local_mocked_bindings( + sample_covariates_mice_timevarying = function(...) stop("sampler reached") + ) + expect_warning( + expect_error( + anonymize_dataset(dat, covariates = "WT", model_file = model), + "sampler reached" + ), + "not in `covariates`.*`conc0`" + ) +}) + +test_that("anonymize_dataset simulates a model naming a covariate in another case (#43)", { + skip_if_not_installed("ferx") + ex <- ferx::ferx_example("warfarin") + dat <- utils::read.csv(ex$data, na.strings = ".") + dat <- dat[dat$ID %in% 1:6, ] + dat$wt <- 60 + 5 * dat$ID + model <- tempfile(fileext = ".ferx") + src <- readLines(ex$model) + src <- sub("CL = TVCL * exp(ETA_CL)", "CL = TVCL * (WT / 70)^0.75 * exp(ETA_CL)", + src, fixed = TRUE) + writeLines(c(src, "[data]", paste0(" path = ", ex$data)), model) + out <- anonymize_dataset(dat, covariates = "wt", model_file = model, seed = 3) + expect_true("wt" %in% names(out)) + expect_true(all(is.finite(out$DV[out$EVID == 0 & out$MDV == 0]))) +}) + +test_that("ferx_model_identifiers treats ODE states and grammar words as non-covariates", { + lines <- c( + "[structural_model]", + " ode(obs_cmt=central, states=[depot, central])", + "[odes]", + " d/dt(depot) = -KA * depot", + " d/dt(central) = KA * depot - CL / V * central * PK", + "[scaling]", + " y = central / V" + ) + parsed <- parse_ferx_model_lines(lines) + ids <- ferx_model_identifiers(parsed$stripped, parsed$block, parsed$is_header) + expect_setequal(ids$referenced, c("KA", "CL", "V", "PK")) + expect_true(all(c("depot", "central") %in% ids$defined)) +}) + +test_that("prepare_simulation_model_file never renames an exactly referenced column away", { + # `pk` is the FeRx structural keyword; the `PK` covariate column must keep + # its name rather than be bridged to `pk` + model <- tempfile(fileext = ".ferx") + writeLines(c( + "[individual_parameters]", + " CL = TVCL * (1 + PK)", + "[structural_model]", + " pk one_cpt_oral(cl=CL, v=V, ka=KA)", + "[data]", + " path = x.csv" + ), model) + out <- prepare_simulation_model_file( + model, tempfile(fileext = ".csv"), c("ID", "TIME", "DV", "PK") + ) + expect_false(any(grepl("^\\s*pk\\s*=", readLines(out)))) + + # an ODE state that differs only by case from a covariate column is not + # a covariate reference, and the exactly referenced column stays put + writeLines(c( + "[structural_model]", + " ode(obs_cmt=central, states=[depot, central])", + "[odes]", + " d/dt(depot) = -KA * depot", + " d/dt(central) = KA * depot - CL / V * central * DEPOT", + "[data]", + " path = x.csv" + ), model) + out <- prepare_simulation_model_file( + model, tempfile(fileext = ".csv"), c("ID", "TIME", "DV", "DEPOT", "CENTRAL") + ) + expect_false(any(grepl("depot =|central =", readLines(out)))) + + # a heuristic false positive that collides with an exact reference is not + # reported as an ambiguity either + writeLines(c( + "[individual_parameters]", + " CL = TVCL * WT * Wt", + "[data]", + " path = x.csv" + ), model) + out <- prepare_simulation_model_file( + model, tempfile(fileext = ".csv"), c("ID", "TIME", "DV", "WT") + ) + expect_false(any(grepl("Wt =", readLines(out)))) +}) + +test_that("anonymize_dataset keeps an upper-case PK covariate next to the `pk` keyword", { + skip_if_not_installed("ferx") + ex <- ferx::ferx_example("warfarin") + dat <- utils::read.csv(ex$data, na.strings = ".") + dat <- dat[dat$ID %in% 1:6, ] + dat$PK <- 0.1 * dat$ID + model <- tempfile(fileext = ".ferx") + src <- readLines(ex$model) + src <- sub("CL = TVCL * exp(ETA_CL)", "CL = TVCL * (1 + PK) * exp(ETA_CL)", + src, fixed = TRUE) + writeLines(c(src, "[data]", paste0(" path = ", ex$data)), model) + out <- anonymize_dataset(dat, covariates = "PK", model_file = model, seed = 3) + expect_true("PK" %in% names(out)) + expect_true(all(is.finite(out$DV[out$EVID == 0 & out$MDV == 0]))) +}) + test_that("a cat_covs entry with implausibly many levels is rejected before sampling", { # e.g. a clock column (time of previous reset) passed in `cat_covs` dat <- data.frame( @@ -1473,3 +1701,30 @@ test_that("a cat_covs entry with implausibly many levels is rejected before samp check_anonymize_dots("max_cat_levels", 1, method = "mice") ) }) + +test_that("the up-front model check counts design_cols as part of the frame", { + dat <- data.frame( + ID = c(1, 1, 2, 2), TIME = c(0, 1, 0, 1), EVID = c(1, 0, 1, 0), + AMT = c(100, 0, 100, 0), DV = c(0, 4, 0, 5), + WT = c(70, 70, 80, 80), occ = c(1, 2, 1, 2) + ) + model <- tempfile(fileext = ".ferx") + writeLines(c("[individual_parameters]", " CL = TVCL * WT * (1 + 0.1 * occ)"), model) + # a design column referenced by the model does not trigger the warning + expect_no_warning(check_anonymize_model_covariates( + model, dat, covariates = "WT", dictionary = normalize_anonymize_dictionary(list()), + design_cols = "occ" + )) + expect_warning( + check_anonymize_model_covariates( + model, dat, covariates = "WT", dictionary = normalize_anonymize_dictionary(list()) + ), + "neither|not in `covariates` or `design_cols`.*`occ`" + ) + # a design column named in another case by the model is bridged too + writeLines(c("[individual_parameters]", " CL = TVCL * WT * (1 + 0.1 * OCC)"), model) + out <- prepare_simulation_model_file( + model, tempfile(fileext = ".csv"), c("ID", "TIME", "EVID", "AMT", "DV", "occ", "WT") + ) + expect_true(" OCC = occ" %in% readLines(out)) +})