R/aib_amplify.R

Defines functions aib_amplify

Documented in aib_amplify

#' Contrast the recovery and retention gaps (amplification index)
#'
#' @description
#' Computes \eqn{A_{g,r}(t) = B_{g,r}(t|1) - B_{g,r}(t|0)}, where
#' \eqn{B_{g,r}(t|d)} is the focal-minus-reference gap in the decision rate
#' at \eqn{t} among units whose decision at \eqn{t-1} was \eqn{d}. Under the
#' default sign convention this is the recovery gap minus the retention gap.
#' The index measures how far the conditional gap depends on the prior
#' decision. It does not by itself say whether the overall gap grew or
#' shrank, or why: use [AIBias::aib_decompose()] for that.
#'
#' @param object An `aibias` object from [AIBias::aib_build()]. Recommended to run
#'   [AIBias::aib_transition()] first.
#' @param ref_group Character. Reference group.
#' @param sign Character; \code{"mechanism"} (default) or \code{"legacy"}.
#'   Under \code{"mechanism"} the reported index is
#'   \eqn{(p_{11,r} - p_{11,g}) - (p_{01,r} - p_{01,g})}: negative values mean
#'   the focal group's recovery shortfall exceeds its retention shortfall,
#'   positive values the reverse. Under \code{"legacy"} the sign is flipped,
#'   \eqn{B_{g,r}(t|1) - B_{g,r}(t|0)}.
#' @param lag Character or NULL. Pairing rule, as in
#'   [AIBias::aib_transition()]. If NULL, uses the rule stored by
#'   `aib_transition()` when present, otherwise `"scheduled"`.
#' @param verbose Logical.
#'
#' @return The `aibias` object with `$amplification` populated. Contains:
#'   - `lagged_disparity`: \eqn{B_{g,r}(t|d)} for d equal to 0 or 1
#'   - `index`: \eqn{A_{g,r}(t)} by group and occasion
#'   - `cumulative`: sum, mean and maximum of \eqn{|A_{g,r}(t)|} over occasions
#'   - `matrix_norm`: \eqn{L_1} distance between pooled transition matrices
#'   - `narratives`, `ref_group`, `sign`, `lag`
#'
#' @details
#' A zero index means the recovery and retention gaps are equal. It does
#' not mean prior decisions are irrelevant: when both conditional gaps are
#' negative and equal, the overall gap can still widen from one occasion to
#' the next because the focal group enters each occasion with fewer
#' favorable decisions. See the zero-index example in
#' `vignette("introduction", package = "AIBias")`. The index is descriptive;
#' reading it as a causal effect of prior decisions needs assumptions the
#' audit data cannot check.
#'
#' @examples
#' data(lending_panel)
#' obj <- aib_build(lending_panel, "applicant_id", "year", "race", "approved")
#' obj <- aib_transition(obj, ref_group = "White")
#' obj <- aib_amplify(obj, ref_group = "White")
#' obj$amplification$index
#'
#' @export
aib_amplify <- function(object,
                        ref_group = NULL,
                        sign      = c("mechanism", "legacy"),
                        verbose   = TRUE,
                        lag       = NULL) {
  .check_aibias(object)
  sign <- match.arg(sign)

  ref_group <- .resolve_ref_group(object, ref_group)
  data      <- object$data
  id_col    <- object$meta$id
  time_col  <- object$meta$time_int
  grp_col   <- object$meta$group
  dec_col   <- object$meta$decision
  groups    <- setdiff(levels(data[[grp_col]]), ref_group)

  # ---- Build lag structure ------------------------------------------------
  if (is.null(lag)) {
    lag <- if (!is.null(object$transitions$lag)) object$transitions$lag else "scheduled"
  }
  lag    <- match.arg(lag, c("scheduled", "recorded"))
  lagged <- .lagged_pairs(object, lag)

  # ---- Lagged group-conditional decision rates ----------------------------
  # B_{g,r}(t | d) for d in {0, 1}
  lagged_rates <- lagged |>
    group_by(.data[[grp_col]], .data[[time_col]], .data$D_lag) |>
    summarise(
      rate_cond = mean(.data[[dec_col]], na.rm = TRUE),
      n         = n(),
      .groups   = "drop"
    ) |>
    rename(group = 1, time = 2, d_lag = 3)

  ref_lagged <- lagged_rates |>
    filter(.data$group == ref_group) |>
    select("time", "d_lag", rate_ref_cond = "rate_cond")

  # ---- Compute B(t|d) and amplification index per group ------------------
  amp_list <- lapply(groups, function(g) {
    g_lag <- lagged_rates |>
      filter(.data$group == g) |>
      left_join(ref_lagged, by = c("time", "d_lag")) |>
      mutate(
        B_cond = .data$rate_cond - .data$rate_ref_cond,
        group  = g
      )

    # A(t) = B(t|1) - B(t|0)
    amp_by_time <- g_lag |>
      select("group", "time", "d_lag", "B_cond") |>
      pivot_wider(names_from   = "d_lag",
                  values_from  = "B_cond",
                  names_prefix = "B_d")
    if (!"B_d0" %in% names(amp_by_time)) amp_by_time$B_d0 <- NA_real_
    if (!"B_d1" %in% names(amp_by_time)) amp_by_time$B_d1 <- NA_real_
    amp_by_time <- amp_by_time |>
      mutate(
        A_index    = .data$B_d1 - .data$B_d0,
        amplifying = abs(.data$A_index) > 1e-10
      )

    amp_by_time
  })

  amp_index <- bind_rows(amp_list)
  # Keep a row for every focal group and step, so steps without adjacent
  # pairs (or with an empty prior-state cell) give NA rather than no row
  steps <- if (object$meta$n_times >= 2) seq.int(2L, object$meta$n_times) else integer(0)
  full  <- tidyr::expand_grid(group = groups, time = steps)
  if (nrow(amp_index) == 0) {
    amp_index <- tibble(group = character(), time = integer(), B_d0 = numeric(),
                        B_d1 = numeric(), A_index = numeric(), amplifying = logical())
  }
  amp_index <- full |>
    left_join(amp_index |> mutate(time = as.integer(.data$time)),
              by = c("group", "time")) |>
    mutate(amplifying = !is.na(.data$A_index) & .data$amplifying %in% TRUE)

  # ---- Apply sign convention ----------------------------------------------
  # "mechanism": negate so negative = recovery-driven, positive = retention-driven
  # "legacy":    keep as B(t|1) - B(t|0)
  if (sign == "mechanism") {
    amp_index$A_index <- -amp_index$A_index
  }

  # ---- Cumulative amplification -------------------------------------------
  cumulative_amp <- amp_index |>
    group_by(.data$group) |>
    summarise(
      A_cumulative = if (all(is.na(.data$A_index))) NA_real_ else
        sum(.data$A_index, na.rm = TRUE),
      A_mean       = .nan_to_na(mean(.data$A_index, na.rm = TRUE)),
      A_max        = .safe_max(abs(.data$A_index)),
      T_amplifying = sum(.data$amplifying, na.rm = TRUE),
      .groups      = "drop"
    )

  # ---- Matrix norm amplification (if transitions computed) ----------------
  matrix_norm <- NULL
  if (!is.null(object$transitions)) {
    mats    <- object$transitions$matrices
    mat_ref <- mats[[ref_group]]

    matrix_norm <- lapply(groups, function(g) {
      mat_g  <- mats[[g]]
      norm_t <- if (all(!is.na(mat_g)) && all(!is.na(mat_ref))) {
        sum(abs(mat_g - mat_ref))
      } else NA_real_
      tibble(group = g, matrix_L1_norm = norm_t)
    }) |> bind_rows()
  }

  # ---- Narrative interpretation -------------------------------------------
  narratives <- lapply(groups, function(g) {
    ca  <- cumulative_amp |> filter(.data$group == g)
    rg  <- object$transitions$recovery_gap  |> filter(.data$group == g) |>
      pull(.data$recovery_gap)
    rtn <- object$transitions$retention_gap |> filter(.data$group == g) |>
      pull(.data$retention_gap)
    if (length(rg)  == 0 || is.na(rg[1]))  rg  <- NA_real_
    if (length(rtn) == 0 || is.na(rtn[1])) rtn <- NA_real_
    rg  <- rg[1]; rtn <- rtn[1]
    A   <- ca$A_cumulative

    msgs <- character(0)
    if (!is.na(rg) && rg < -0.05)
      msgs <- c(msgs, sprintf(
        "Recovery disparity = %.3f: group %s is less likely to regain favorable status after an adverse decision.",
        rg, g))
    if (!is.na(rtn) && rtn < -0.05)
      msgs <- c(msgs, sprintf(
        "Retention disparity = %.3f: group %s is less likely to retain favorable status across periods.",
        rtn, g))
    if (!is.null(A) && !is.na(A) && abs(A) > 0.1)
      msgs <- c(msgs, sprintf(
        "Cumulative index A = %.3f: recovery and retention gaps differ, so the group gap depends on the prior decision.",
        A))

    tibble(group = g, narrative = paste(msgs, collapse = " | "))
  }) |> bind_rows()

  object$amplification <- list(
    lagged_disparity = bind_rows(amp_list |> lapply(\(x) {
      x |> select("group", "time", B_d0 = "B_d0", B_d1 = "B_d1")
    })),
    index        = amp_index,
    cumulative   = cumulative_amp,
    matrix_norm  = matrix_norm,
    narratives   = narratives,
    ref_group    = ref_group,
    sign         = sign,
    lag          = lag
  )

  if (verbose) {
    cli_h2("Amplification Analysis (ref: {ref_group}, sign: {sign})")
    for (g in groups) {
      ca <- cumulative_amp |> filter(.data$group == g)
      direction <- if (is.na(ca$A_mean)) {
        "not estimable: a prior-state cell is empty"
      } else if (sign == "mechanism") {
        if (abs(ca$A_mean) < 1e-10) {
          "recovery and retention gaps equal"
        } else if (ca$A_mean < 0) {
          "recovery gap larger"
        } else {
          "retention gap larger"
        }
      } else {
        if (abs(ca$A_mean) < 1e-10) {
          "recovery and retention gaps equal"
        } else if (ca$A_mean < 0) "retention gap larger" else "recovery gap larger"
      }
      cli_li("Group {g}: A_cumulative = {round(ca$A_cumulative, 3)} ({direction})")
    }
  }

  invisible(object)
}

Try the AIBias package in your browser

Any scripts or data that you put into this service are public.

AIBias documentation built on Dec. 1, 2026, 1:06 a.m.