colon_reps <- 2000L # Full scale: 2000 sampled datasets per sampler.
simulated_datasets <- 50L # Full scale: 50 simulated datasets.
simulated_patients <- 10000L # Full scale: 10000 patients per simulated dataset.
simulated_reps <- 200L # Full scale: 200 sampled datasets per simulated dataset and sampler.Rendered on 2026-11-30 with retrogroup 0.0.3 at commit
35499a3.
vignette("sampling", package = "retrogroup") claims that
sampled datasets reproduce the subgroup hazard ratios on average. This
vignette checks that claim by simulation for
group_sample_unconstrained() and
group_sample_constrained().
Each benchmark starts with a patient-level dataset whose true
subgroups are known. The target hazard ratio of each subgroup level
comes from group_analysis_summary(), which fits a Cox
proportional hazards model to the patients in that level, with treatment
as the only covariate and Efron’s method for ties. We hide the true
subgroups, sample new ones from the summary statistics, and compute the
hazard ratios of the sampled dataset with
group_analysis_summary().
We run two examples:
group_example_patient() with the target hazard ratios of
group_example_summary(). These are real data, so the
proportional hazards model behind
group_analysis_probability() may not hold exactly.group_analysis_probability(), so any difference from the
targets is due to the samplers.For group_sample_constrained(), the benchmark stops with
an error unless the number of patients in each subgroup level of every
sampled dataset exactly matches the assumed counts.
Each figure shows histograms of the hazard ratio of each sampled dataset minus its target, with one panel per subgroup level and sampler. A histogram centered on zero means the sampler reproduces the target on average, and its width shows how much a single sampled dataset varies around the target.
# Shared code for the simulation vignettes:
# benchmarks_sampling, benchmarks_optimization, and prognostic.
#
# Each *.Rmd.source file loads this file into a folded chunk, so the code is
# baked into every rendered vignette. The roxygen2-style comments document
# the functions for reviewers. roxygen2 does not process this file.
#
# To try the examples, start R in the package root and run:
#
# library(retrogroup)
# library(ggplot2)
# source("vignettes/benchmarks.R")
#
# Every example runs in a few seconds.
#
# Results format
# --------------
#
# A benchmark is a list with two data frames:
#
# - estimates: one row per method, replication, subgroup level, and stage
# (if the vignette has stages). Columns:
# - method: factor, the reconstruction method.
# - replication: integer, the index of the replication within the method.
# - stage: factor, optional, e.g. "Sampled" or "Optimized".
# - subgroup: factor, "variable: level" or a similar label.
# - target: the value the reconstructed dataset should reproduce.
# - estimate: the value the reconstructed dataset achieves,
# NA if it cannot be computed.
# - difference: estimate minus target.
# - runs: one row per optimization run, or NULL if nothing is optimized.
# Columns: method, replication, seconds (elapsed time of the optimizer),
# and warned (TRUE if the loss did not fall below the tolerance).
# Simulation elements ---------------------------------------------------------
#' @title Colon cancer example data
#' @description Standardize the colon cancer example patients and summary
#' statistics of `group_example_patient()` and `group_example_summary()`.
#' @return A list with `patient` (output of `group_data_patient()`) and
#' `summary` (output of `group_data_summary()`).
#' @examples
#' colon <- example_colon()
#' colon$summary
example_colon <- function() {
list(
patient = group_data_patient(
group_example_patient(),
arm = "arm",
treatment = "Lev+5FU",
time = "time",
event = "event"
),
summary = group_data_summary(
group_example_summary(),
variable = "variable",
level = "level",
patients = "patients",
events = "events",
hazard_ratio = "hazard_ratio"
)
)
}
#' @title Reconstruction methods under test
#' @description Each method pairs a sampler with its matching optimizer.
#' @return A named list of methods. Each method is a list with:
#' - `sample`: the sampler, e.g. `group_sample_unconstrained()`.
#' - `optimize`: the optimizer, e.g. `group_optimize_unconstrained()`.
#' - `constrained`: `TRUE` if every sampled and optimized dataset must
#' reproduce the assumed counts of patients exactly.
#' @examples
#' methods <- benchmark_methods()
#' names(methods)
#' colon <- example_colon()
#' sampled <- methods$Constrained$sample(colon$patient, colon$summary)
#' table(sampled$age)
benchmark_methods <- function() {
list(
Unconstrained = list(
sample = group_sample_unconstrained,
optimize = group_optimize_unconstrained,
constrained = FALSE
),
Constrained = list(
sample = group_sample_constrained,
optimize = group_optimize_constrained,
constrained = TRUE
)
)
}
#' @title Subgroup labels
#' @description Label each row of a summary statistics data frame.
#' @param summary Data frame with `variable` and `level` columns, such as
#' the output of `group_data_summary()` or `group_analysis_summary()`.
#' @return Character vector with one `"variable: level"` label per row.
#' @examples
#' subgroup_label(example_colon()$summary)
subgroup_label <- function(summary) {
paste0(summary$variable, ": ", summary$level)
}
#' @title Check the counts of patients
#' @description Stop with an error unless the number of patients in each
#' subgroup level of a dataset equals the assumed count in `summary`.
#' Constrained methods promise exact counts, and the benchmarks call this
#' function to verify the promise on every dataset.
#' @param statistics Output of `group_analysis_summary()` for the dataset.
#' Levels with no patients may be missing.
#' @param summary Summary statistics with the assumed counts.
#' @param name Description of the dataset for the error message.
#' @return `NULL` (invisibly) if the counts match.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' sampled <- group_sample_constrained(colon$patient, colon$summary)
#' statistics <- group_analysis_summary(sampled, variables)
#' check_counts(statistics, colon$summary, "sampled dataset")
check_counts <- function(statistics, summary, name) {
rows <- match(subgroup_label(summary), subgroup_label(statistics))
observed <- statistics$patients[rows]
if (!identical(observed, summary$patients)) {
stop(
"The constrained ", name, " does not match the assumed counts.\n",
"Assumed patients: ", toString(summary$patients), "\n",
"Observed patients: ", toString(observed),
call. = FALSE
)
}
invisible()
}
#' @title Compare achieved hazard ratios with their targets
#' @description Pair each target hazard ratio with the hazard ratio a
#' reconstructed dataset achieves in the same subgroup level.
#' @param targets Summary statistics with the target hazard ratios.
#' @param achieved Output of `group_analysis_summary()` for the
#' reconstructed dataset. Levels with no patients may be missing,
#' and their estimates are `NA`.
#' @return Data frame with one row per row of `targets` and columns
#' `subgroup`, `target`, and `estimate`.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' sampled <- group_sample_unconstrained(colon$patient, colon$summary)
#' compare_summary(colon$summary, group_analysis_summary(sampled, variables))
compare_summary <- function(targets, achieved) {
rows <- match(subgroup_label(targets), subgroup_label(achieved))
data.frame(
subgroup = subgroup_label(targets),
target = targets$hazard_ratio,
estimate = achieved$hazard_ratio[rows]
)
}
#' @title Run one optimization
#' @description Call an optimizer and record its elapsed time and whether
#' it warned that the loss did not fall below the tolerance.
#' The warning is recorded, not shown.
#' @param optimize Optimizer, e.g. `group_optimize_constrained()`.
#' @param start Starting dataset, usually from the matching sampler.
#' @param summary Summary statistics with the target hazard ratios.
#' @param iterations Maximum number of iterations per subgroup variable.
#' @param tolerance Stop when the loss falls below this value.
#' @return List with `optimized` (the optimized dataset), `seconds`
#' (elapsed time of the optimizer only), and `warned` (logical).
#' @examples
#' colon <- example_colon()
#' start <- group_sample_constrained(colon$patient, colon$summary)
#' run <- optimize_once(
#' group_optimize_constrained,
#' start,
#' colon$summary,
#' iterations = 20L,
#' tolerance = 1e-3
#' )
#' run[c("seconds", "warned")]
optimize_once <- function(optimize, start, summary, iterations, tolerance) {
warned <- FALSE
seconds <- system.time(
optimized <- withCallingHandlers(
optimize(start, summary, iterations = iterations, tolerance = tolerance),
retrogroup_warning = function(condition) {
warned <<- TRUE
invokeRestart("muffleWarning")
}
)
)[["elapsed"]]
list(optimized = optimized, seconds = seconds, warned = warned)
}
#' @title Run a benchmark
#' @description Run independent replications of every method and
#' assemble the results in the format described at the top of this file.
#' @param methods Named list of methods, e.g. from `benchmark_methods()`.
#' @param reps Number of replications per method.
#' @param replication Function of one method that runs one replication.
#' It returns a list with:
#' - `estimates`: data frame with columns `subgroup`, `target`,
#' `estimate`, and optionally `stage`.
#' - `runs`: data frame with columns `seconds` and `warned`,
#' or `NULL` if the replication does not optimize.
#' @return List with `estimates` and `runs`. Factor levels of `method`,
#' `stage`, and `subgroup` follow their order of first appearance,
#' which fixes the order of panels in figures.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' replication <- function(method) {
#' sampled <- method$sample(colon$patient, colon$summary)
#' achieved <- group_analysis_summary(sampled, variables)
#' list(estimates = compare_summary(colon$summary, achieved), runs = NULL)
#' }
#' results <- run_benchmark(benchmark_methods(), reps = 2L, replication)
#' head(results$estimates)
run_benchmark <- function(methods, reps, replication) {
results <- lapply(names(methods), \(name) {
lapply(seq_len(reps), \(index) {
result <- replication(methods[[name]])
label <- function(data) {
if (is.null(data)) {
return(NULL)
}
cbind(method = name, replication = index, data)
}
list(estimates = label(result$estimates), runs = label(result$runs))
})
})
results <- unlist(results, recursive = FALSE)
estimates <- do.call(rbind, lapply(results, `[[`, "estimates"))
runs <- do.call(rbind, lapply(results, `[[`, "runs"))
estimates$difference <- estimates$estimate - estimates$target
for (column in intersect(c("method", "stage", "subgroup"), names(estimates))) {
estimates[[column]] <- in_order(estimates[[column]])
}
if (!is.null(runs)) {
runs$method <- in_order(runs$method)
}
list(estimates = estimates, runs = runs)
}
#' @title Factor in order of first appearance
#' @param x Vector.
#' @return Factor whose levels are the unique values of `x` in order.
#' @examples
#' in_order(c("b", "a", "b"))
in_order <- function(x) {
factor(x, levels = unique(x))
}
# Display ---------------------------------------------------------------------
#' @title Format numbers for tables
#' @description Show 3 decimal places, but switch to scientific notation
#' with 3 significant figures for nonzero values that would otherwise
#' round to zero.
#' @param x Numeric vector.
#' @return Character vector.
#' @examples
#' format_number(c(0.12345, 0.0001234, 0))
format_number <- function(x) {
ifelse(
x != 0 & round(x, 3L) == 0,
formatC(x, digits = 2L, format = "e"),
formatC(x, digits = 3L, format = "f")
)
}
# Colors shared by all figures.
colors <- c(
bars = "#2a78d6",
zero = "#8c8b86",
mean = "#1b1b1b",
warned = "#d6542a"
)
theme_benchmark <- function() {
theme_minimal(base_size = 11) +
theme(
plot.title.position = "plot",
panel.grid.minor = element_blank(),
panel.spacing = grid::unit(0.8, "lines"),
strip.text.y = element_text(angle = 0, hjust = 0),
legend.position = "bottom"
)
}
#' @title Histograms of differences
#' @description Plot the distribution of estimate minus target over
#' replications, with one panel per subgroup level (rows) and per
#' combination of `columns`. All panels share the x axis. A solid gray
#' line marks zero, and a dashed line marks the mean of each panel.
#' Replications whose estimate is `NA` are dropped.
#' @param estimates The `estimates` element of the output of
#' `run_benchmark()`.
#' @param columns Character vector of columns of `estimates` that define
#' the columns of panels.
#' @param xlab Label of the x axis.
#' @return A `ggplot` object.
#' @examples
#' colon <- example_colon()
#' variables <- unique(colon$summary$variable)
#' replication <- function(method) {
#' sampled <- method$sample(colon$patient, colon$summary)
#' achieved <- group_analysis_summary(sampled, variables)
#' list(estimates = compare_summary(colon$summary, achieved), runs = NULL)
#' }
#' results <- run_benchmark(benchmark_methods(), reps = 20L, replication)
#' plot_differences(results$estimates)
plot_differences <- function(
estimates,
columns = "method",
xlab = "Hazard ratio: estimate minus target"
) {
estimates <- estimates[!is.na(estimates$difference), ]
panels <- c("subgroup", columns)
means <- stats::aggregate(
estimates["difference"],
by = estimates[panels],
FUN = mean
)
ggplot(estimates, aes(x = difference)) +
geom_histogram(bins = 40L, fill = colors[["bars"]], color = NA) +
geom_vline(xintercept = 0, color = colors[["zero"]]) +
geom_vline(
aes(xintercept = difference),
data = means,
color = colors[["mean"]],
linetype = "dashed"
) +
facet_grid(stats::reformulate(columns, "subgroup"), scales = "free_y") +
labs(
title = "Solid gray line: zero. Dashed line: mean.",
x = xlab,
y = "Replications"
) +
theme_benchmark() +
theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank())
}
#' @title Histograms of running times
#' @description Plot the distribution of the elapsed seconds per
#' optimization run on a log scale, with one panel per method.
#' Bars are stacked by whether the run converged or warned.
#' @param runs The `runs` element of the output of `run_benchmark()`.
#' @return A `ggplot` object.
#' @examples
#' runs <- data.frame(
#' method = in_order(rep(c("Unconstrained", "Constrained"), each = 50L)),
#' seconds = stats::rlnorm(100L),
#' warned = stats::runif(100L) < 0.1
#' )
#' plot_seconds(runs)
plot_seconds <- function(runs) {
runs$status <- factor(
ifelse(runs$warned, "Warned", "Converged"),
levels = c("Converged", "Warned")
)
ggplot(runs, aes(x = seconds, fill = status)) +
geom_histogram(bins = 40L, position = "stack", color = NA) +
facet_grid(method ~ ., scales = "free_y") +
scale_x_log10() +
scale_fill_manual(
values = c(Converged = colors[["bars"]], Warned = colors[["warned"]]),
drop = FALSE,
name = NULL
) +
labs(
x = "Elapsed seconds per optimization run (log scale)",
y = "Runs"
) +
theme_benchmark()
}
#' @title Table of convergence
#' @description Count the optimization runs of each method and the
#' fraction that warned that the loss did not fall below the tolerance.
#' @param runs The `runs` element of the output of `run_benchmark()`.
#' @return A `knitr_kable` table.
#' @examples
#' runs <- data.frame(
#' method = in_order(rep(c("Unconstrained", "Constrained"), each = 4L)),
#' seconds = 1,
#' warned = c(FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE)
#' )
#' table_convergence(runs)
table_convergence <- function(runs) {
counts <- stats::aggregate(
warned ~ method,
data = runs,
FUN = \(warned) c(length(warned), mean(warned))
)
knitr::kable(
data.frame(
Method = counts$method,
Runs = counts$warned[, 1L],
`Fraction warned` = format_number(counts$warned[, 2L]),
check.names = FALSE
),
align = c("l", "r", "r"),
row.names = FALSE
)
}# One replication: sample the subgroups of data$patient from data$summary,
# then compare the hazard ratios of the sampled subgroups with their
# targets. Constrained samplers must reproduce the assumed counts.
replication <- function(method, data) {
variables <- unique(data$summary$variable)
sampled <- method$sample(data$patient, data$summary)
achieved <- group_analysis_summary(sampled, variables)
if (method$constrained) {
check_counts(achieved, data$summary, "sampled dataset")
}
list(estimates = compare_summary(data$summary, achieved), runs = NULL)
}
# Simulate a dataset whose true subgroups follow the model behind
# group_analysis_probability(), with prognostic effects gamma and treatment
# effects beta on the log hazard scale. Returns the patients without their
# subgroups and the summary statistics of the true subgroups.
simulate_dataset <- function(n) {
gamma <- c(0, -0.5, 0.7)
beta <- c(-0.8, 0, 0.5)
levels <- c("low", "middle", "high")
treatment <- stats::rbinom(n, 1L, 0.5)
x <- sample.int(3L, n, replace = TRUE, prob = c(0.3, 0.3, 0.4))
event_time <- stats::rexp(n, 0.1 * exp(gamma[x] + beta[x] * treatment))
censor_time <- stats::runif(n, 0, 20)
patient <- group_data_patient(
tibble::tibble(
arm = ifelse(treatment == 1L, "treatment", "control"),
time = pmin(event_time, censor_time),
event = as.integer(event_time <= censor_time)
),
arm = "arm",
treatment = "treatment",
time = "time",
event = "event"
)
truth <- patient
truth$group <- factor(levels[x], levels = levels)
summary <- group_data_summary(
group_analysis_summary(truth, "group"),
variable = "variable",
level = "level",
patients = "patients",
events = "events",
hazard_ratio = "hazard_ratio"
)
list(patient = patient, summary = summary)
}We draw 2000 sampled datasets with each sampler.
colon <- example_colon()
set.seed(1)
colon_results <- run_benchmark(
benchmark_methods(),
reps = colon_reps,
replication = \(method) replication(method, colon)
)Colon cancer example: hazard ratio of each sampled dataset minus its target, for each subgroup level and sampler. The solid gray line marks zero, and the dashed line marks the mean.
We simulate 50 datasets and draw 200 sampled datasets from each with each sampler. Each sampled dataset is compared with the targets of its own simulated dataset, and the histograms pool all simulated datasets.
set.seed(2)
simulated_estimates <- lapply(seq_len(simulated_datasets), \(dataset) {
data <- simulate_dataset(simulated_patients)
results <- run_benchmark(
benchmark_methods(),
reps = simulated_reps,
replication = \(method) replication(method, data)
)
cbind(dataset = dataset, results$estimates)
})
simulated_estimates <- do.call(rbind, simulated_estimates)Simulated example: hazard ratio of each sampled dataset minus its target, for each subgroup level and sampler, pooled over all simulated datasets. The solid gray line marks zero, and the dashed line marks the mean.