Nothing
#' Cluster-bootstrap intervals for the audit quantities
#'
#' @description
#' Resamples whole unit histories with replacement and recomputes every audit
#' component already present in the object: the gap trajectory and
#' cumulative burden ([AIBias::aib_describe()]), the pooled recovery and
#' retention gaps ([AIBias::aib_transition()]), the amplification index
#' ([AIBias::aib_amplify()]) and the gap decomposition
#' ([AIBias::aib_decompose()]). Each replicate reuses the reference group,
#' weights, pairing rule, sign convention and sparse-cell threshold stored
#' in the object.
#'
#' @param object An `aibias` object with at least one of `$bias`,
#' `$transitions`, `$amplification` or `$decomposition` populated.
#' @param B Integer. Number of bootstrap replicates. Default 500.
#' @param conf Numeric. Confidence level. Default 0.95.
#' @param ref_group Character or NULL. Reference group. If NULL (default),
#' uses the reference group stored by the earlier steps. Supplying a
#' different group than those steps used is an error.
#' @param seed Integer. Random seed for reproducibility.
#' @param verbose Logical.
#'
#' @details
#' Units are resampled with replacement and all their occasions are kept,
#' which preserves the dependence between a unit's decisions. Intervals are
#' pointwise percentile intervals. A replicate can fail to produce a
#' quantity, for example when a resample leaves a prior-state cell empty;
#' such replicates are dropped for that quantity only, and `n_valid`
#' reports how many replicates remained. Treat intervals with `n_valid`
#' well below `B` as unreliable.
#'
#' @return The `aibias` object with `$bootstrap` populated, a list with
#' - `ci`: gap trajectory intervals (`group`, `time`, `B_raw`, `B_lo`,
#' `B_hi`), as in earlier versions
#' - `intervals`: one row per reported quantity, with columns
#' `component`, `group`, `time`, `quantity`, `estimate`, `lo`, `hi`,
#' `se`, `n_valid`
#' - `boot_draws`: replicate values of the gap trajectory
#' - `B`, `conf`, `ref_group`
#'
#' @examples
#' \donttest{
#' data(lending_panel)
#' obj <- aib_build(lending_panel, "applicant_id", "year", "race", "approved",
#' verbose = FALSE)
#' obj <- aib_describe(obj, ref_group = "White", verbose = FALSE)
#' obj <- aib_decompose(obj, ref_group = "White", verbose = FALSE)
#' obj <- aib_bootstrap(obj, B = 100, seed = 42)
#' head(obj$bootstrap$intervals)
#' }
#'
#' @export
aib_bootstrap <- function(object,
B = 500,
conf = 0.95,
ref_group = NULL,
seed = NULL,
verbose = TRUE) {
.check_aibias(object)
.check_fixed_group(object, "aib_bootstrap()")
have <- c(bias = !is.null(object$bias),
transitions = !is.null(object$transitions),
amplification = !is.null(object$amplification),
decomposition = !is.null(object$decomposition))
if (!any(have))
abort(c("Nothing to bootstrap.",
"i" = "Run `aib_describe()`, `aib_transition()`, `aib_amplify()` or `aib_decompose()` first."))
stored_refs <- unique(c(object$bias$ref_group,
object$transitions$ref_group,
object$amplification$ref_group,
object$decomposition$ref_group))
if (length(stored_refs) > 1)
abort(c("The audit steps in `object` use different reference groups.",
"i" = paste0("Found: ", paste(stored_refs, collapse = ", "),
". Rerun them with one `ref_group`.")))
if (is.null(ref_group)) {
ref_group <- stored_refs
} else if (!identical(ref_group, stored_refs)) {
abort(paste0("`ref_group` ('", ref_group, "') differs from the one used ",
"by the earlier steps ('", stored_refs, "')."))
}
ref_group <- .resolve_ref_group(object, ref_group)
if (!is.null(seed)) set.seed(seed)
alpha <- 1 - conf
data <- object$data
id_col <- object$meta$id
# Unit order follows .decision_matrix() so both resamples line up
dm <- .decision_matrix(object)
unit_rows <- split(seq_len(nrow(data)),
factor(data[[id_col]], levels = dm$ids))
n_units <- length(dm$ids)
focal <- setdiff(as.character(object$meta$groups), ref_group)
weights <- object$bias$weights
lag_tr <- object$transitions$lag %||% "scheduled"
lag_amp <- object$amplification$lag %||% lag_tr
sign_amp <- object$amplification$sign %||% "mechanism"
min_cell <- object$decomposition$min_cell %||% 10
if (verbose) cli_alert_info("Running {B} cluster-bootstrap replicates...")
draws <- vector("list", B)
for (b in seq_len(B)) {
idx <- sample.int(n_units, n_units, replace = TRUE)
draws[[b]] <- .boot_one(object, idx, unit_rows, dm, have, ref_group,
focal, weights, lag_tr, lag_amp, sign_amp,
min_cell, b)
}
pick <- function(name) {
out <- lapply(draws, `[[`, name)
out <- out[!vapply(out, is.null, logical(1))]
if (length(out) == 0) return(NULL)
bind_rows(out)
}
intervals <- list()
if (have["bias"]) {
traj_obs <- object$bias$trajectory
intervals$trajectory <- .boot_summarise(
pick("trajectory"), traj_obs, c("group", "time"),
c("B_raw", "B_smd"), "trajectory", alpha, B)
cum_obs <- object$bias$cumulative
intervals$cumulative <- .boot_summarise(
pick("cumulative"), cum_obs, "group",
c("CB_raw", "CB_normalized"), "cumulative", alpha, B)
}
if (have["transitions"]) {
tr_obs <- left_join(
object$transitions$recovery_gap |> select("group", "recovery_gap"),
object$transitions$retention_gap |> select("group", "retention_gap"),
by = "group")
tr_obs$group <- as.character(tr_obs$group)
intervals$transitions <- .boot_summarise(
pick("transitions"), tr_obs, "group",
c("recovery_gap", "retention_gap"), "transitions", alpha, B)
}
if (have["amplification"]) {
intervals$amplification <- .boot_summarise(
pick("amplification"), object$amplification$index, c("group", "time"),
"A_index", "amplification", alpha, B)
intervals$amplification_total <- .boot_summarise(
pick("amplification_total"), object$amplification$cumulative, "group",
"A_cumulative", "amplification", alpha, B)
}
if (have["decomposition"]) {
comp_vars <- c("gap_prev", "gap_curr", "change", "gap_pair_prev",
"gap_pair_curr", "carry", "decay", "recovery",
"retention", "sample_prev", "sample_curr",
"sample_change")
intervals$decomposition <- .boot_summarise(
pick("decomposition"), object$decomposition$steps, c("group", "time"),
comp_vars, "decomposition", alpha, B)
intervals$decomposition_total <- .boot_summarise(
pick("decomposition_total"), object$decomposition$totals, "group",
c("change", "decay", "recovery", "retention", "sample_change"),
"decomposition_total", alpha, B)
}
intervals <- bind_rows(intervals)
if (!"time" %in% names(intervals)) intervals$time <- NA_integer_
intervals <- intervals[, c("component", "group", "time", "quantity",
"estimate", "lo", "hi", "se", "n_valid")]
# Backward-compatible trajectory table
ci <- NULL
boot_df <- pick("trajectory")
if (have["bias"]) {
tr <- intervals[intervals$component == "trajectory" &
intervals$quantity == "B_raw", ]
ci <- tibble(group = tr$group, time = tr$time, B_raw = tr$estimate,
B_lo = tr$lo, B_hi = tr$hi)
}
object$bootstrap <- list(
ci = ci,
intervals = intervals,
boot_draws = boot_df,
B = B,
conf = conf,
ref_group = ref_group
)
if (verbose) {
low <- intervals[intervals$n_valid < 0.9 * B, ]
if (nrow(low) > 0)
cli_alert_warning(
"{nrow(low)} quantit{?y/ies} estimable in fewer than 90% of replicates; see `n_valid`.")
cli_alert_success("Bootstrap complete ({conf*100}% percentile intervals).")
}
invisible(object)
}
# ---- Internal: one replicate -----------------------------------------------
.boot_one <- function(object, idx, unit_rows, dm, have, ref_group, focal,
weights, lag_tr, lag_amp, sign_amp, min_cell, b) {
out <- list()
id_col <- object$meta$id
fast <- identical(lag_tr, "scheduled") && identical(lag_amp, "scheduled")
if (fast && (have["bias"] || have["transitions"] || have["amplification"])) {
fs <- .fast_stats(dm$Y[idx, , drop = FALSE], dm$G[idx], ref_group, focal,
weights, sign_amp)
if (have["bias"]) {
out$trajectory <- mutate(fs$trajectory, rep = b)
out$cumulative <- mutate(fs$cumulative, rep = b)
}
if (have["transitions"]) out$transitions <- mutate(fs$transitions, rep = b)
if (have["amplification"]) {
out$amplification <- mutate(fs$amplification, rep = b)
out$amplification_total <- mutate(fs$amplification_total, rep = b)
}
}
if (!fast && (have["bias"] || have["transitions"] || have["amplification"])) {
rows <- unit_rows[idx]
data_b <- object$data[unlist(rows, use.names = FALSE), , drop = FALSE]
data_b[[id_col]] <- rep.int(seq_along(idx), lengths(rows))
obj_b <- object
obj_b$data <- data_b
obj_b$rates <- .compute_rates(data_b, object$meta$group,
object$meta$decision, object$meta$time_int)
obj_b$bias <- obj_b$transitions <- obj_b$amplification <- NULL
obj_b$decomposition <- obj_b$bootstrap <- NULL
if (have["bias"]) {
res <- tryCatch(
aib_describe(obj_b, ref_group = ref_group, weights = weights,
verbose = FALSE),
error = function(e) NULL)
if (!is.null(res)) {
out$trajectory <- res$bias$trajectory |>
select("group", "time", "B_raw", "B_smd") |>
mutate(rep = b)
out$cumulative <- res$bias$cumulative |>
select("group", "CB_raw", "CB_normalized") |>
mutate(rep = b)
}
}
if (have["transitions"] || have["amplification"]) {
res <- tryCatch(
aib_transition(obj_b, ref_group = ref_group, lag = lag_tr,
verbose = FALSE),
error = function(e) NULL)
if (!is.null(res) && have["transitions"]) {
tr <- left_join(
res$transitions$recovery_gap |> select("group", "recovery_gap"),
res$transitions$retention_gap |> select("group", "retention_gap"),
by = "group")
tr$group <- as.character(tr$group)
out$transitions <- mutate(tr, rep = b)
}
if (have["amplification"]) {
base <- if (is.null(res)) obj_b else res
res2 <- tryCatch(
aib_amplify(base, ref_group = ref_group, sign = sign_amp,
lag = lag_amp, verbose = FALSE),
error = function(e) NULL)
if (!is.null(res2)) {
out$amplification <- res2$amplification$index |>
select("group", "time", "A_index") |>
mutate(rep = b)
out$amplification_total <- res2$amplification$cumulative |>
select("group", "A_cumulative") |>
mutate(rep = b)
}
}
}
}
if (have["decomposition"]) {
st <- .decompose_core(dm$Y[idx, , drop = FALSE], dm$R[idx, , drop = FALSE],
dm$G[idx], ref_group, focal, min_cell)
st$rep <- b
out$decomposition <- st
tot <- .decompose_totals(st)
tot$rep <- b
out$decomposition_total <- tot
}
out
}
# Matrix versions of the trajectory, cumulative burden, pooled transition
# gaps and amplification index for scheduled pairing. They reproduce
# aib_describe(), aib_transition() and aib_amplify() (tested against them)
# and make the bootstrap fast.
.fast_stats <- function(Y, G, ref_group, focal, weights, sign) {
nT <- ncol(Y)
Op <- !is.na(Y)
Yz <- Y
Yz[!Op] <- 0L
prv <- seq_len(nT - 1L)
cur <- prv + 1L
B <- Op[, prv, drop = FALSE] & Op[, cur, drop = FALSE]
Yp <- Yz[, prv, drop = FALSE] == 1L
Yc <- Yz[, cur, drop = FALSE] == 1L
pi_all <- colSums(Yz) / colSums(Op)
if (is.null(weights)) weights <- rep(1, nT)
gstats <- function(h) {
w <- G == h
P1 <- B[w, , drop = FALSE] & Yp[w, , drop = FALSE]
P0 <- B[w, , drop = FALSE] & !Yp[w, , drop = FALSE]
Ych <- Yc[w, , drop = FALSE]
list(rate = colSums(Yz[w, , drop = FALSE]) / colSums(Op[w, , drop = FALSE]),
n0 = colSums(P0), n1 = colSums(P1),
c01 = colSums(P0 & Ych), c11 = colSums(P1 & Ych))
}
sr <- gstats(ref_group)
traj <- cum <- trans <- amp <- amp_tot <- vector("list", length(focal))
for (j in seq_along(focal)) {
g <- focal[j]
sg <- gstats(g)
b_raw <- .nan_to_na(sg$rate - sr$rate)
den <- sqrt(pi_all * (1 - pi_all))
b_smd <- ifelse(den > 0, b_raw / den, NA_real_)
traj[[j]] <- data.frame(group = g, time = seq_len(nT), B_raw = b_raw,
B_smd = b_smd, stringsAsFactors = FALSE)
keep <- !is.na(b_raw)
cb <- sum(weights[keep] * b_raw[keep])
cum[[j]] <- data.frame(group = g, CB_raw = cb,
CB_normalized = cb / sum(weights[keep]),
stringsAsFactors = FALSE)
trans[[j]] <- data.frame(
group = g,
recovery_gap = .nan_to_na(sum(sg$c01) / sum(sg$n0) - sum(sr$c01) / sum(sr$n0)),
retention_gap = .nan_to_na(sum(sg$c11) / sum(sg$n1) - sum(sr$c11) / sum(sr$n1)),
stringsAsFactors = FALSE)
a <- .nan_to_na((sg$c11 / sg$n1 - sr$c11 / sr$n1) -
(sg$c01 / sg$n0 - sr$c01 / sr$n0))
if (sign == "mechanism") a <- -a
amp[[j]] <- data.frame(group = g, time = cur, A_index = a,
stringsAsFactors = FALSE)
amp_tot[[j]] <- data.frame(group = g, A_cumulative = if (all(is.na(a))) NA_real_ else sum(a, na.rm = TRUE),
stringsAsFactors = FALSE)
}
list(trajectory = do.call(rbind, traj), cumulative = do.call(rbind, cum),
transitions = do.call(rbind, trans), amplification = do.call(rbind, amp),
amplification_total = do.call(rbind, amp_tot))
}
.boot_summarise <- function(draws, observed, keys, vars, component,
alpha, B) {
if (is.null(draws) || nrow(draws) == 0) return(NULL)
observed <- as.data.frame(observed)
draws <- as.data.frame(draws)
observed$group <- as.character(observed$group)
draws$group <- as.character(draws$group)
res <- lapply(vars, function(v) {
key_obs <- do.call(paste, c(observed[keys], sep = "\r"))
key_drw <- do.call(paste, c(draws[keys], sep = "\r"))
rows <- lapply(seq_len(nrow(observed)), function(i) {
x <- draws[[v]][key_drw == key_obs[i]]
x <- x[is.finite(x)]
nv <- length(x)
data.frame(
component = component,
group = observed$group[i],
time = if ("time" %in% keys) observed$time[i] else NA_integer_,
quantity = v,
estimate = observed[[v]][i],
lo = if (nv > 1) unname(quantile(x, alpha / 2)) else NA_real_,
hi = if (nv > 1) unname(quantile(x, 1 - alpha / 2)) else NA_real_,
se = if (nv > 1) sd(x) else NA_real_,
n_valid = nv,
stringsAsFactors = FALSE
)
})
do.call(rbind, rows)
})
as_tibble(do.call(rbind, res))
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.