tests/testthat/test-decompose.R

# ---- Helpers ---------------------------------------------------------------

# Deterministic two-state chain whose transition shares are exact
exact_chain <- function(n, init, p01, p11, n_times, group) {
  D  <- matrix(NA_integer_, n, n_times)
  n1 <- round(n * init)
  D[, 1] <- c(rep(1L, n1), rep(0L, n - n1))
  for (t in 2:n_times) {
    prev <- D[, t - 1]
    cur  <- integer(n)
    i1 <- which(prev == 1L)
    i0 <- which(prev == 0L)
    k11 <- round(length(i1) * p11)
    k01 <- round(length(i0) * p01)
    if (k11 > 0) cur[i1[seq_len(k11)]] <- 1L
    if (k01 > 0) cur[i0[seq_len(k01)]] <- 1L
    D[, t] <- cur
  }
  data.frame(id = rep(paste0(group, seq_len(n)), times = n_times),
             time = rep(seq_len(n_times), each = n),
             group = group, decision = as.vector(D),
             stringsAsFactors = FALSE)
}

zero_index_panel <- function() {
  rbind(exact_chain(1000, 0.5, 0.2, 0.8, 3, "ref"),
        exact_chain(1000, 0.5, 0.1, 0.7, 3, "focal"))
}

gap_panel <- function() {
  set.seed(11)
  d <- data.frame(id = rep(1:60, each = 4), time = rep(1:4, 60),
                  group = rep(c("A", "B"), each = 120),
                  decision = rbinom(240, 1, 0.5))
  d <- d[-c(2, 6, 10, 50, 51, 130, 134, 200), ]
  d$decision[c(20, 140)] <- NA
  d
}

build <- function(d) aib_build(d, "id", "time", "group", "decision",
                               verbose = FALSE)


# ---- Zero-index counterexample ----------------------------------------------

test_that("equal conditional gaps give a zero index while the gap widens", {
  obj <- build(zero_index_panel())
  obj <- aib_transition(obj, ref_group = "ref", verbose = FALSE)
  obj <- aib_amplify(obj, ref_group = "ref", verbose = FALSE)
  obj <- aib_decompose(obj, ref_group = "ref", verbose = FALSE)

  expect_equal(obj$amplification$index$A_index, c(0, 0), tolerance = 1e-12)

  st <- obj$decomposition$steps
  expect_equal(st$gap_prev, c(0, -0.10), tolerance = 1e-12)
  expect_equal(st$gap_curr, c(-0.10, -0.16), tolerance = 1e-12)
  # Step 2 -> 3: q_bar = 0.45, s_bar = 0.6, prior paired gap = -0.10
  expect_equal(st$carry[2],     -0.06,  tolerance = 1e-12)
  expect_equal(st$decay[2],      0.04,  tolerance = 1e-12)
  expect_equal(st$recovery[2],  -0.055, tolerance = 1e-12)
  expect_equal(st$retention[2], -0.045, tolerance = 1e-12)
  expect_equal(st$sample_change, c(0, 0), tolerance = 1e-12)
  expect_true(all(st$supported))
})


# ---- Exact reconstruction ----------------------------------------------------

test_that("components reconstruct the observed change exactly", {
  sim <- aib_simulate(n = c(300, 250, 200), n_times = 5,
                      groups = c("A", "B", "C"),
                      init = c(0.6, 0.4, 0.5), p01 = c(0.3, 0.2, 0.25),
                      p11 = c(0.8, 0.6, 0.7),
                      observe = rbind(c(0.9, 0.6, 0.7), c(0.95, 0.9, 0.85)),
                      seed = 3)
  sim <- sim[-sample(nrow(sim), 200), ]          # also drop whole rows
  obj <- aib_decompose(build(sim), ref_group = "A", verbose = FALSE)
  st  <- obj$decomposition$steps

  expect_equal(nrow(st), 2 * 4)
  ok <- st$supported
  expect_true(all(abs(st$recon_error[ok]) < 1e-12))
  # Level form
  expect_equal(st$gap_curr[ok],
               (st$carry + st$recovery + st$retention + st$sample_curr)[ok],
               tolerance = 1e-12)
  # Paired-gap form
  expect_equal(st$gap_pair_curr[ok],
               (st$carry + st$recovery + st$retention)[ok],
               tolerance = 1e-12)
  # Totals telescope to last minus first gap
  tot <- obj$decomposition$totals
  for (g in tot$group) {
    s <- st[st$group == g, ]
    expect_equal(tot$change[tot$group == g],
                 s$gap_curr[nrow(s)] - s$gap_prev[1], tolerance = 1e-12)
  }
})

test_that("gaps match direct calculation from the data", {
  d   <- gap_panel()
  obj <- aib_decompose(build(d), ref_group = "A", verbose = FALSE)
  st  <- obj$decomposition$steps
  rate <- function(g, t) mean(d$decision[d$group == g & d$time == t],
                              na.rm = TRUE)
  for (k in 2:4) {
    expect_equal(st$gap_curr[st$time == k], rate("B", k) - rate("A", k))
    expect_equal(st$gap_prev[st$time == k], rate("B", k - 1) - rate("A", k - 1))
  }
})

test_that("complete panels have no sample terms", {
  obj <- aib_decompose(build(zero_index_panel()), ref_group = "ref",
                       verbose = FALSE)
  st <- obj$decomposition$steps
  expect_equal(st$sample_prev, c(0, 0))
  expect_equal(st$sample_curr, c(0, 0))
  expect_equal(st$gap_pair_prev, st$gap_prev)
})


# ---- Reference reversal ------------------------------------------------------

test_that("swapping focal and reference negates every component", {
  d  <- gap_panel()
  sa <- aib_decompose(build(d), ref_group = "A", verbose = FALSE)$decomposition$steps
  sb <- aib_decompose(build(d), ref_group = "B", verbose = FALSE)$decomposition$steps
  for (v in c("gap_prev", "gap_curr", "change", "carry", "decay",
              "recovery", "retention", "sample_prev", "sample_curr",
              "sample_change")) {
    expect_equal(sb[[v]], -sa[[v]], tolerance = 1e-12, info = v)
  }
})


# ---- Missed occasions --------------------------------------------------------

test_that("a missed occasion breaks the scheduled pair but not the recorded one", {
  d <- data.frame(id = c(1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4),
                  time = c(1, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3),
                  group = c("A", "A", "A", "A", "A", "B", "B", "B",
                            "B", "B", "B"),
                  decision = c(0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1))
  obj <- build(d)
  sch <- aib_transition(obj, ref_group = "A", lag = "scheduled",
                        verbose = FALSE)$transitions$counts
  rec <- aib_transition(obj, ref_group = "A", lag = "recorded",
                        verbose = FALSE)$transitions$counts
  # Unit 1 (A) jumps from occasion 1 to 3
  a3_sch <- sch[sch$group == "A" & sch$time == 3, ]
  a3_rec <- rec[rec$group == "A" & rec$time == 3, ]
  expect_equal(sum(a3_sch$n_total), 1)
  expect_equal(sum(a3_rec$n_total), 2)

  st <- aib_decompose(obj, ref_group = "A", verbose = FALSE)$decomposition$steps
  expect_equal(st$n_pair_g, c(2, 2))
  expect_equal(st$n_pair_ref, c(1, 1))
  expect_equal(st$n_obs_curr_ref, c(1, 2))
})

test_that("lag = 'recorded' reproduces AIBias 0.1.1", {
  obj <- build(gap_panel())
  obj <- aib_transition(obj, ref_group = "A", lag = "recorded", verbose = FALSE)
  obj <- aib_amplify(obj, ref_group = "A", verbose = FALSE)
  expect_equal(obj$amplification$lag, "recorded")
  # Reference values computed with AIBias 0.1.1
  expect_equal(obj$transitions$recovery_gap$recovery_gap, 0.0711538462,
               tolerance = 1e-9)
  expect_equal(obj$transitions$retention_gap$retention_gap, 0.2673835125,
               tolerance = 1e-9)
  expect_equal(obj$amplification$index$A_index,
               c(-0.1756410256, -0.0454545455, -0.380952381),
               tolerance = 1e-9)
})

test_that("scheduled and recorded pairing agree on complete balanced panels", {
  obj <- build(zero_index_panel())
  a <- aib_transition(obj, ref_group = "ref", lag = "scheduled", verbose = FALSE)
  b <- aib_transition(obj, ref_group = "ref", lag = "recorded",  verbose = FALSE)
  expect_equal(a$transitions$pooled, b$transitions$pooled)
})

test_that("rows with a missing decision count as present but unscored", {
  d <- zero_index_panel()
  d$decision[d$group == "focal" & d$time == 2][1:100] <- NA
  st <- aib_decompose(build(d), ref_group = "ref",
                      verbose = FALSE)$decomposition$steps
  expect_equal(st$n_present_curr_g[1], 1000)
  expect_equal(st$n_obs_curr_g[1], 900)
  expect_equal(st$n_pair_g, c(900, 900))
  expect_true(all(abs(st$recon_error) < 1e-12))
})


# ---- Empty and sparse cells --------------------------------------------------

test_that("an empty prior-state cell gives NA components and a flag", {
  d <- rbind(exact_chain(50, 1.0, 0.2, 0.8, 3, "ref"),   # all favorable at t = 1
             exact_chain(50, 0.5, 0.1, 0.7, 3, "focal"))
  obj <- aib_decompose(build(d), ref_group = "ref", min_cell = 5,
                       verbose = FALSE)
  st  <- obj$decomposition$steps
  expect_false(st$supported[1])
  expect_true(is.na(st$recovery[1]))
  expect_true(is.na(st$decay[1]))
  expect_false(is.na(st$change[1]))
  expect_true(st$supported[2])
  expect_equal(obj$decomposition$totals$n_unsupported, 1)
  expect_output(summary(obj), "empty cell")
})

test_that("small cells are flagged as sparse", {
  d <- rbind(exact_chain(40, 0.9, 0.2, 0.8, 3, "ref"),
             exact_chain(40, 0.5, 0.1, 0.7, 3, "focal"))
  st <- aib_decompose(build(d), ref_group = "ref", min_cell = 10,
                      verbose = FALSE)$decomposition$steps
  expect_true(st$sparse[1])            # 4 reference units with prior 0
  expect_true(st$supported[1])
})


# ---- Large-sample recovery ---------------------------------------------------

test_that("components approach their population values", {
  sim <- aib_simulate(n = 40000, n_times = 3, groups = c("r", "g"),
                      init = c(0.6, 0.4), p01 = c(0.3, 0.2),
                      p11 = c(0.8, 0.6), seed = 7)
  st <- aib_decompose(build(sim), ref_group = "r",
                      verbose = FALSE)$decomposition$steps
  # Step 1 -> 2 population values
  q_bar <- 0.5; s_bar <- ((0.8 - 0.3) + (0.6 - 0.2)) / 2
  expect_lt(abs(st$carry[1]     - s_bar * (0.4 - 0.6)),       0.01)
  expect_lt(abs(st$recovery[1]  - (1 - q_bar) * (0.2 - 0.3)), 0.01)
  expect_lt(abs(st$retention[1] - q_bar * (0.6 - 0.8)),       0.01)
})


# ---- Bootstrap ---------------------------------------------------------------

test_that("bootstrap covers decomposition components and reports n_valid", {
  sim <- aib_simulate(n = 150, n_times = 3, seed = 5)
  obj <- build(sim)
  obj <- aib_describe(obj, ref_group = "reference", verbose = FALSE)
  obj <- aib_transition(obj, ref_group = "reference", verbose = FALSE)
  obj <- aib_amplify(obj, ref_group = "reference", verbose = FALSE)
  obj <- aib_decompose(obj, ref_group = "reference", verbose = FALSE)
  obj <- aib_bootstrap(obj, B = 40, seed = 1, verbose = FALSE)

  bi <- obj$bootstrap$intervals
  expect_true(all(c("trajectory", "cumulative", "transitions",
                    "amplification", "decomposition",
                    "decomposition_total") %in% bi$component))
  expect_true(all(bi$n_valid <= 40))
  dc <- bi[bi$component == "decomposition" & bi$quantity == "recovery", ]
  expect_equal(nrow(dc), 2)
  expect_true(all(dc$lo <= dc$hi))
  expect_s3_class(obj$bootstrap$ci, "tbl_df")
  expect_named(obj$bootstrap$ci, c("group", "time", "B_raw", "B_lo", "B_hi"))

  again <- aib_bootstrap(obj, B = 40, seed = 1, verbose = FALSE)
  expect_equal(again$bootstrap$intervals, bi)
})

test_that("the bootstrap's fast path matches the package functions", {
  for (d in list(gap_panel(),
                 aib_simulate(n = c(80, 60, 70), n_times = 4,
                              groups = c("A", "B", "C"),
                              init = c(.5, .4, .6), p01 = c(.3, .2, .25),
                              p11 = c(.8, .7, .75),
                              observe = rbind(c(.7, .8, .6), c(.9, .9, 1)),
                              seed = 9))) {
    obj <- build(d)
    obj <- aib_describe(obj, ref_group = "A", weights = c(1, 2, 1, 3),
                        verbose = FALSE)
    obj <- aib_transition(obj, ref_group = "A", verbose = FALSE)
    obj <- aib_amplify(obj, ref_group = "A", verbose = FALSE)
    dm  <- AIBias:::.decision_matrix(obj)
    fs  <- AIBias:::.fast_stats(dm$Y, dm$G, "A", c("B", "C")[c("B", "C") %in% dm$G],
                                c(1, 2, 1, 3), "mechanism")
    tr  <- obj$bias$trajectory
    m   <- merge(tr, fs$trajectory, by = c("group", "time"))
    expect_equal(m$B_raw.x, m$B_raw.y, tolerance = 1e-12)
    expect_equal(m$B_smd.x, m$B_smd.y, tolerance = 1e-12)
    m <- merge(obj$bias$cumulative, fs$cumulative, by = "group")
    expect_equal(m$CB_raw.x, m$CB_raw.y, tolerance = 1e-12)
    expect_equal(m$CB_normalized.x, m$CB_normalized.y, tolerance = 1e-12)
    rg <- obj$transitions$recovery_gap
    m  <- merge(data.frame(group = as.character(rg$group), x = rg$recovery_gap),
                fs$transitions, by = "group")
    expect_equal(m$x, m$recovery_gap, tolerance = 1e-12)
    m <- merge(obj$amplification$index, fs$amplification, by = c("group", "time"))
    expect_equal(m$A_index.x, m$A_index.y, tolerance = 1e-12)
  }
})

test_that("bootstrap refuses a reference group that differs from earlier steps", {
  obj <- aib_describe(build(gap_panel()), ref_group = "A", verbose = FALSE)
  expect_error(aib_bootstrap(obj, B = 5, ref_group = "B", verbose = FALSE),
               "differs")
})


# ---- Integration -------------------------------------------------------------

test_that("aib_audit runs the decomposition and plots it", {
  data(lending_panel, package = "AIBias")
  res <- aib_audit(lending_panel, id = "applicant_id", time = "year",
                   group = "race", decision = "approved",
                   ref_group = "White", verbose = FALSE)
  expect_false(is.null(res$decomposition))
  expect_equal(nrow(res$decomposition$steps), 2 * 5)
  expect_s3_class(plot(res, type = "decomposition"), "ggplot")
  expect_output(summary(res), "change = decay")
})

test_that("aib_build rejects duplicated unit-occasion rows", {
  d <- gap_panel()
  d <- rbind(d, d[1, ])
  expect_error(build(d), "at most one row")
})

test_that("aib_simulate validates inputs and hides decisions", {
  expect_error(aib_simulate(n_times = 1), "at least 2")
  expect_error(aib_simulate(p01 = c(0.1, 0.2, 0.3)), "one value per group")
  s <- aib_simulate(n = 200, n_times = 3,
                    observe = rbind(c(0.5, 0.5), c(1, 1)), seed = 2)
  expect_true(all(!is.na(s$decision[s$time == 1])))
  expect_true(anyNA(s$decision))
  expect_true(all(is.na(s$decision) | s$decision == s$decision_true))
  s2 <- aib_simulate(n = 200, n_times = 3,
                     observe = rbind(c(0.5, 0.5), c(1, 1)), seed = 2,
                     unobserved = "drop")
  expect_false(anyNA(s2$decision))
})


# ---- Review fixes (0.2.0) ----------------------------------------------------

test_that("aib_audit runs on an all-favorable panel and keeps the observed change", {
  d <- data.frame(id = rep(1:20, each = 3), time = rep(1:3, 20),
                  group = rep(c("A", "B"), each = 30), decision = 1L)
  expect_no_warning(
    res <- aib_audit(d, id = "id", time = "time", group = "group",
                     decision = "decision", ref_group = "A", verbose = FALSE))
  expect_true(is.na(res$transitions$recovery_gap$recovery_gap))
  expect_equal(res$transitions$retention_gap$retention_gap, 0)
  st <- res$decomposition$steps
  expect_false(any(st$supported))
  expect_equal(st$change, c(0, 0))
  expect_true(all(is.na(st$recovery)))
  expect_equal(st$retention, c(0, 0))       # both groups have prior favorable units
  expect_true(all(is.na(st$decay)))
  expect_true(all(is.na(res$amplification$index$A_index)))
  expect_output(summary(res), "empty cell")
})

test_that("with one empty cell, components that do not need it are kept", {
  d <- rbind(exact_chain(50, 1.0, 0.2, 0.8, 3, "ref"),
             exact_chain(50, 0.5, 0.1, 0.7, 3, "focal"))
  st <- aib_decompose(build(d), ref_group = "ref",
                      verbose = FALSE)$decomposition$steps
  expect_true(is.na(st$recovery[1]))        # no reference unit with prior 0
  expect_false(is.na(st$retention[1]))
  expect_true(is.na(st$carry[1]))
  expect_true(is.na(st$recon_error[1]))
  expect_equal(st$change[1], st$gap_curr[1] - st$gap_prev[1])
})

test_that("character and factor decisions are converted, not lost", {
  d <- gap_panel()
  dc <- d; dc$decision <- as.character(dc$decision)
  df <- d; df$decision <- factor(df$decision)
  dl <- d; dl$decision <- ifelse(is.na(d$decision), NA, ifelse(d$decision == 1, "TRUE", "false"))
  ref <- build(d)$data$decision
  expect_equal(build(dc)$data$decision, ref)
  expect_equal(build(df)$data$decision, ref)
  expect_equal(build(dl)$data$decision, ref)
  bad <- d; bad$decision <- ifelse(d$decision == 1, "yes", "no")
  expect_error(build(bad), "must be binary")
  bad2 <- d; bad2$decision[1] <- 2
  expect_error(build(bad2), "must be binary")
})

test_that("a scheduled occasion absent from the data is not skipped", {
  d <- data.frame(id = rep(1:40, each = 2),
                  time = factor(rep(c("w1", "w3"), 40), levels = c("w1", "w2", "w3")),
                  group = rep(c("A", "B"), each = 40),
                  decision = rep(c(0L, 1L), 40))
  expect_warning(obj <- build(d), "no rows: w2")
  expect_equal(obj$meta$n_times, 3)
  st <- aib_decompose(obj, ref_group = "A", verbose = FALSE)$decomposition$steps
  expect_equal(st$n_pair_g, c(0, 0))
  tr <- aib_transition(obj, ref_group = "A", verbose = FALSE)
  expect_equal(sum(tr$transitions$counts$n_total), 0)

  # same with an explicit schedule on integer time
  d2 <- d; d2$time <- ifelse(d$time == "w1", 1L, 3L)
  expect_warning(o2 <- aib_build(d2, "id", "time", "group", "decision",
                                 schedule = 1:3, verbose = FALSE), "no rows: 2")
  expect_equal(o2$meta$n_times, 3)
  expect_error(aib_build(d2, "id", "time", "group", "decision",
                         schedule = 1:2, verbose = FALSE), "must appear in")
})

test_that("decomposition and bootstrap need a fixed group per unit", {
  d <- data.frame(id = rep(1:6, each = 2), time = rep(1:2, 6),
                  group = c("A","A","A","A","A","A","B","B","B","B","A","B"),
                  decision = c(1,1,1,1,1,1,0,0,0,0,0,1))
  expect_warning(obj <- build(d), "change `group`")
  expect_no_error(aib_describe(obj, ref_group = "A", verbose = FALSE))
  expect_error(aib_decompose(obj, ref_group = "A", verbose = FALSE),
               "stay in one group")
  obj <- aib_describe(obj, ref_group = "A", verbose = FALSE)
  expect_error(aib_bootstrap(obj, B = 5, verbose = FALSE), "stay in one group")
})

test_that("a schedule with no adjacent pairs gives NA, not an error", {
  d <- data.frame(id = rep(1:20, each = 2), time = rep(c(1L, 3L), 20),
                  group = rep(c("A", "B"), each = 20),
                  decision = rep(c(0L, 1L, 1L, 0L), 10))
  obj <- suppressWarnings(aib_build(d, "id", "time", "group", "decision",
                                    schedule = 1:3, verbose = FALSE))
  expect_no_error(res <- aib_audit(obj, ref_group = "A", verbose = FALSE))
  expect_equal(nrow(res$amplification$index), 2)
  expect_true(all(is.na(res$amplification$index$A_index)))
  expect_true(is.na(res$amplification$cumulative$A_cumulative))
  expect_false(any(res$decomposition$steps$supported))
  expect_no_error(aib_bootstrap(res, B = 10, seed = 1, verbose = FALSE))
})

test_that("factor ids with unused levels are accepted", {
  data(lending_panel, package = "AIBias")
  lp <- lending_panel
  lp$applicant_id <- factor(lp$applicant_id)
  lp <- subset(lp, race != "Hispanic")
  expect_no_error(obj <- aib_build(lp, "applicant_id", "year", "race",
                                   "approved", verbose = FALSE))
  expect_equal(obj$meta$n_units, length(unique(lp$applicant_id)))
  expect_no_error(aib_decompose(obj, ref_group = "White", verbose = FALSE))
})

test_that("positional calls valid in 0.1.1 still work", {
  data(lending_panel, package = "AIBias")
  # aib_build(data, id, time, group, decision, outcome, verbose)
  obj <- aib_build(lending_panel, "applicant_id", "year", "race", "approved",
                   NULL, FALSE)
  expect_s3_class(obj, "aibias")
  # aib_transition(object, ref_group, verbose); aib_amplify(object, ref_group, sign, verbose)
  expect_silent(o2 <- aib_transition(obj, "White", FALSE))
  expect_silent(o3 <- aib_amplify(o2, "White", "legacy", FALSE))
  expect_equal(o3$amplification$sign, "legacy")
  # aib_audit(object, ref_group, bootstrap, B, seed, verbose)
  res <- aib_audit(obj, "White", TRUE, 20, 1, FALSE)
  expect_equal(res$bootstrap$B, 20)
  expect_false(is.null(res$decomposition))
})

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.