Rendered on 2026-11-30 with retrogroup 0.0.3 at commit
35499a3.
vignette("optimization", package = "retrogroup") claims
that optimization refines a sampled dataset until its subgroup hazard
ratios match their targets. This vignette checks that claim by
simulation for group_optimize_unconstrained() and
group_optimize_constrained(). It reports how closely the
optimized hazard ratios match their targets, how long optimization
takes, and how often optimization stops before the loss falls below the
tolerance.
vignette("benchmarks_sampling", package = "retrogroup")
benchmarks the samplers.
Each replication creates its own targets from a known assignment of
subgroups, so a solution with zero loss always exists. Starting from the
patients of group_example_patient() and the summary
statistics of group_example_summary(), each replication of
each method does the following:
group_analysis_summary(), and convert
them to the standard format with group_data_summary(). The
hazard ratio of each subgroup level is its target, and the numbers of
patients and events are the assumed counts. Each hazard ratio comes from
a Cox proportional hazards model fit to the patients in that level, with
treatment as the only covariate and Efron’s method for ties.group_analysis_summary(), and
subtract the targets.We test two methods:
group_sample_unconstrained() and
group_optimize_unconstrained().group_sample_constrained() and
group_optimize_constrained().The unconstrained optimizer takes a flip step or a swap step with
probability 1/2 each, and the constrained optimizer takes only swap
steps (see the “Moves” section of
vignette("optimization", package = "retrogroup")). A flip
step fits one Cox model per subgroup level and a swap step fits two,
which affects the elapsed time per iteration.
For the constrained method, the benchmark stops with an error unless the number of patients in each subgroup level exactly matches the colon cancer summary statistics in the ground truth and the assumed counts of the targets in the starting point and the optimized dataset.
Every optimization uses tolerance = 0.001 and at most 10000
iterations per subgroup variable. The loss is the Euclidean distance
between the optimized and target hazard ratios, so a loss below the
tolerance means that every hazard ratio is within 0.001 of its target. A
run stops when its loss falls below the tolerance. Otherwise, it stops
at the maximum number of iterations and throws a warning of class
"retrogroup_warning", and we count the run as warned. The
elapsed time covers the call to the optimizer only.
# 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 of one method, following steps 1 to 5 of the Design
# section. Returns estimates (one row per subgroup level) and runs (one row).
replication <- function(method, colon) {
variables <- unique(colon$summary$variable)
# Step 1: ground truth.
truth <- method$sample(colon$patient, colon$summary)
# Step 2: targets.
truth_statistics <- group_analysis_summary(truth, variables)
targets <- group_data_summary(
truth_statistics,
variable = "variable",
level = "level",
patients = "patients",
events = "events",
hazard_ratio = "hazard_ratio"
)
# Step 3: starting point.
start <- method$sample(colon$patient, targets)
# Step 4: optimization.
run <- optimize_once(method$optimize, start, targets, iterations, tolerance)
# Step 5: comparison.
achieved <- group_analysis_summary(run$optimized, variables)
if (method$constrained) {
check_counts(truth_statistics, colon$summary, "ground truth")
check_counts(
group_analysis_summary(start, variables),
targets,
"starting point"
)
check_counts(achieved, targets, "optimized dataset")
}
list(
estimates = compare_summary(targets, achieved),
runs = data.frame(seconds = run$seconds, warned = run$warned)
)
}We run 1000 replications of each method.
colon <- example_colon()
set.seed(1)
colon_results <- run_benchmark(
benchmark_methods(),
reps = reps,
replication = \(method) replication(method, colon)
)The figure shows histograms of the hazard ratio of each optimized dataset minus its target, with one panel per subgroup level and method. A narrow histogram centered on zero means that each optimized dataset reproduces its own targets. Differences on the order of the tolerance (0.001) or less are negligible.
Colon cancer example: hazard ratio of each optimized dataset minus its target, for each subgroup level and method. The solid gray line marks zero, and the dashed line marks the mean.
The table shows the fraction of optimization runs that warned.
| Method | Runs | Fraction warned |
|---|---|---|
| Unconstrained | 1000 | 0.000 |
| Constrained | 1000 | 0.000 |
The figure shows histograms of the elapsed time of each optimization run.
Colon cancer example: elapsed seconds per optimization run, excluding sampling and summary statistics, for each method. Bars are stacked by whether the run converged or warned.