## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse  = TRUE,
  comment   = "#>",
  fig.width = 7,
  fig.height = 4.5,
  warning   = FALSE,
  message   = FALSE
)
library(AIBias)

## ----data-overview------------------------------------------------------------
data(lending_panel)
head(lending_panel)

## ----approval-rates-----------------------------------------------------------
# Pooled approval rates by group
tapply(lending_panel$approved, lending_panel$race, mean) |> round(3)

## ----build--------------------------------------------------------------------
obj <- aib_build(
  data     = lending_panel,
  id       = "applicant_id",
  time     = "year",
  group    = "race",
  decision = "approved"
)
print(obj)

## ----describe-----------------------------------------------------------------
obj <- aib_describe(obj, ref_group = "White")
obj$bias$cumulative

## ----plot-trajectory, fig.alt="Bias trajectory plot"--------------------------
plot(obj, type = "trajectory")

## ----plot-heatmap, fig.alt="Group-time disparity heatmap"---------------------
plot(obj, type = "heatmap")

## ----transition---------------------------------------------------------------
obj <- aib_transition(obj, ref_group = "White")

# Recovery and retention gaps
obj$transitions$recovery_gap
obj$transitions$retention_gap

## ----plot-transition, fig.alt="Transition probabilities plot"-----------------
plot(obj, type = "transition")

## ----amp-state----------------------------------------------------------------
obj$transitions$amp_state

## ----amplify------------------------------------------------------------------
obj <- aib_amplify(obj, ref_group = "White")
obj$amplification$cumulative

## ----plot-amplification, fig.alt="Amplification index plot"-------------------
plot(obj, type = "amplification")

## ----narratives---------------------------------------------------------------
obj$amplification$narratives

## ----adjust, eval=FALSE-------------------------------------------------------
# obj <- aib_adjust(
#   obj,
#   formula   = ~ income + credit_score,
#   method    = "glm",
#   ref_group = "White"
# )
# 
# # Adjusted trajectory
# head(obj$adjusted$trajectory)

## ----bootstrap, eval=FALSE----------------------------------------------------
# obj <- aib_bootstrap(obj, B = 500, seed = 2024, conf = 0.95)
# plot(obj, type = "trajectory")  # Now includes ribbon CIs

## ----audit, eval=FALSE--------------------------------------------------------
# result <- aib_audit(
#   lending_panel,
#   id        = "applicant_id",
#   time      = "year",
#   group     = "race",
#   decision  = "approved",
#   ref_group = "White",
#   bootstrap = TRUE,
#   B         = 200,
#   seed      = 42
# )
# 
# summary(result)

