From 7e811ff3498cdb52ec49e247668183e42e27a947 Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Tue, 17 Nov 2026 10:43:40 -0800 Subject: [PATCH 1/3] anonymize_dataset: treat two-level numeric covariates as categorical and check level shares (#46) A binary 0/1 covariate not listed in cat_covs was resampled as continuous and could lose one of its levels without any notice. With method = "mice" such columns are now treated as categorical (with a message); "lme" and "copulas" reject them with an error naming the column. After resampling, the level set and record-level shares of each discrete covariate are compared with the source, warning on lost levels, new values, or >3-fold share changes. Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 2 +- NEWS.md | 12 ++ R/anonymize_dataset.R | 158 ++++++++++++++++++++++++ man/anonymize_dataset.Rd | 11 ++ tests/testthat/test-anonymize_dataset.R | 127 +++++++++++++++++++ 5 files changed, 309 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 542b6d8..deb2ccd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: irxforge Title: Forging data for pharmacometric analyses -Version: 0.0.0.9049 +Version: 0.0.0.9050 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 9daca81..701cd1c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,17 @@ # irxforge (development version) +* `anonymize_dataset()`: a numeric covariate with exactly two distinct values + (e.g. a 0/1 flag) that is not listed in `cat_covs` is no longer resampled as + continuous, which could silently drop one of its levels. With + `method = "mice"` it is now treated as categorical (with a message naming + it); with `"lme"` or `"copulas"` it is rejected with an error naming it. + After resampling, the record-level share of each level of every discrete + covariate (categorical covariates, and whole-number covariates with at most + 3 distinct values) is compared with the source, and a warning + (`irxforge_anonymize_level_warning`) lists covariates where a source level is + absent from the output, values absent from the source appear, or a level's + share changes more than 3-fold (#46). + * `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 diff --git a/R/anonymize_dataset.R b/R/anonymize_dataset.R index 44189ba..a645123 100644 --- a/R/anonymize_dataset.R +++ b/R/anonymize_dataset.R @@ -50,6 +50,17 @@ #' returned with their original numeric codes. With `method = "mice"`, a #' warning is raised for numeric covariates that look like categorical codes #' (whole numbers with at most 3 distinct values) but are not listed here. +#' A numeric covariate with exactly two distinct values (e.g. a 0/1 flag; +#' checked when it has at least 10 non-missing values) has no continuous +#' distribution to preserve and could lose a level if resampled as +#' continuous: with `method = "mice"` it is treated as categorical (with a +#' message) even when not listed here, and with `"lme"` or `"copulas"` it is +#' rejected with an error naming it. After resampling, the level shares of +#' each discrete covariate (categorical covariates, and covariates with at +#' least 10 whole-number values and at most 3 distinct values) are compared, +#' record by record, with the source, and a warning is raised when a source +#' level is absent from the output, values absent from the source appear, or +#' a level's share changes more than 3-fold. #' Categorical covariates (including factor and character columns) with #' more than 20 distinct values are rejected with an error reporting the #' level count of each categorical covariate: such a column is almost always @@ -219,6 +230,30 @@ anonymize_dataset <- function( is.factor(x) || is.character(x) }, logical(1)) ]) + # a numeric covariate with exactly two distinct values (e.g. a 0/1 flag) has + # no continuous distribution to preserve: resampling it as continuous can + # silently drop one of its levels, so treat it as categorical (MICE) or + # refuse it (LME / copulas, which support only continuous covariates) + binary_covs <- find_anonymize_binary_covariates(sample_data, covariates, cat_covs) + if (length(binary_covs) > 0) { + if (method != "mice") { + stop( + "`method = \"", method, "\"` supports only continuous covariates, but ", + "these numeric covariates take exactly two distinct values and cannot ", + "be resampled as continuous: ", + paste0("`", binary_covs, "`", collapse = ", "), + ". Use `method = \"mice\"` (they are then sampled as categorical), or ", + "remove them from `covariates`.", + call. = FALSE + ) + } + message( + "Treating two-level numeric covariate(s) as categorical: ", + paste0("`", binary_covs, "`", collapse = ", "), + ". Add them to `cat_covs` to silence this message." + ) + cat_covs <- union(cat_covs, binary_covs) + } if (method != "mice" && length(cat_covs) > 0) { stop( "`method = \"", method, "\"` supports only continuous covariates, but these ", @@ -254,6 +289,16 @@ anonymize_dataset <- function( ... ) + # compare the level set and level shares of discrete covariates between the + # source and the resampled data, so a lost or collapsed level is reported + # instead of silently changing the design + check_anonymize_covariate_levels( + source = data, + resampled = selected$data, + covariates = covariates, + cat_covs = cat_covs + ) + anonymized <- apply_anonymize_sigdig( data = selected$data, covariates = covariates, @@ -345,6 +390,119 @@ check_anonymize_dots <- function(dot_names, n_dots, method) { invisible(NULL) } +#' Find numeric covariates that take exactly two distinct values +#' +#' Such a column (typically a 0/1 flag) has no continuous distribution to +#' preserve. Covariates with fewer than 10 non-missing values are not flagged, +#' since a continuous covariate in a very small dataset can take two values by +#' chance. +#' +#' @param data data.frame holding the covariates. +#' @param covariates names of the covariates to check. +#' @param cat_covs names of the covariates already treated as categorical. +#' @returns character vector of the two-level numeric covariates not in +#' `cat_covs`. +#' +#' @noRd +find_anonymize_binary_covariates <- function(data, covariates, cat_covs = NULL) { + covs <- setdiff(covariates, cat_covs) + covs[vapply(covs, function(cov) { + x <- data[[cov]] + if (!is.numeric(x)) return(FALSE) + x <- x[!is.na(x)] + length(x) >= 10 && length(unique(x)) == 2 + }, logical(1))] +} + +#' Warn when resampling loses or distorts a level of a discrete covariate +#' +#' For every discrete covariate (the categorical covariates, plus numeric +#' covariates with at least 10 non-missing source values, all whole numbers +#' with at most 3 distinct values), compares the record-level share of each level in `source` with +#' that in `resampled`. A single warning lists every covariate where a level +#' present in the source is absent from the resampled data, where values absent +#' from the source appear, or where a level's share changes by more than +#' `max_ratio`-fold. +#' +#' @param source the original data. +#' @param resampled the anonymized data (before rounding and BLQ handling). +#' @param covariates names of the resampled covariates. +#' @param cat_covs names of the categorical covariates. +#' @param max_ratio largest accepted fold change of a level's share. +#' @returns a character vector with one problem description per affected +#' covariate, invisibly. +#' +#' @noRd +check_anonymize_covariate_levels <- function(source, resampled, covariates, + cat_covs = NULL, max_ratio = 3) { + covs <- intersect(covariates, names(resampled)) + discrete <- covs[vapply(covs, function(cov) { + if (cov %in% cat_covs) return(TRUE) + x <- source[[cov]] + if (!is.numeric(x)) return(FALSE) + x <- x[!is.na(x)] + ux <- unique(x) + length(x) >= 10 && length(ux) >= 2 && length(ux) <= 3 && all(ux == round(ux)) + }, logical(1))] + level_shares <- function(x) { + x <- as.character(x[!is.na(x)]) + if (length(x) == 0) return(numeric(0)) + tab <- table(x) + stats::setNames(as.numeric(tab) / length(x), names(tab)) + } + fmt <- function(p) formatC(p, digits = 3, format = "f") + problems <- character(0) + for (cov in discrete) { + src <- level_shares(source[[cov]]) + out <- level_shares(resampled[[cov]]) + if (length(src) == 0 || length(out) == 0) next + issues <- character(0) + lost <- setdiff(names(src), names(out)) + if (length(lost) > 0) { + issues <- c(issues, paste0( + "level(s) ", paste0("`", lost, "`", collapse = ", "), + " (source share ", paste(fmt(src[lost]), collapse = ", "), + ") absent from the output" + )) + } + new <- setdiff(names(out), names(src)) + if (length(new) > 0) { + shown <- utils::head(new, 5) + issues <- c(issues, paste0( + length(new), " value(s) absent from the source (e.g. ", + paste0("`", shown, "`", collapse = ", "), ")" + )) + } + common <- intersect(names(src), names(out)) + ratio <- out[common] / src[common] + shifted <- common[ratio > max_ratio | ratio < 1 / max_ratio] + if (length(shifted) > 0) { + issues <- c(issues, paste0( + "share of level(s) ", + paste0("`", shifted, "` ", fmt(src[shifted]), " -> ", fmt(out[shifted]), + collapse = ", ") + )) + } + if (length(issues) > 0) { + problems <- c(problems, paste0("`", cov, "`: ", paste(issues, collapse = "; "))) + } + } + if (length(problems) > 0) { + warning(warningCondition( + paste0( + "Resampling changed the level distribution of discrete covariate(s) ", + "(record-level shares, source -> output):\n", + paste0(" * ", problems, collapse = "\n"), + "\nThe anonymized dataset may not reflect the source design. Declare ", + "categorical codes in `cat_covs`, or pass study-design columns that ", + "must not be resampled in `design_cols`." + ), + class = "irxforge_anonymize_level_warning" + )) + } + invisible(problems) +} + #' Draw one time-varying covariate candidate with the chosen sampler #' #' Dispatches to the MICE, LME or copula time-varying sampler, in all cases diff --git a/man/anonymize_dataset.Rd b/man/anonymize_dataset.Rd index 5d66e65..d06be44 100644 --- a/man/anonymize_dataset.Rd +++ b/man/anonymize_dataset.Rd @@ -75,6 +75,17 @@ categorical). Use this for numerically coded categorical covariates, e.g. returned with their original numeric codes. With \code{method = "mice"}, a warning is raised for numeric covariates that look like categorical codes (whole numbers with at most 3 distinct values) but are not listed here. +A numeric covariate with exactly two distinct values (e.g. a 0/1 flag; +checked when it has at least 10 non-missing values) has no continuous +distribution to preserve and could lose a level if resampled as +continuous: with \code{method = "mice"} it is treated as categorical (with a +message) even when not listed here, and with \code{"lme"} or \code{"copulas"} it is +rejected with an error naming it. After resampling, the level shares of +each discrete covariate (categorical covariates, and covariates with at +least 10 whole-number values and at most 3 distinct values) are compared, +record by record, with the source, and a warning is raised when a source +level is absent from the output, values absent from the source appear, or +a level's share changes more than 3-fold. Categorical covariates (including factor and character columns) with more than 20 distinct values are rejected with an error reporting the level count of each categorical covariate: such a column is almost always diff --git a/tests/testthat/test-anonymize_dataset.R b/tests/testthat/test-anonymize_dataset.R index d29ce4e..9ab80e5 100644 --- a/tests/testthat/test-anonymize_dataset.R +++ b/tests/testthat/test-anonymize_dataset.R @@ -1728,3 +1728,130 @@ test_that("the up-front model check counts design_cols as part of the frame", { ) expect_true(" OCC = occ" %in% readLines(out)) }) + +test_that("two-level numeric covariates are treated as categorical (#46)", { + n <- 12 + dat <- data.frame( + ID = rep(seq_len(n), each = 2), TIME = rep(c(0, 1), n), + EVID = rep(c(1, 0), n), AMT = rep(c(100, 0), n), DV = rep(c(0, 5), n), + WT = rep(seq(60, 115, by = 5), each = 2), + W4 = rep(rep(c(0, 1), each = 6), each = 2) + ) + model <- tempfile(fileext = ".ferx") + file.create(model) + + expect_equal(find_anonymize_binary_covariates(dat, c("WT", "W4")), "W4") + expect_equal(find_anonymize_binary_covariates(dat, c("WT", "W4"), "W4"), character(0)) + # too few values to tell a flag from a continuous covariate + expect_equal(find_anonymize_binary_covariates(dat[1:8, ], "W4"), character(0)) + + expect_error( + anonymize_dataset(dat, covariates = c("WT", "W4"), model_file = model, + method = "lme"), + "exactly two distinct values.*`W4`" + ) + expect_error( + anonymize_dataset(dat, covariates = c("WT", "W4"), model_file = model, + method = "copulas"), + "exactly two distinct values.*`W4`" + ) + + passed_cat_covs <- NULL + local_mocked_bindings( + sample_covariates_mice_timevarying = function(data, cat_covs, ...) { + passed_cat_covs <<- cat_covs + out <- data[, c("ID", "TIME", "WT", "W4")] + out$.design_id <- out$ID + out$W4 <- factor(as.character(out$W4)) + out + }, + simulate_anonymized_concentrations = function(model_file, data, seed = NULL) { + obs <- data[data$EVID == 0, ] + data.frame(ID = obs$ID, TIME = obs$TIME, DV_SIM = 5) + } + ) + expect_message( + out <- anonymize_dataset(dat, covariates = c("WT", "W4"), model_file = model), + "two-level numeric covariate.*`W4`" + ) + expect_equal(passed_cat_covs, "W4") + expect_type(out$W4, "double") + expect_setequal(unique(out$W4), c(0, 1)) + + # declaring it in `cat_covs` silences the message + expect_silent( + anonymize_dataset(dat, covariates = c("WT", "W4"), model_file = model, + cat_covs = "W4") + ) +}) + +test_that("resampling that loses or distorts a level is reported (#46)", { + src <- data.frame( + W1 = c(rep(0, 54), rep(1, 46)), + W4 = c(rep(0, 97), rep(1, 3)), + WT = seq(50, 99), + SEX = factor(rep(c("F", "M"), 50)) + ) + same <- src + expect_silent( + check_anonymize_covariate_levels(src, same, names(src), cat_covs = "SEX") + ) + + out <- src + out$W1 <- c(rep(0, 12), rep(1, 88)) + out$W4 <- 0 + out$SEX <- factor(rep("F", 100), levels = c("F", "M")) + w <- expect_warning( + problems <- check_anonymize_covariate_levels( + src, out, names(src), cat_covs = "SEX" + ), + class = "irxforge_anonymize_level_warning" + ) + expect_length(problems, 3) + expect_match(conditionMessage(w), "`W1`: share of level\\(s\\) `0` 0.540 -> 0.120") + expect_match(conditionMessage(w), "`W4`: level\\(s\\) `1` \\(source share 0.030\\) absent") + expect_match(conditionMessage(w), "`SEX`: level\\(s\\) `M`") + # continuous covariates are not checked + expect_no_match(conditionMessage(w), "`WT`") + + # an undeclared integer code resampled as continuous gains new values + out <- src + out$W1 <- out$W1 + 0.25 + expect_warning( + check_anonymize_covariate_levels(src, out, "W1"), + "absent from the source" + ) + + # moderate share changes are accepted + out <- src + out$W1 <- c(rep(0, 40), rep(1, 60)) + expect_silent(check_anonymize_covariate_levels(src, out, "W1")) +}) + +test_that("anonymize_dataset warns when a resampled covariate loses a level (#46)", { + n <- 12 + dat <- data.frame( + ID = rep(seq_len(n), each = 2), TIME = rep(c(0, 1), n), + EVID = rep(c(1, 0), n), AMT = rep(c(100, 0), n), DV = rep(c(0, 5), n), + GRP = rep(rep(c(0, 1, 2), each = 4), each = 2) + ) + model <- tempfile(fileext = ".ferx") + file.create(model) + local_mocked_bindings( + sample_covariates_mice_timevarying = function(data, ...) { + out <- data[, c("ID", "TIME", "GRP")] + out$.design_id <- out$ID + out$GRP <- ifelse(out$GRP == 2, 1, out$GRP) + out + }, + simulate_anonymized_concentrations = function(model_file, data, seed = NULL) { + obs <- data[data$EVID == 0, ] + data.frame(ID = obs$ID, TIME = obs$TIME, DV_SIM = 5) + } + ) + expect_warning( + anonymize_dataset(dat, covariates = "GRP", model_file = model), + "`GRP`: level\\(s\\) `2`.*absent from the output", + class = "irxforge_anonymize_level_warning" + ) +}) From 63bd9f41b485372062c64c04e910da408f70a4bb Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Tue, 17 Nov 2026 10:47:28 -0800 Subject: [PATCH 2/3] anonymize_dataset: address review of two-level covariate handling (#46) - Detect two-level numeric covariates regardless of record count, and always include them in the level audit. - Do not round categorical covariates with sigdig, and run the level audit on the rounded (returned) data, so merged codes are reported. - Report an all-missing resampled covariate as losing every source level instead of skipping it. - Give test fixtures a weight column with more than two distinct values. Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 2 +- NEWS.md | 23 ++++---- R/anonymize_dataset.R | 52 +++++++++-------- man/anonymize_dataset.Rd | 12 ++-- tests/testthat/test-anonymize_dataset.R | 78 +++++++++++++++++++++---- 5 files changed, 116 insertions(+), 51 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index deb2ccd..0163357 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: irxforge Title: Forging data for pharmacometric analyses -Version: 0.0.0.9050 +Version: 0.0.0.9051 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 701cd1c..2ec4f37 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,16 +1,19 @@ # irxforge (development version) * `anonymize_dataset()`: a numeric covariate with exactly two distinct values - (e.g. a 0/1 flag) that is not listed in `cat_covs` is no longer resampled as - continuous, which could silently drop one of its levels. With - `method = "mice"` it is now treated as categorical (with a message naming - it); with `"lme"` or `"copulas"` it is rejected with an error naming it. - After resampling, the record-level share of each level of every discrete - covariate (categorical covariates, and whole-number covariates with at most - 3 distinct values) is compared with the source, and a warning - (`irxforge_anonymize_level_warning`) lists covariates where a source level is - absent from the output, values absent from the source appear, or a level's - share changes more than 3-fold (#46). + (e.g. a 0/1 flag), however few records carry it, that is not listed in + `cat_covs` is no longer resampled as continuous, which could silently drop + one of its levels. With `method = "mice"` it is now treated as categorical + (with a message naming it); with `"lme"` or `"copulas"` it is rejected with + an error naming it. After resampling, the record-level share of each level + of every discrete covariate (categorical covariates, two-level numeric + covariates, and whole-number covariates with at most 3 distinct values) is + compared with the source, and a warning (`irxforge_anonymize_level_warning`) + lists covariates where a source level is absent from the output (including + an all-missing output), values absent from the source appear, or a level's + share changes more than 3-fold. The check runs on the returned dataset, + after `sigdig` rounding, which no longer applies to categorical covariates + (so numeric codes such as `10000` and `10001` are not merged) (#46). * `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` diff --git a/R/anonymize_dataset.R b/R/anonymize_dataset.R index a645123..4dc8445 100644 --- a/R/anonymize_dataset.R +++ b/R/anonymize_dataset.R @@ -50,15 +50,16 @@ #' returned with their original numeric codes. With `method = "mice"`, a #' warning is raised for numeric covariates that look like categorical codes #' (whole numbers with at most 3 distinct values) but are not listed here. -#' A numeric covariate with exactly two distinct values (e.g. a 0/1 flag; -#' checked when it has at least 10 non-missing values) has no continuous +#' A numeric covariate with exactly two distinct values (e.g. a 0/1 flag) +#' has no continuous #' distribution to preserve and could lose a level if resampled as #' continuous: with `method = "mice"` it is treated as categorical (with a #' message) even when not listed here, and with `"lme"` or `"copulas"` it is #' rejected with an error naming it. After resampling, the level shares of #' each discrete covariate (categorical covariates, and covariates with at -#' least 10 whole-number values and at most 3 distinct values) are compared, -#' record by record, with the source, and a warning is raised when a source +#' least 10 whole-number values and at most 3 distinct values) in the +#' returned dataset are compared, record by record, with the source, and a +#' warning is raised when a source #' level is absent from the output, values absent from the source appear, or #' a level's share changes more than 3-fold. #' Categorical covariates (including factor and character columns) with @@ -79,7 +80,8 @@ #' @param sigdig number of significant digits to round the sampled covariates #' and simulated concentrations (`DV`) to, via [signif()], to further obscure #' the values. Default `4`. `NULL` disables rounding. Rounding is applied -#' before the `loq` comparison. +#' before the `loq` comparison. Categorical covariates (see `cat_covs`) are +#' never rounded, so distinct numeric codes are not merged. #' @param n_candidates number of independent candidates to draw and score against #' the observed data, keeping the closest match. Default `1` (no scoring; a #' single candidate is used). When greater than 1, the candidate with the @@ -289,21 +291,22 @@ anonymize_dataset <- function( ... ) + # categorical codes are labels, not measurements: rounding them could merge + # distinct levels (e.g. 10000 and 10001 with `sigdig = 4`) + anonymized <- apply_anonymize_sigdig( + data = selected$data, + covariates = setdiff(covariates, cat_covs), + sigdig = sigdig + ) # compare the level set and level shares of discrete covariates between the - # source and the resampled data, so a lost or collapsed level is reported - # instead of silently changing the design + # source and the returned (rounded) data, so a lost or collapsed level is + # reported instead of silently changing the design check_anonymize_covariate_levels( source = data, - resampled = selected$data, + resampled = anonymized, covariates = covariates, cat_covs = cat_covs ) - - anonymized <- apply_anonymize_sigdig( - data = selected$data, - covariates = covariates, - sigdig = sigdig - ) result <- apply_anonymize_blq( data = anonymized, loq = loq, @@ -393,9 +396,7 @@ check_anonymize_dots <- function(dot_names, n_dots, method) { #' Find numeric covariates that take exactly two distinct values #' #' Such a column (typically a 0/1 flag) has no continuous distribution to -#' preserve. Covariates with fewer than 10 non-missing values are not flagged, -#' since a continuous covariate in a very small dataset can take two values by -#' chance. +#' preserve, regardless of how many records carry it. #' #' @param data data.frame holding the covariates. #' @param covariates names of the covariates to check. @@ -409,16 +410,16 @@ find_anonymize_binary_covariates <- function(data, covariates, cat_covs = NULL) covs[vapply(covs, function(cov) { x <- data[[cov]] if (!is.numeric(x)) return(FALSE) - x <- x[!is.na(x)] - length(x) >= 10 && length(unique(x)) == 2 + length(unique(x[!is.na(x)])) == 2 }, logical(1))] } #' Warn when resampling loses or distorts a level of a discrete covariate #' -#' For every discrete covariate (the categorical covariates, plus numeric -#' covariates with at least 10 non-missing source values, all whole numbers -#' with at most 3 distinct values), compares the record-level share of each level in `source` with +#' For every discrete covariate (the categorical covariates, numeric +#' covariates with exactly two distinct source values, and numeric covariates +#' with at least 10 non-missing source values, all whole numbers with at most +#' 3 distinct values), compares the record-level share of each level in `source` with #' that in `resampled`. A single warning lists every covariate where a level #' present in the source is absent from the resampled data, where values absent #' from the source appear, or where a level's share changes by more than @@ -442,7 +443,8 @@ check_anonymize_covariate_levels <- function(source, resampled, covariates, if (!is.numeric(x)) return(FALSE) x <- x[!is.na(x)] ux <- unique(x) - length(x) >= 10 && length(ux) >= 2 && length(ux) <= 3 && all(ux == round(ux)) + length(ux) == 2 || + (length(x) >= 10 && length(ux) == 3 && all(ux == round(ux))) }, logical(1))] level_shares <- function(x) { x <- as.character(x[!is.na(x)]) @@ -455,7 +457,9 @@ check_anonymize_covariate_levels <- function(source, resampled, covariates, for (cov in discrete) { src <- level_shares(source[[cov]]) out <- level_shares(resampled[[cov]]) - if (length(src) == 0 || length(out) == 0) next + # nothing to preserve when the source has no values; an all-missing output + # loses every source level and is reported as such below + if (length(src) == 0) next issues <- character(0) lost <- setdiff(names(src), names(out)) if (length(lost) > 0) { diff --git a/man/anonymize_dataset.Rd b/man/anonymize_dataset.Rd index d06be44..2789965 100644 --- a/man/anonymize_dataset.Rd +++ b/man/anonymize_dataset.Rd @@ -75,15 +75,16 @@ categorical). Use this for numerically coded categorical covariates, e.g. returned with their original numeric codes. With \code{method = "mice"}, a warning is raised for numeric covariates that look like categorical codes (whole numbers with at most 3 distinct values) but are not listed here. -A numeric covariate with exactly two distinct values (e.g. a 0/1 flag; -checked when it has at least 10 non-missing values) has no continuous +A numeric covariate with exactly two distinct values (e.g. a 0/1 flag) +has no continuous distribution to preserve and could lose a level if resampled as continuous: with \code{method = "mice"} it is treated as categorical (with a message) even when not listed here, and with \code{"lme"} or \code{"copulas"} it is rejected with an error naming it. After resampling, the level shares of each discrete covariate (categorical covariates, and covariates with at -least 10 whole-number values and at most 3 distinct values) are compared, -record by record, with the source, and a warning is raised when a source +least 10 whole-number values and at most 3 distinct values) in the +returned dataset are compared, record by record, with the source, and a +warning is raised when a source level is absent from the output, values absent from the source appear, or a level's share changes more than 3-fold. Categorical covariates (including factor and character columns) with @@ -107,7 +108,8 @@ observations keep \code{MDV = 0} and are flagged via \code{CENS}).} \item{sigdig}{number of significant digits to round the sampled covariates and simulated concentrations (\code{DV}) to, via \code{\link[=signif]{signif()}}, to further obscure the values. Default \code{4}. \code{NULL} disables rounding. Rounding is applied -before the \code{loq} comparison.} +before the \code{loq} comparison. Categorical covariates (see \code{cat_covs}) are +never rounded, so distinct numeric codes are not merged.} \item{n_candidates}{number of independent candidates to draw and score against the observed data, keeping the closest match. Default \code{1} (no scoring; a diff --git a/tests/testthat/test-anonymize_dataset.R b/tests/testthat/test-anonymize_dataset.R index 9ab80e5..e7f5e89 100644 --- a/tests/testthat/test-anonymize_dataset.R +++ b/tests/testthat/test-anonymize_dataset.R @@ -178,7 +178,7 @@ test_that("sigdig rounds covariates and simulated concentrations", { EVENT = c(1, 0, 1, 0), DOSE = c(100, 0, 200, 0), CONC = c(0, 4, 0, 8), - WT = c(70, 70, 80, 80), + WT = c(70, 71, 80, 81), SCR = c(1.0, 1.1, 0.8, 0.9) ) model <- tempfile(fileext = ".ferx") @@ -299,7 +299,7 @@ test_that("anonymize_dataset matches simulated DV by ID and TIME, not position", EVID = c(1, 0, 0, 1, 0, 0), AMT = c(100, 0, 0, 100, 0, 0), DV = c(0, 5, 4, 0, 6, 7), - WT = c(70, 70, 70, 80, 80, 80) + WT = c(70, 70, 71, 80, 80, 81) ) model <- tempfile(fileext = ".ferx") file.create(model) @@ -581,7 +581,7 @@ test_that("score_on = 'concentration' errors without positive observed concentra EVENT = c(1, 0, 1, 0), DOSE = c(100, 0, 200, 0), CONC = c(0, 0, 0, 0), - WT = c(70, 70, 80, 80) + WT = c(70, 71, 80, 81) ) model <- tempfile(fileext = ".ferx") file.create(model) @@ -722,7 +722,7 @@ test_that("cat_covs marks numerically coded covariates as categorical", { 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, 5, 0, 4), SEX = c(0, 0, 1, 1), - WT = c(70, 70, 80, 80) + WT = c(70, 71, 80, 81) ) model <- tempfile(fileext = ".ferx") file.create(model) @@ -1037,7 +1037,7 @@ test_that("anonymize_dataset accepts reset records with a monotone time axis", { EVID = c(1, 0, 4, 0, 1, 0, 3, 0), AMT = c(100, 0, 100, 0, 100, 0, 0, 0), DV = c(0, 5, 0, 4, 0, 6, 0, 5), - WT = c(70, 70, 70, 70, 80, 80, 80, 80) + WT = c(70, 70, 70, 71, 80, 80, 80, 81) ) model <- tempfile(fileext = ".ferx") file.create(model) @@ -1236,7 +1236,7 @@ test_that("covariates without observed values are rejected up front", { EVID = c(1, 0, 1, 0), AMT = c(100, 0, 100, 0), DV = c(0, 5, 0, 6), - WT = c(70, 70, 80, 80), + WT = c(70, 71, 80, 81), HT = c(NA, 170, NA, 180), AST = c(NA, 20, NA, NA), ALT = NA_real_, @@ -1349,7 +1349,7 @@ test_that("strip_ferx_comment and is_absolute_path follow FeRx/OS conventions", test_that("unknown `...` arguments are rejected up front as unused", { 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, 5, 0, 4), WT = c(70, 70, 80, 80) + AMT = c(100, 0, 100, 0), DV = c(0, 5, 0, 4), WT = c(70, 71, 80, 81) ) model <- tempfile(fileext = ".ferx") file.create(model) @@ -1418,7 +1418,7 @@ test_that("check_anonymize_dots accepts arguments of the selected sampler", { test_that("anonymize_dataset forwards accepted `...` arguments to the sampler", { 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, 5, 0, 4), WT = c(70, 70, 80, 80) + AMT = c(100, 0, 100, 0), DV = c(0, 5, 0, 4), WT = c(70, 71, 80, 81) ) model <- tempfile(fileext = ".ferx") file.create(model) @@ -1559,7 +1559,7 @@ test_that("anonymize_dataset warns up front about model references left out of ` 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) + WT = c(70, 71, 80, 81), conc0 = c(1, 1, 2, 2) ) model <- tempfile(fileext = ".ferx") writeLines(c( @@ -1706,7 +1706,7 @@ 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) + WT = c(70, 71, 80, 81), occ = c(1, 2, 1, 2) ) model <- tempfile(fileext = ".ferx") writeLines(c("[individual_parameters]", " CL = TVCL * WT * (1 + 0.1 * occ)"), model) @@ -1742,7 +1742,9 @@ test_that("two-level numeric covariates are treated as categorical (#46)", { expect_equal(find_anonymize_binary_covariates(dat, c("WT", "W4")), "W4") expect_equal(find_anonymize_binary_covariates(dat, c("WT", "W4"), "W4"), character(0)) - # too few values to tell a flag from a continuous covariate + # detection does not depend on the number of records + expect_equal(find_anonymize_binary_covariates(dat[c(1, 24), ], "W4"), "W4") + # a constant column is not two-level expect_equal(find_anonymize_binary_covariates(dat[1:8, ], "W4"), character(0)) expect_error( @@ -1826,6 +1828,60 @@ test_that("resampling that loses or distorts a level is reported (#46)", { out <- src out$W1 <- c(rep(0, 40), rep(1, 60)) expect_silent(check_anonymize_covariate_levels(src, out, "W1")) + + # an all-missing output loses every source level + out <- src + out$SEX <- factor(rep(NA, 100), levels = c("F", "M")) + expect_warning( + check_anonymize_covariate_levels(src, out, "SEX", cat_covs = "SEX"), + "`SEX`: level\\(s\\) `F`, `M` .*absent from the output" + ) + # an all-missing source has nothing to preserve + src$SEX[] <- NA + expect_silent(check_anonymize_covariate_levels(src, out, "SEX", cat_covs = "SEX")) + + # a two-level column in a small dataset is still checked + small_src <- data.frame(FLAG = c(0, 1, 1)) + small_out <- data.frame(FLAG = c(1, 1, 1)) + expect_warning( + check_anonymize_covariate_levels(small_src, small_out, "FLAG"), + "`FLAG`: level\\(s\\) `0`" + ) +}) + +test_that("sigdig does not round categorical codes, and the check sees rounded data (#46)", { + dat <- data.frame( + ID = rep(1:6, each = 2), TIME = rep(c(0, 1), 6), + EVID = rep(c(1, 0), 6), AMT = rep(c(100, 0), 6), DV = rep(c(0, 5), 6), + SITE = rep(c(10000, 10001, 10002), each = 4), + CODE = rep(c(10000, 10001, 10002), each = 4) + ) + model <- tempfile(fileext = ".ferx") + file.create(model) + local_mocked_bindings( + sample_covariates_mice_timevarying = function(data, ...) { + out <- data[, c("ID", "TIME", "SITE", "CODE")] + out$.design_id <- out$ID + out$SITE <- factor(as.character(out$SITE)) + out + }, + simulate_anonymized_concentrations = function(model_file, data, seed = NULL) { + obs <- data[data$EVID == 0, ] + data.frame(ID = obs$ID, TIME = obs$TIME, DV_SIM = 5) + } + ) + # SITE is declared categorical and keeps its codes; CODE is not, so the + # default `sigdig = 4` merges its levels, which the post-rounding check reports + w <- expect_warning( + out <- anonymize_dataset( + dat, covariates = c("SITE", "CODE"), model_file = model, cat_covs = "SITE" + ), + class = "irxforge_anonymize_level_warning" + ) + expect_equal(sort(unique(out$SITE)), c(10000, 10001, 10002)) + expect_equal(unique(out$CODE), 10000) + expect_match(conditionMessage(w), "`CODE`: level\\(s\\) `10001`, `10002`") + expect_no_match(conditionMessage(w), "`SITE`") }) test_that("anonymize_dataset warns when a resampled covariate loses a level (#46)", { From cc3fe37124b14baabe7875f56b999ae06ddaec63 Mon Sep 17 00:00:00 2001 From: roninsightrx Date: Tue, 17 Nov 2026 10:50:47 -0800 Subject: [PATCH 3/3] anonymize_dataset: run the covariate level check after BLQ removal (#46) Removing below-LOQ records can drop every record carrying a rare level, so the check now inspects the final returned dataset. Adds a regression test where BLQ removal eliminates a level (and censoring keeps it). Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 2 +- NEWS.md | 4 ++- R/anonymize_dataset.R | 37 ++++++++++++---------- man/anonymize_dataset.Rd | 8 ++--- tests/testthat/test-anonymize_dataset.R | 42 +++++++++++++++++++++++++ 5 files changed, 70 insertions(+), 23 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 0163357..cbf75a3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: irxforge Title: Forging data for pharmacometric analyses -Version: 0.0.0.9051 +Version: 0.0.0.9052 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 2ec4f37..ed0e182 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,7 +12,9 @@ lists covariates where a source level is absent from the output (including an all-missing output), values absent from the source appear, or a level's share changes more than 3-fold. The check runs on the returned dataset, - after `sigdig` rounding, which no longer applies to categorical covariates + after below-LOQ records are removed (with `loq` and + `blq_method = "remove"`) and after `sigdig` rounding, which no longer + applies to categorical covariates (so numeric codes such as `10000` and `10001` are not merged) (#46). * `anonymize_dataset()`: a covariate that the model references under a spelling diff --git a/R/anonymize_dataset.R b/R/anonymize_dataset.R index 4dc8445..07a5e20 100644 --- a/R/anonymize_dataset.R +++ b/R/anonymize_dataset.R @@ -58,10 +58,10 @@ #' rejected with an error naming it. After resampling, the level shares of #' each discrete covariate (categorical covariates, and covariates with at #' least 10 whole-number values and at most 3 distinct values) in the -#' returned dataset are compared, record by record, with the source, and a -#' warning is raised when a source -#' level is absent from the output, values absent from the source appear, or -#' a level's share changes more than 3-fold. +#' returned dataset (after `sigdig` rounding and below-`loq` removal) are +#' compared, record by record, with the source, and a warning is raised when +#' a source level is absent from the output, values absent from the source +#' appear, or a level's share changes more than 3-fold. #' Categorical covariates (including factor and character columns) with #' more than 20 distinct values are rejected with an error reporting the #' level count of each categorical covariate: such a column is almost always @@ -298,21 +298,21 @@ anonymize_dataset <- function( covariates = setdiff(covariates, cat_covs), sigdig = sigdig ) - # compare the level set and level shares of discrete covariates between the - # source and the returned (rounded) data, so a lost or collapsed level is - # reported instead of silently changing the design - check_anonymize_covariate_levels( - source = data, - resampled = anonymized, - covariates = covariates, - cat_covs = cat_covs - ) result <- apply_anonymize_blq( data = anonymized, loq = loq, blq_method = blq_method ) result <- recompute_anonymized_mdv(result) + # compare the level set and level shares of discrete covariates between the + # source and the returned data (after rounding and below-LOQ removal), so a + # lost or collapsed level is reported instead of silently changing the design + check_anonymize_covariate_levels( + source = data, + resampled = result, + covariates = covariates, + cat_covs = cat_covs + ) attr(result, "design_map") <- attr(selected$data, "design_map") attr(result, "similarity_score") <- selected$score result @@ -414,7 +414,7 @@ find_anonymize_binary_covariates <- function(data, covariates, cat_covs = NULL) }, logical(1))] } -#' Warn when resampling loses or distorts a level of a discrete covariate +#' Warn when anonymization loses or distorts a level of a discrete covariate #' #' For every discrete covariate (the categorical covariates, numeric #' covariates with exactly two distinct source values, and numeric covariates @@ -426,7 +426,8 @@ find_anonymize_binary_covariates <- function(data, covariates, cat_covs = NULL) #' `max_ratio`-fold. #' #' @param source the original data. -#' @param resampled the anonymized data (before rounding and BLQ handling). +#' @param resampled the returned anonymized data (after rounding and BLQ +#' handling). #' @param covariates names of the resampled covariates. #' @param cat_covs names of the categorical covariates. #' @param max_ratio largest accepted fold change of a level's share. @@ -494,12 +495,14 @@ check_anonymize_covariate_levels <- function(source, resampled, covariates, if (length(problems) > 0) { warning(warningCondition( paste0( - "Resampling changed the level distribution of discrete covariate(s) ", + "Anonymization changed the level distribution of discrete covariate(s) ", "(record-level shares, source -> output):\n", paste0(" * ", problems, collapse = "\n"), "\nThe anonymized dataset may not reflect the source design. Declare ", "categorical codes in `cat_covs`, or pass study-design columns that ", - "must not be resampled in `design_cols`." + "must not be resampled in `design_cols`. With `loq`, removing ", + "below-LOQ records (`blq_method = \"remove\"`) can also drop levels; ", + "`blq_method = \"cens\"` keeps them." ), class = "irxforge_anonymize_level_warning" )) diff --git a/man/anonymize_dataset.Rd b/man/anonymize_dataset.Rd index 2789965..893419a 100644 --- a/man/anonymize_dataset.Rd +++ b/man/anonymize_dataset.Rd @@ -83,10 +83,10 @@ message) even when not listed here, and with \code{"lme"} or \code{"copulas"} it rejected with an error naming it. After resampling, the level shares of each discrete covariate (categorical covariates, and covariates with at least 10 whole-number values and at most 3 distinct values) in the -returned dataset are compared, record by record, with the source, and a -warning is raised when a source -level is absent from the output, values absent from the source appear, or -a level's share changes more than 3-fold. +returned dataset (after \code{sigdig} rounding and below-\code{loq} removal) are +compared, record by record, with the source, and a warning is raised when +a source level is absent from the output, values absent from the source +appear, or a level's share changes more than 3-fold. Categorical covariates (including factor and character columns) with more than 20 distinct values are rejected with an error reporting the level count of each categorical covariate: such a column is almost always diff --git a/tests/testthat/test-anonymize_dataset.R b/tests/testthat/test-anonymize_dataset.R index e7f5e89..0d7e440 100644 --- a/tests/testthat/test-anonymize_dataset.R +++ b/tests/testthat/test-anonymize_dataset.R @@ -1911,3 +1911,45 @@ test_that("anonymize_dataset warns when a resampled covariate loses a level (#46 class = "irxforge_anonymize_level_warning" ) }) + +test_that("the level check sees records removed as below LOQ (#46)", { + n <- 12 + dat <- data.frame( + ID = rep(seq_len(n), each = 2), TIME = rep(c(0, 1), n), + EVID = rep(c(1, 0), n), AMT = rep(c(100, 0), n), DV = rep(c(0, 5), n), + # W4 is set only on the observation records of subjects 1 and 2 + W4 = c(0, 1, 0, 1, rep(0, 2 * n - 4)) + ) + model <- tempfile(fileext = ".ferx") + file.create(model) + local_mocked_bindings( + sample_covariates_mice_timevarying = function(data, ...) { + out <- data[, c("ID", "TIME", "W4")] + out$.design_id <- out$ID + out$W4 <- factor(as.character(out$W4)) + out + }, + simulate_anonymized_concentrations = function(model_file, data, seed = NULL) { + obs <- data[data$EVID == 0, ] + # the W4 = 1 observations simulate below the LOQ + data.frame(ID = obs$ID, TIME = obs$TIME, DV_SIM = ifelse(obs$W4 == 1, 0.01, 5)) + } + ) + w <- expect_warning( + out <- anonymize_dataset( + dat, covariates = "W4", model_file = model, cat_covs = "W4", loq = 1 + ), + class = "irxforge_anonymize_level_warning" + ) + expect_false(any(out$W4 == 1)) + expect_match(conditionMessage(w), "`W4`: level\\(s\\) `1` .*absent from the output") + + # censoring keeps the records, and with them the level + expect_no_warning( + out <- anonymize_dataset( + dat, covariates = "W4", model_file = model, cat_covs = "W4", loq = 1, + blq_method = "cens" + ) + ) + expect_equal(sum(out$W4 == 1), 2) +})