14  Graph Complexity and Omitted Dependence

Objectives

This chapter presents the additional simulation study run for the revision of the paper. It addresses concerns about bias and mean squared error (MSE) relative to known targets, and the dependence of performance on the sample size \(n\), the mediator dimension \(d\) and the size \(q\) of the parent sets. It also documents the bias–variance trade-off associated with the choice of graph in sequential transport (ST): a sparser graph can be wrong (it omits a dependence) but easier to estimate.

The simulations are run with the replication codes in the folder CS_R1_replication/ (master file run_all.R, in "full" mode with legacy seeding), which store their results in CS_R1_replication/replication_results/full/. This chapter only reads these results: it does not rerun the simulations.

library(knitr)
library(kableExtra)

# Folder with the results of the replication codes (full mode)
res_dir <- "../CS_R1_replication/replication_results/full/"

# Result tables of the main simulation (step 2 of run_all.R)
res <- readRDS(file.path(res_dir, "main_results.rds"))
raw <- res$raw # one row per scenario x replication x method x fit
truths <- res$truths # population targets
bv <- res$bv # profile squared bias / variance
summary_results <- res$summary_results # Monte Carlo summaries
paired <- res$paired # paired q=1 vs q=2 comparisons
B <- max(summary_results$B)

# Figure functions used for the paper (drawn inline with file = NULL)
source("../CS_R1_replication/R/functions_plots.R")
Helper functions to extract and format the results.
#' Value of one summary statistic for one scenario and method
#' @param col Column of `summary_results` (e.g. "mse_delta", "mse_profile").
get_val <- function(d, b2, n, method, col, fit = "oracle") {
  v <- summary_results[[col]][
    summary_results$d == d & summary_results$b2 == b2 &
      summary_results$n == n & summary_results$method == method &
      summary_results$fit == fit
  ]
  if (length(v) == 1L) v else NA_real_
}

#' Format small numbers in scientific notation, for inline text (LaTeX)
fmt_sci <- function(x, digits = 2) {
  if (is.na(x)) return("--")
  e <- floor(log10(abs(x)))
  m <- x / 10^e
  sprintf("%s\\times 10^{%d}", formatC(m, format = "f", digits = digits), e)
}

#' Format numbers with a fixed number of decimals
fmt_num <- function(x, digits = 5) formatC(x, format = "f", digits = digits)

# Reference slice and largest sample size
d_ref  <- 8L
b2_ref <- 0.16
n_max  <- max(summary_results$n)

14.1 Simulation Design

14.1.1 Data Generating Process

There are \(d \in \{4, 8, 12\}\) scalar continuous mediators. In the source group, \(X_{0,j} = 2U_j - 1\), where the \(U_j\) are independent uniforms. In the target group, writing \(X_{1,0} = X_{1,-1} = 0\) and \(E_j = \{G_{2,1}^{-1}(U_j) - 2\}/\sqrt{2}\), with \(G_{2,1}\) the Gamma CDF (shape 2, scale 1), we generate recursively

\[ X_{1,j} = \tanh\!\left[0.5 X_{1,j-1} + b_2 X_{1,j-2} + 0.12 \sin(2.5 X_{1,j-1}) + (0.44 + 0.16 |X_{1,j-1}|) E_j\right]. \]

The disturbances are skewed (non-Gaussian), and each structural equation is strictly increasing in \(U_j\) given the parents. The parameter \(b_2 \in \{0, 0.16, 0.35\}\) controls the strength of the second-order edge \(X_{j-2} \to X_j\): the correct graph uses the two preceding nodes when \(b_2 > 0\), and only the preceding node when \(b_2 = 0\).

Because both groups are generated from the same ranks \(U\), the transported profile of each unit has a known reference value (its target-group profile with the same ranks). This allows to have measurable individual errors.

The group-specific outcome probabilities are logistic in the features \((1, X_1, X_2, H_d)\), with \(H_d = (d-2)^{-1} \sum_{j=3}^{d} X_j X_{j-2}\):

\[ \begin{aligned} \mu_0(x) &= \operatorname{logit}^{-1}\{-0.25 + 0.55 x_1 - 0.4 x_2 + 2.6 H_d(x)\},\\ \mu_1(x) &= \operatorname{logit}^{-1}\{0.35 + 0.35 x_1 - 0.1 x_2 + 1.8 H_d(x)\}. \end{aligned} \]

14.1.2 Graphs Compared and Estimator

For each mediator \(j\), the fitted ST map uses the \(q\) preceding mediators as parents, \(X_{\max(1, j-q)}, \ldots, X_{j-1}\), with \(q \in \{0, 1, 2, 4\}\) (subject to \(q < d\)):

  • \(q = 0\): no graph (marginal quantile maps);
  • \(q = 1\): first-order chain, which omits the edge of strength \(b_2\);
  • \(q = 2\): the true graph when \(b_2 > 0\);
  • \(q = 4\): an over-parameterized graph.

Both the source conditional CDF and the target conditional quantile are estimated with Gaussian-kernel weights on standardized parent variables, with bandwidth \(1.2\, n^{-1/(4+k)}\) for \(k\) parents. The source weights are evaluated at the observed parents of the unit, the target weights at its already transported parents. Estimated conditional ranks are clipped to \([c, 1-c]\), with \(c = \min(0.2, 0.5/\max(n_{\text{eff}}, 2))\) and \(n_{\text{eff}}\) the effective number of points receiving weight. The bandwidth is fixed in this controlled experiment, not tuned. The direct estimator (standardization to the empirical target distribution) is reported as a benchmark for the aggregate components only, since it does not produce individual profiles.

14.1.3 Targets and Criteria

The population contributions are \(\delta = \mathbb{E}\{\mu_0(X_1) - \mu_0(X_0)\}\), \(\zeta = \mathbb{E}\{\mu_1(X_1) - \mu_0(X_1)\}\) and \(\tau = \delta + \zeta\), approximated with 120,000 independent draws for each \((d, b_2)\). In each replication, the plug-in estimates are computed on the transported training sample, either with the true (oracle) regressions \(\mu_a\) or with group-specific GLMs fitted on the same (correctly specified) regressors. The criteria are:

  • bias and MSE of \(\widehat\delta\), \(\widehat\zeta\) and \(\widehat\tau\);
  • the profile MSE: mean squared distance between the transported profiles and their reference values, on 80 fixed validation units per scenario, split into squared bias and variance across replications;
  • the conditional-rank MSE: mean squared difference between the conditional ranks of the transported profiles (under the true target mechanism) and the source ranks;
  • paired Monte Carlo differences between \(q = 1\) and \(q = 2\), computed on the same samples.

For each of the \(3 \times 3 \times 4\) combinations of \((d, b_2, n)\), with \(n \in \{80, 200, 400, 800\}\) observations per group, we run \(B = 200\) replications.

Codes of the data-generating process, outcome models and sequential transport estimator (R/functions_core.R).
# Core functions: data-generating process, outcome models, sequential
# transport estimator and exact Gaussian benchmark (section 2).
# Used by all step scripts.

# 2. Data-generating process, outcome models and sequential transport----

## 2.1 Data-generating process----

#' Generate target-group mediators from their ranks
#'
#' Maps a matrix of ranks \eqn{U \in (0,1)^{m \times d}} to group-1 mediators
#' with a nonlinear second-order chain. The source group is defined separately
#' as \eqn{X^{(0)}_j = 2U_j - 1}. Using the same `U` for both groups therefore
#' gives the true counterfactual profile of each unit.
#'
#' @param U Numeric matrix (\eqn{m \times d}) of ranks in \eqn{(0,1)}.
#' @param b2 Numeric, \eqn{\ge 0}. Strength of the \eqn{X_{j-2} \to X_j} edge.
#'   With `b2 = 0` the graph is a first-order chain (so `q = 1` is the true
#'   graph); with `b2 > 0`, `q = 2` is the true graph.
#'
#' @returns Numeric matrix (\eqn{m \times d}) with values in \eqn{(-1,1)}.
#'
#' @details The disturbances are standardised Gamma(2,1) quantiles,
#'   \eqn{e_j = (F^{-1}_{\Gamma(2,1)}(U_j) - 2)/\sqrt{2}} (mean 0, variance 1,
#'   skewed). With \eqn{a = X_{j-1}} and \eqn{b = X_{j-2}} (set to 0 when they
#'   do not exist), the structural equations are
#'   \deqn{X_j = \tanh\{0.5a + b_2 b + 0.12\sin(2.5a) + (0.44 + 0.16|a|)\,e_j\},}
#'   which are strictly increasing in \eqn{e_j}, hence in \eqn{U_j} given the
#'   parents. Ranks are clipped to \eqn{[10^{-9}, 1-10^{-9}]} before taking the
#'   Gamma quantile.
map_target <- function(U, b2) {
  m <- nrow(U)
  d <- ncol(U)
  e <- matrix(
    (qgamma(pmin(1 - 1e-9, pmax(1e-9, as.vector(U))), shape = 2) - 2) / sqrt(2),
    m, d
  )
  x <- matrix(0, m, d)
  for (j in seq_len(d)) {
    a <- if (j > 1L) x[, j - 1L] else rep(0, m)
    b <- if (j > 2L) x[, j - 2L] else rep(0, m)
    x[, j] <- tanh(
      0.5 * a + b2 * b + 0.12 * sin(2.5 * a) + (0.44 + 0.16 * abs(a)) * e[, j]
    )
  }
  x
}

#' Recover conditional ranks under the true target mechanism
#'
#' Exact inverse of [map_target()]: given target-group mediators, solves the
#' structural equations for the disturbances and returns the corresponding
#' conditional ranks. Used to compute the conditional-rank MSE of the
#' transported profiles (how well transport keeps each unit's rank).
#'
#' @param x Numeric matrix (\eqn{m \times d}) of mediators in \eqn{(-1,1)}.
#' @param b2 Numeric. Same edge strength as in [map_target()].
#'
#' @returns Numeric matrix (\eqn{m \times d}) of ranks in \eqn{(0,1)}.
#'   `target_ranks(map_target(U, b2), b2)` returns `U` (up to clipping).
#'
#' @details Values are clipped to \eqn{[-1+10^{-12}, 1-10^{-12}]} before
#'   `atanh()`, so transported points on the boundary of the support do not
#'   produce infinite values.
target_ranks <- function(x, b2) {
  m <- nrow(x)
  d <- ncol(x)
  u <- matrix(NA_real_, m, d)
  for (j in seq_len(d)) {
    a  <- if (j > 1L) x[, j - 1L] else rep(0, m)
    b  <- if (j > 2L) x[, j - 2L] else rep(0, m)
    xx <- pmax(-1 + 1e-12, pmin(1 - 1e-12, x[, j]))
    e  <- (atanh(xx) - 0.5 * a - b2 * b - 0.12 * sin(2.5 * a)) /
      (0.44 + 0.16 * abs(a))
    u[, j] <- pgamma(2 + sqrt(2) * e, shape = 2)
  }
  
  u
}

## 2.2 Outcome models----

#' Outcome features
#'
#' Builds the design matrix shared by the true outcome models and the fitted
#' GLMs. So the GLM is correctly specified, and its error is estimation
#' error only, never misspecification.
#'
#' @param x Numeric matrix (\eqn{m \times d}) of mediators, \eqn{d \ge 3}.
#'
#' @returns Numeric matrix (\eqn{m \times 4}) with columns: intercept,
#'   \eqn{X_1}, \eqn{X_2}, and the mean of the lag-2 products
#'   \eqn{\frac{1}{d-2}\sum_{j=3}^{d} X_j X_{j-2}}.
feature_matrix <- function(x) {
  d <- ncol(x)
  
  cbind(
    1, x[, 1], x[, 2],
    rowMeans(x[, 3:d, drop = FALSE] * x[, 1:(d - 2L), drop = FALSE])
  )
}

#' True outcome regression in group 0
#'
#' @param x Numeric matrix of mediators (see [feature_matrix()]).
#' @returns Numeric vector of \eqn{P(Y = 1 \mid X = x, A = 0)}.
mu0 <- function(x) {
  F <- feature_matrix(x)
  
  plogis(-0.25 + 0.55 * F[, 2] - 0.4 * F[, 3] + 2.6 * F[, 4])
}

#' True outcome regression in group 1
#'
#' @param x Numeric matrix of mediators (see [feature_matrix()]).
#' @returns Numeric vector of \eqn{P(Y = 1 \mid X = x, A = 1)}.
mu1 <- function(x) {
  F <- feature_matrix(x)
  
  plogis(0.35 + 0.35 * F[, 2] - 0.1 * F[, 3] + 1.8 * F[, 4])
}

## 2.3 Sequential transport estimator----

#' Nadaraya-Watson kernel weights
#'
#' Computes Gaussian-kernel weights of the training points for each query
#' point, on standardised variables. These weights give the conditional CDF
#' and conditional quantile estimates used in [st_transport()].
#'
#' @param train Numeric matrix (\eqn{n \times k}) of conditioning variables
#'   (parents) in the training sample. `k = 0` is allowed.
#' @param query Numeric matrix (\eqn{m \times k}) of conditioning values at
#'   which weights are needed.
#' @param h Positive numeric. Bandwidth, on the standardised scale.
#'
#' @return Numeric matrix (\eqn{m \times n}) whose rows sum to 1. If
#'   \eqn{k = 0} (no parents), all weights equal \eqn{1/n}, i.e. the
#'   unconditional empirical distribution.
#'
#' @details Each column is divided by its training standard deviation, floored
#'   at 0.08. Weights are \eqn{\exp\{-\|z - a\|^2 / (2h^2)\}}, floored at
#'   \eqn{10^{-100}} so that no row is entirely zero, then normalised by row.
kernel_weights <- function(train, 
                           query, 
                           h) {
  train <- as.matrix(train)
  query <- as.matrix(query)
  n <- nrow(train)
  m <- nrow(query)
  if (ncol(train) == 0L) return(matrix(1 / n, m, n))
  s <- pmax(apply(train, 2L, sd), 0.08)
  a <- sweep(train, 2L, s, "/")
  z <- sweep(query, 2L, s, "/")
  dist2 <- outer(rowSums(z * z), rowSums(a * a), "+") - 2 * tcrossprod(z, a)
  dist2[dist2 < 0] <- 0  # keeps dim; pmax(0, matrix) could drop it
  w <- exp(-dist2 / (2 * h * h))
  w[w < 1e-100] <- 1e-100
  stopifnot(is.matrix(w), nrow(w) == m, ncol(w) == n)
  
  w / rowSums(w)
}

#' Sequential transport with a q-th order chain graph
#'
#' Transports source-group profiles to the target group one mediator at a
#' time. For each mediator \eqn{j}, the conditional rank of the unit in the
#' source group (given its observed parents) is mapped to the conditional
#' quantile of the target group, given the parents already transported.
#' Both conditional distributions are estimated with kernel weights.
#'
#' @param x0 Numeric matrix (\eqn{n_0 \times d}). Source-group sample
#'   (group 0).
#' @param x1 Numeric matrix (\eqn{n_1 \times d}). Target-group sample
#'   (group 1).
#' @param query Numeric matrix (\eqn{m \times d}). Source-group profiles to
#'   transport (in the main study: the training sample `x0` stacked with the
#'   validation units).
#' @param q Non-negative integer. Number of preceding mediators used as
#'   parents: mediator \eqn{j} conditions on
#'   \eqn{X_{\max(1, j-q)}, \dots, X_{j-1}}. `q = 0` uses unconditional
#'   marginal quantiles (no graph).
#' @param hscale Positive numeric. Bandwidth multiplier (default `HSCALE`).
#'
#' @returns Numeric matrix (\eqn{m \times d}) of transported profiles.
#'
#' @details With \eqn{k} parents, the bandwidths are
#'   \eqn{h_g = \text{hscale} \cdot n_g^{-1/(4+k)}}, \eqn{g \in \{0, 1\}}.
#'   For each query unit \eqn{i} and mediator \eqn{j}:
#'   \enumerate{
#'     \item conditional rank \eqn{u = \sum_l w^{(0)}_{il}
#'       \mathbf{1}\{x^{(0)}_{lj} \le \text{query}_{ij}\}};
#'     \item \eqn{u} is clipped to \eqn{[c, 1-c]}, with
#'       \eqn{c = \min(0.2, 0.5/\max(n_{\text{eff}}, 2))} and
#'       \eqn{n_{\text{eff}} = 1/\sum_l (w^{(0)}_{il})^2} (Kish effective
#'       sample size), which avoids extreme quantiles when few points get
#'       weight;
#'     \item \eqn{z_{ij}} is the weighted quantile of \eqn{x^{(1)}_{\cdot j}} at
#'       level \eqn{u}, by linear interpolation of the midpoint weighted CDF,
#'       with constant extrapolation outside its range.
#'   }
#'   Cost is \eqn{O(m \cdot (n_0 + n_1) \cdot d)} per call, which is the main
#'   computational burden of the script.
st_transport <- function(x0, 
                         x1, 
                         query, 
                         q, 
                         hscale = HSCALE) {
  d  <- ncol(x0)
  n0 <- nrow(x0)
  n1 <- nrow(x1)
  m  <- nrow(query)
  z  <- matrix(NA_real_, m, d)
  
  for (j in seq_len(d)) {
    parents <- if (j == 1L || q == 0L) {
      integer(0)
    } else {
      seq.int(max(1L, j - q), j - 1L)
    }
    k <- length(parents)
    
    # Source weights: conditional on the ORIGINAL parents of the query units
    w0 <- kernel_weights(x0[, parents, drop = FALSE],
                         query[, parents, drop = FALSE],
                         hscale * n0^(-1 / (4 + k)))
    # Target weights: conditional on the TRANSPORTED parents
    w1 <- kernel_weights(x1[, parents, drop = FALSE],
                         z[, parents, drop = FALSE],
                         hscale * n1^(-1 / (4 + k)))
    
    ord <- order(x1[, j])
    y   <- x1[ord, j]
    for (i in seq_len(m)) {
      u    <- sum(w0[i, x0[, j] <= query[i, j]])
      neff <- 1 / sum(w0[i, ]^2)
      clip <- min(0.20, 0.5 / max(neff, 2))
      u    <- max(clip, min(1 - clip, u))
      w    <- w1[i, ord]
      z[i, j] <- approx(cumsum(w) - w / 2, y, xout = u,
                        rule = 2, ties = "ordered")$y
    }
  }
  stopifnot(all(is.finite(z)))
  
  z
}

## 2.4 Exact Gaussian benchmark----

#' Exact comparison of sequential transport and Brenier OT (Gaussian case)
#'
#' Two-dimensional example: the source is \eqn{N(0, I_2)} and the target is
#' \eqn{N(0, \Sigma)} with \eqn{\Sigma = \begin{pmatrix}1 & 1\\ 1 & 2
#' \end{pmatrix}}. Both linear maps push the source onto the target. The
#' Brenier OT map (\eqn{\Sigma^{1/2}}) minimises the displacement, while
#' sequential transport (the lower-triangular Cholesky factor, i.e. the
#' Knothe-Rosenblatt map) keeps the conditional residual of the second
#' coordinate.
#'
#' @returns A data frame with two rows (`"ST exact"`, `"Brenier OT exact"`) and
#'   columns:
#'   \describe{
#'     \item{squared_displacement}{\eqn{E\|MX - X\|^2 = \|M - I\|_F^2}.}
#'     \item{conditional_residual_mse}{\eqn{E\{(Z_2 - Z_1) - X_2\}^2} for
#'       \eqn{Z = MX}: 0 when the map keeps the second conditional
#'       residual.}
#'   }
#'   Exact values: ST has displacement 1 and residual error 0; OT has
#'   displacement \eqn{5 - 2\sqrt{5}} and a positive residual error.
gaussian_check <- function() {
  Sigma <- matrix(c(1, 1, 1, 2), 2, 2)
  ee <- eigen(Sigma, symmetric = TRUE)
  OT <- ee$vectors %*% diag(sqrt(ee$values), 2) %*% t(ee$vectors)
  ST <- matrix(c(1, 0, 1, 1), 2, 2, byrow = TRUE)
  cost <- function(M) sum((M - diag(2))^2)
  rank_error <- function(M) sum((M[2, ] - M[1, ] - c(0, 1))^2)
  
  data.frame(
    method = c("ST exact", "Brenier OT exact"),
    squared_displacement = c(cost(ST), cost(OT)),
    conditional_residual_mse = c(rank_error(ST), rank_error(OT))
  )
}
Codes of the Monte Carlo simulation and summaries (R/functions_main.R).
# Functions of the main simulation (sections 4 and 5).
# Used by scripts/02_main_simulation.R.

# 4. Main simulation (non-Gaussian chain), with checkpoints----

# One scenario = one (d, b2, n). Two seeding schemes (SEEDING, section 1.2):
#
# - "legacy": a single set.seed(SEED) for the whole study, with scenarios run
#   in the order d -> b2 -> n, and the reference sample and validation units
#   drawn once per (d, b2), before the loop over n. This is exactly the
#   random-number stream of CS_R1_common.R, whose "main" run produced the
#   numbers in the manuscript (comparaison-R1.tex): with the full-mode grid,
#   this script reproduces them. The equivalence requires the full grid, in
#   the order given in section 1.3.
# - "scenario": independent seeds per scenario (see make_seed()). Scenarios
#   can then be run separately or in any order, but the numbers differ from
#   those in the manuscript (within Monte Carlo error).
#
# Within a replication, the transports for the different q run in parallel
# (par_lapply()); scenarios themselves run one after the other, as the legacy
# stream requires.
#
# Each completed scenario is saved as an .rds file in CKPT_DIR (one folder per
# seeding scheme, so the two are never mixed). While a scenario is running, a
# partial .rds is saved every 5 replications in "full" mode (every 2 in
# "pilot"). An interrupted run never repeats completed scenarios, and resumes a
# partial scenario at the next replication with exactly the same random draws:
# in "legacy" mode, each checkpoint stores the state of the random-number
# generator, which is restored when the checkpoint is reloaded.

## 4.1 Helpers----

#' Path of the completed-scenario checkpoint
#'
#' @param d Integer. Mediator dimension.
#' @param b2 Numeric. Edge strength (stored as `round(100 * b2)` in the name).
#' @param n Integer. Observations per group.
#' @returns Character. Path `CKPT_DIR/scenario_d<d>_b<100*b2>_n<n>.rds`.
scenario_file <- function(d, b2, n) {
  file.path(CKPT_DIR, sprintf("scenario_d%d_b%d_n%d.rds", d, round(100 * b2), n))
}

#' Path of the partial (in-progress) scenario checkpoint
#'
#' @inheritParams scenario_file
#' @returns Character. Path `CKPT_DIR/scenario_d<d>_b<100*b2>_n<n>_partial.rds`.
scenario_partial <- function(d, b2, n) {
  file.path(CKPT_DIR, sprintf("scenario_d%d_b%d_n%d_partial.rds",
                              d, round(100 * b2), n))
}

#' Current state of the random-number generator
#'
#' @returns Integer vector, a copy of `.Random.seed` in the global environment.
get_rng_state <- function() {
  get(".Random.seed", envir = globalenv())
}

#' Restore a saved state of the random-number generator
#'
#' @param state Integer vector previously returned by [get_rng_state()].
#' @returns Called for its side effect (sets `.Random.seed` in the global
#'   environment).
set_rng_state <- function(state) {
  assign(".Random.seed", state, envir = globalenv())
}

#' Population targets and validation units of a (d, b2) pair
#'
#' Draws the reference sample used to approximate the population
#' contributions, then the fixed validation units used for the profile
#' metrics. Both depend on \eqn{(d, b_2)} only, not on \eqn{n}.
#'
#' @param d Integer. Mediator dimension.
#' @param b2 Numeric. Strength of the \eqn{X_{j-2} \to X_j} edge.
#' @param seed_ref,seed_val Integers or `NULL`. Seeds set before drawing the
#'   reference sample and the validation units. With `NULL` (legacy seeding),
#'   the draws continue the current random-number stream.
#'
#' @returns A list with:
#'   \describe{
#'     \item{truth}{named vector of population `delta`, `zeta`, `tau`;}
#'     \item{Uval}{ranks of the validation units
#'       (\eqn{N_{val} \times d});}
#'     \item{val0}{source profiles of the validation units, \eqn{2U - 1};}
#'     \item{val1}{their true counterfactual profiles, `map_target(Uval, b2)`.}
#'   }
#'
#' @details With \eqn{U} uniform on \eqn{(0,1)^d} (`N_REFERENCE` draws),
#'   \eqn{X^{(0)} = 2U - 1} and \eqn{X^{(1)} = } `map_target(U, b2)`:
#'   \eqn{\delta = E\{\mu_0(X^{(1)}) - \mu_0(X^{(0)})\}},
#'   \eqn{\zeta = E\{\mu_1(X^{(1)}) - \mu_0(X^{(1)})\}},
#'   \eqn{\tau = \delta + \zeta}.
draw_scenario_context <- function(d, b2, seed_ref = NULL, seed_val = NULL) {
  if (!is.null(seed_ref)) set.seed(seed_ref)
  Uref <- matrix(runif(N_REFERENCE * d), ncol = d)
  ref0 <- 2 * Uref - 1
  ref1 <- map_target(Uref, b2)
  truth <- c(
    delta = mean(mu0(ref1) - mu0(ref0)),
    zeta  = mean(mu1(ref1) - mu0(ref1))
  )
  truth <- c(truth, tau = sum(truth))

  if (!is.null(seed_val)) set.seed(seed_val)
  Uval <- matrix(runif(N_VALIDATION * d), ncol = d)

  list(truth = truth, Uval = Uval, val0 = 2 * Uval - 1,
       val1 = map_target(Uval, b2))
}

#' One Monte Carlo replication of a scenario
#'
#' Draws both groups, fits the outcome GLMs, transports the training sample
#' and the validation units for each graph order, and computes the estimates
#' and error metrics. The random draws continue the current stream: seeding
#' is left to the caller.
#'
#' @param d,b2,n Scenario identifiers (\eqn{n_0 = n_1 = n}).
#' @param rep Integer. Replication index (stored in the result rows).
#' @param qs Integer vector. Graph orders to use.
#' @param ctx List returned by [draw_scenario_context()].
#'
#' @returns A list with:
#'   \describe{
#'     \item{rows}{data frame with one row per (method, fit): `d, b2, n, q`
#'       (method label, `"q=0"`, ..., `"direct"`), `fit` (`"oracle"` /
#'       `"glm"`), `rep`, `delta, zeta, tau`, squared errors
#'       `err_delta2, err_zeta2, err_tau2`, `profile_mse`, `rank_mse` and
#'       `elapsed_seconds` (the last three are `NA` for `"direct"`);}
#'     \item{pred}{matrix (\eqn{|q| \times (N_{val} d)}) of transported
#'       validation profiles.}
#'   }
#'
#' @details The transports for the different \eqn{q} are computed in parallel
#'   with [par_lapply()]. Random draws, in this order: ranks of group 0 and group 1
#'   (`runif`), then outcomes of group 0 and group 1 (`rbinom`). The same
#'   order as in CS_R1_common.R, which the legacy seeding relies on.
#'   The plug-in estimates use the transported training units:
#'   \eqn{\hat\delta = \bar m_0(z) - \bar m_0(x_0)},
#'   \eqn{\hat\zeta = \bar m_1(z) - \bar m_0(z)}, with \eqn{m_g = \mu_g}
#'   (oracle) or the fitted GLMs. Profile MSE and rank MSE are computed on the
#'   validation units and do not depend on the outcome fit. The `"direct"`
#'   benchmark replaces \eqn{z} by the observed group-1 sample \eqn{x_1}. All
#'   \eqn{q} use the same training samples, so q=1 and q=2 can be compared
#'   pairwise.
run_replication <- function(d, b2, n, rep, qs, ctx) {
  U0 <- matrix(runif(n * d), ncol = d)
  U1 <- matrix(runif(n * d), ncol = d)
  x0 <- 2 * U0 - 1
  x1 <- map_target(U1, b2)
  y0 <- rbinom(n, 1L, mu0(x0))
  y1 <- rbinom(n, 1L, mu1(x1))

  # Correctly specified outcome GLMs
  beta0 <- suppressWarnings(
    glm.fit(feature_matrix(x0), y0, family = binomial())$coefficients
  )
  beta1 <- suppressWarnings(
    glm.fit(feature_matrix(x1), y1, family = binomial())$coefficients
  )
  if (any(!is.finite(c(beta0, beta1))))
    stop("GLM failed d=", d, " b2=", b2, " n=", n, " rep=", rep)
  f0 <- function(x) plogis(drop(feature_matrix(x) %*% beta0))
  f1 <- function(x) plogis(drop(feature_matrix(x) %*% beta1))
  truth <- ctx$truth

  #' One result row for a given method and outcome fit (internal)
  #'
  #' @param q Character. Method label (`"q=1"`, ..., `"direct"`).
  #' @param fit Character. `"oracle"` (true mu0, mu1) or `"glm"` (fitted).
  #' @param z Numeric matrix. Counterfactual profiles of the training units
  #'   (transported profiles, or `x1` for `"direct"`).
  #' @param profile_mse,rank_mse,runtime Validation metrics and transport
  #'   time (`NA` for `"direct"`).
  #' @return One-row data frame (see `rows` in the @returns above).
  collect <- function(q, fit, z, profile_mse = NA_real_,
                      rank_mse = NA_real_, runtime = NA_real_) {
    m0 <- if (fit == "oracle") mu0 else f0
    m1 <- if (fit == "oracle") mu1 else f1
    de <- mean(m0(z) - m0(x0))
    ze <- mean(m1(z) - m0(z))
    ta <- de + ze
    data.frame(
      d = d, b2 = b2, n = n, q = q, fit = fit, rep = rep,
      delta = de, zeta = ze, tau = ta,
      err_delta2 = (de - truth["delta"])^2,
      err_zeta2  = (ze - truth["zeta"])^2,
      err_tau2   = (ta - truth["tau"])^2,
      profile_mse = profile_mse, rank_mse = rank_mse,
      elapsed_seconds = runtime
    )
  }

  # Sequential transport for each graph order q, in parallel over q. The
  # transport draws no random numbers, so this does not change the results.
  query <- rbind(x0, ctx$val0)
  transported <- par_lapply(qs, function(q) {
    tick <- proc.time()["elapsed"]
    z <- st_transport(x0, x1, query, q, hscale = HSCALE)
    list(z = z, runtime = unname(proc.time()["elapsed"] - tick))
  })

  rows <- list()
  jj <- 0L
  pred <- matrix(NA_real_, length(qs), N_VALIDATION * d)
  for (qi in seq_along(qs)) {
    z <- transported[[qi]]$z
    runtime <- transported[[qi]]$runtime
    ztr <- z[seq_len(n), , drop = FALSE] # training units
    zv  <- z[n + seq_len(N_VALIDATION), , drop = FALSE] # validation units
    pred[qi, ] <- as.vector(zv)
    pf <- mean((zv - ctx$val1)^2) # profile MSE
    rk <- mean((target_ranks(zv, b2) - ctx$Uval)^2) # conditional-rank MSE
    for (fit in c("oracle", "glm")) {
      jj <- jj + 1L
      rows[[jj]] <- collect(paste0("q=", qs[qi]), fit, ztr, pf, rk, runtime)
    }
  }
  # Direct benchmark: observed target sample (aggregate only, no profiles)
  for (fit in c("oracle", "glm")) {
    jj <- jj + 1L
    rows[[jj]] <- collect("direct", fit, x1)
  }

  list(rows = do.call(rbind, rows), pred = pred)
}

#' Run (or resume) one Monte Carlo scenario
#'
#' For a given \eqn{(d, b_2, n)}, gets the population targets and validation
#' units, then runs `B` replications with [run_replication()], for each graph
#' order \eqn{q} in `Q_VALUES` (restricted to \eqn{q < d}).
#'
#' @param d Integer. Mediator dimension.
#' @param b2 Numeric. Strength of the \eqn{X_{j-2} \to X_j} edge.
#' @param n Integer. Observations per group (\eqn{n_0 = n_1 = n}).
#' @param ctx List returned by [draw_scenario_context()] for the same
#'   \eqn{(d, b_2)}, or `NULL`. Legacy seeding only: pass the context of the
#'   previous \eqn{n} of the same \eqn{(d, b_2)}, and `NULL` for the first
#'   \eqn{n} (the context is then drawn from the current stream). Ignored with
#'   scenario seeding, where the context is drawn with its own seeds.
#'
#' @returns A list (also saved to [scenario_file()]) with elements:
#'   \describe{
#'     \item{B, HSCALE, seeding}{settings used, checked on reload;}
#'     \item{completed}{number of completed replications (\eqn{= B});}
#'     \item{rows}{list of length `B` of data frames (see
#'       [run_replication()]);}
#'     \item{pred}{array (\eqn{B \times |q| \times (N_{val} d)}) of transported
#'       validation profiles, used for the bias-variance decomposition;}
#'     \item{qs}{graph orders actually used;}
#'     \item{ctx}{the scenario context (see [draw_scenario_context()]);}
#'     \item{truth, val1}{copies of `ctx$truth` and `ctx$val1`;}
#'     \item{rng_state}{legacy seeding only: state of the random-number
#'       generator after the last completed replication.}
#'   }
#'
#' @details
#' \strong{Seeds.} Scenario seeding: `salt = 1` (reference sample), `2`
#' (validation units) and `3` (training samples, per replication); see
#' [make_seed()]. Legacy seeding: no seed is set here; the caller sets
#' `set.seed(SEED)` once before the first scenario.
#'
#' \strong{Checkpoints.} If a completed file exists, it is returned directly,
#' after checking that `B`, `HSCALE` and the graph orders match the current
#' settings (otherwise the function stops); with legacy seeding, the
#' generator state saved in the file is restored, so the next scenario
#' continues the stream exactly. If a partial file exists, the run resumes
#' after its last completed replication, from the saved state. Other settings
#' (`N_REFERENCE`, `N_VALIDATION`) are not checked: delete `CKPT_DIR` after
#' changing them.
run_scenario <- function(d, b2, n, ctx = NULL) {
  final   <- scenario_file(d, b2, n)
  partial <- scenario_partial(d, b2, n)
  legacy  <- SEEDING == "legacy"
  qs      <- Q_VALUES[Q_VALUES < d] # mediator j has at most j - 1 predecessors

  check_checkpoint <- function(obj, file) {
    if (!identical(obj$B, B) || !identical(obj$HSCALE, HSCALE) ||
        !identical(obj$qs, qs)) {
      stop("Checkpoint with different B, bandwidth or q values: ", file)
    }
    if (legacy && is.null(obj$rng_state)) {
      stop("Checkpoint without generator state (not legacy seeding): ", file)
    }
  }

  # Completed scenario: reload
  if (file.exists(final)) {
    obj <- readRDS(final)
    check_checkpoint(obj, final)
    if (legacy) set_rng_state(obj$rng_state)
    return(obj)
  }

  # Partial scenario: resume; otherwise start a new one
  if (file.exists(partial)) {
    obj <- readRDS(partial)
    check_checkpoint(obj, partial)
    if (legacy) set_rng_state(obj$rng_state)
  } else {
    obj <- list(
      B = B,
      HSCALE = HSCALE,
      seeding = SEEDING,
      completed = 0L,
      rows = list(),
      pred = array(NA_real_, c(B, length(qs), N_VALIDATION * d)),
      qs = qs
    )
  }

  # Population targets and validation units
  if (legacy) {
    if (is.null(obj$ctx)) {
      obj$ctx <- if (!is.null(ctx)) ctx else draw_scenario_context(d, b2)
    }
  } else {
    obj$ctx <- draw_scenario_context(
      d, b2,
      seed_ref = make_seed(d, b2, salt = 1),
      seed_val = make_seed(d, b2, salt = 2)
    )
  }
  obj$truth <- obj$ctx$truth
  obj$val1  <- obj$ctx$val1

  # Replications
  every <- if (MODE == "pilot") 2L else 5L
  if (obj$completed < B) for (rep in seq.int(obj$completed + 1L, B)) {
    if (!legacy) set.seed(make_seed(d, b2, n, rep, salt = 3))
    res <- run_replication(d, b2, n, rep, qs, obj$ctx)
    obj$rows[[rep]] <- res$rows
    obj$pred[rep, , ] <- res$pred
    obj$completed <- rep

    # Partial checkpoint
    if (rep %% every == 0L || rep == B) {
      if (legacy) obj$rng_state <- get_rng_state()
      saveRDS(obj, partial)
      cat(sprintf("d=%d b2=%.2f n=%d : %d/%d\n", d, b2, n, rep, B))
    }
  }

  if (legacy) obj$rng_state <- get_rng_state()
  saveRDS(obj, final)
  if (file.exists(partial)) unlink(partial)
  obj
}

#' Bias-variance decomposition of the transported validation profiles
#'
#' For each graph order of a scenario, splits the profile MSE on the fixed
#' validation units into squared bias and variance across the `B`
#' replications.
#'
#' @param obj A scenario object returned by [run_scenario()].
#'
#' @returns A data frame with one row per \eqn{q}: `d, b2, n, q, bias2,
#'   variance, profile_mse`.
#'
#' @details With \eqn{\hat z_b} the transported validation profiles in
#'   replication \eqn{b} (stacked into a vector), \eqn{\bar z} their average
#'   over replications and \eqn{z^\star} the true counterfactual profiles:
#'   \eqn{\text{bias}^2 = \text{mean}(\bar z - z^\star)^2} and
#'   \eqn{\text{variance} = \text{mean}_{b}\,\text{mean}(\hat z_b - \bar z)^2}
#'   (divisor \eqn{B}, not \eqn{B - 1}). With this divisor,
#'   bias^2 + variance equals exactly the average over replications of
#'   `profile_mse`; this identity is checked below.
profile_bias_variance <- function(obj) {
  r <- obj$rows[[1]][1, ]
  do.call(rbind, lapply(seq_along(obj$qs), function(qi) {
    P     <- matrix(obj$pred[, qi, ], nrow = B)
    bar   <- colMeans(P)
    bias2 <- mean((bar - as.vector(obj$val1))^2)
    var0  <- mean(sweep(P, 2L, bar, "-")^2)
    data.frame(
      d = r$d, b2 = r$b2, n = r$n, q = obj$qs[qi],
      bias2 = bias2, variance = var0, profile_mse = bias2 + var0
    )
  }))
}

# 5. Summary tables, paired comparisons and checks----

#' Monte Carlo summary for one scenario, method and outcome fit
#'
#' Aggregates the `B` replications of one \eqn{(d, b_2, n)} scenario for one
#' method (`"q=0"`, ..., `"direct"`) and one outcome fit (`"oracle"` /
#' `"glm"`).
#'
#' @param v Data frame. The rows of `raw` for one (d, b2, n, method, fit).
#' @param truths Data frame of population targets (see section 4), matched to
#'   `v` on (d, b2, n).
#'
#' @returns A one-row data frame with columns:
#'   \describe{
#'     \item{d, b2, n, method, fit, B}{identifiers and number of
#'       replications;}
#'     \item{bias_delta, mcse_bias_delta}{Monte Carlo bias of
#'       \eqn{\hat\delta} and its standard error \eqn{sd/\sqrt{B}};}
#'     \item{variance_delta}{variance of \eqn{\hat\delta} across
#'       replications (divisor \eqn{B});}
#'     \item{mse_delta, mcse_mse_delta}{MSE of \eqn{\hat\delta} and its Monte
#'       Carlo standard error;}
#'     \item{mse_zeta, mse_tau}{MSE of \eqn{\hat\zeta} and \eqn{\hat\tau};}
#'     \item{mse_profile, mse_rank}{average profile MSE and conditional-rank
#'       MSE on the validation units (`NA` for `"direct"`);}
#'     \item{runtime}{average transport time in seconds (`NA` for
#'       `"direct"`).}
#'   }
#'
#' @details Since `variance_delta` uses divisor \eqn{B},
#'   `mse_delta = bias_delta^2 + variance_delta` holds exactly.
summarise_method <- function(v, truths) {
  target <- truths$delta[match(paste(v$d[1], v$b2[1], v$n[1]),
                               paste(truths$d, truths$b2, truths$n))]
  ee <- v$delta - target
  data.frame(
    d = v$d[1], b2 = v$b2[1], n = v$n[1], method = v$q[1], fit = v$fit[1],
    B = nrow(v),
    bias_delta = mean(ee),
    mcse_bias_delta = sd(ee) / sqrt(nrow(v)),
    variance_delta = mean((v$delta - mean(v$delta))^2),
    mse_delta = mean(v$err_delta2),
    mcse_mse_delta = sd(v$err_delta2) / sqrt(nrow(v)),
    mse_zeta = mean(v$err_zeta2),
    mse_tau = mean(v$err_tau2),
    mse_profile = if (all(is.na(v$profile_mse))) NA_real_ else mean(v$profile_mse),
    mse_rank = if (all(is.na(v$rank_mse))) NA_real_ else mean(v$rank_mse),
    runtime = if (all(is.na(v$elapsed_seconds))) NA_real_ else mean(v$elapsed_seconds)
  )
}

#' Paired comparison of q = 1 and q = 2
#'
#' Compares the two graph orders on the same replications (same training
#' samples, same validation units), which removes most of the Monte Carlo
#' noise shared by both methods.
#'
#' @param raw Data frame of all replications (section 4).
#' @param d,b2,n Scenario identifiers.
#' @param fit Character. `"oracle"` or `"glm"`.
#' @param metrics Character vector of columns of `raw` to compare. Defaults:
#'   `"err_delta2"` (squared error of \eqn{\hat\delta}), `"profile_mse"`,
#'   `"rank_mse"`.
#'
#' @returns A data frame with one row per metric: `d, b2, n, fit, metric,
#'   contrast` (`"q=1 minus q=2"`), `difference` (mean paired difference),
#'   `mcse` (\eqn{sd/\sqrt{B}}) and a normal 95% interval `lo, hi`.
#'
#' @details A positive difference means q = 1 has the larger error, i.e. it
#'   favours q = 2. Profile and rank metrics do not depend on the outcome fit,
#'   so they are only returned for `fit = "oracle"`. The intervals ignore the
#'   uncertainty in the Monte Carlo truth, and with small `B` (pilot mode,
#'   B = 4) they are not meaningful.
paired_q1_q2 <- function(raw, 
                         d, 
                         b2, 
                         n, 
                         fit,
                         metrics = c("err_delta2", "profile_mse", "rank_mse")) {
  a <- raw[raw$d == d & raw$b2 == b2 & raw$n == n &
             raw$q == "q=1" & raw$fit == fit, ]
  b <- raw[raw$d == d & raw$b2 == b2 & raw$n == n &
             raw$q == "q=2" & raw$fit == fit, ]
  a <- a[order(a$rep), ]
  b <- b[order(b$rep), ]
  stopifnot(nrow(a) == B, nrow(b) == B, identical(a$rep, b$rep))
  
  if (fit == "glm") metrics <- intersect(metrics, "err_delta2")
  do.call(
    rbind, 
    lapply(metrics, function(metric) {
      dif <- a[[metric]] - b[[metric]]
      m   <- mean(dif)
      se  <- sd(dif) / sqrt(B)
      data.frame(d = d, b2 = b2, n = n, fit = fit, metric = metric,
                 contrast = "q=1 minus q=2", difference = m, mcse = se,
                 lo = m - 1.96 * se, hi = m + 1.96 * se)
    }
    )
  )
}
Master file used to run all the simulations (run_all.R).
# Additional experiments for the R1 revision: master file
#
# Monte Carlo study of sequential transport for causal mediation with
# continuous, non-Gaussian mediators. It looks at how the choice of graph
# (q = number of preceding mediators used as parents: 0, 1, 2, 4) trades bias
# against variance, as a function of sample size n, mediator dimension d and
# the strength b2 of the second-order dependence (q = 1 omits it; q = 2 is the
# true graph when b2 > 0). The target group is built from known ranks, so true
# individual counterfactual profiles are available. This allows us to compare
# aggregate errors (delta, zeta, tau) with individual errors (profile MSE split
# into bias^2 and variance, conditional-rank MSE), for oracle and GLM outcome
# models. Additional experiments: analytic Gaussian examples, bandwidth
# sensitivity, a mixed-type example, an entropic OT comparison and an
# exploratory COMPAS analysis.
#
# Usage: set the options below, then run this file from the folder containing
# this script (run_all.R).
#
# Outputs (CSV tables, PDF figures, LaTeX tables) go to replication_results/<mode>/.
#
# Files:
#   R/settings.R                   settings, output folders, helpers
#                                  (cache, parallel computing)
#   R/functions_core.R             data-generating process, outcome models,
#                                  sequential transport
#   R/functions_main.R             main simulation and summary functions
#   R/functions_plots.R            figures and LaTeX tables
#   scripts/01_checks_analytic.R   unit tests, exact Gaussian benchmark,
#                                  analytic examples
#   scripts/02_main_simulation.R   main simulation + summaries (long)
#   scripts/03_figures_tables.R    figures and tables of the main simulation
#   scripts/04_bandwidth.R         bandwidth sensitivity
#   scripts/05_mixed.R             mixed-type example
#   scripts/06_sinkhorn.R          entropic OT comparison
#   scripts/07_compas.R            COMPAS exploratory analysis
#   scripts/08_final_checks.R      checks, comparison with the manuscript

# Options----

# "pilot": quick check of the whole pipeline
# "full": B = 200 replications per scenario, the settings of the paper
# Sys.setenv(CS_R1_MODE = "pilot") # ~10 seconds
Sys.setenv(CS_R1_MODE = "full") # ~30 minutes

# Seeding of the main simulation:
# * "legacy": random-number stream of CS_R1_common.R; in full mode, reproduces
#             the numbers printed in the manuscript exactly
# * "scenario": independent seeds per scenario
Sys.setenv(CS_R1_SEEDING = "legacy")

# Number of cores. The results do not depend on it.
Sys.setenv(CS_R1_CORES = max(1L, parallel::detectCores(logical = FALSE) - 1L))
# Parallel backend: "fork" (default on macOS / Linux) or "socket" (always used
# on Windows). 
# Uncomment the next line to force "socket", e.g. if forking fails in RStudio.
# Sys.setenv(CS_R1_BACKEND = "socket")

# Figures: plain PDF (default) or tikz export with LaTeX labels, as for the
# figures of the first version (requires tikzDevice and LaTeX). The PDF file
# names are the same in both cases.
Sys.setenv(CS_R1_TIKZ = "true")

# Steps to run (set to FALSE to skip). 
# Steps 3 and 8 only need the saved results of step 2, so they can be rerun on their own.
STEPS <- c(
  checks_analytic = TRUE, # 01
  main_simulation = TRUE, # 02
  figures_tables  = TRUE, # 03
  bandwidth       = TRUE, # 04
  mixed           = TRUE, # 05
  sinkhorn        = TRUE, # 06
  compas          = TRUE, # 07
  final_checks    = TRUE  # 08
)

# Run----

source("R/settings.R")
source("R/functions_core.R")
source("R/functions_main.R")
source("R/functions_plots.R")
start_workers() # "socket" backend only: starts the worker processes
cat("Mode:", MODE, " Seeding:", SEEDING, " Cores:", N_CORES, "(", PAR_BACKEND, ")\n")

step_files <- c(
  checks_analytic = "scripts/01_checks_analytic.R",
  main_simulation = "scripts/02_main_simulation.R",
  figures_tables  = "scripts/03_figures_tables.R",
  bandwidth       = "scripts/04_bandwidth.R",
  mixed           = "scripts/05_mixed.R",
  sinkhorn        = "scripts/06_sinkhorn.R",
  compas          = "scripts/07_compas.R",
  final_checks    = "scripts/08_final_checks.R"
)

for (step in names(step_files)) {
  if (!STEPS[[step]]) next
  cat("\n==== Step:", step, "====\n")
  tick <- proc.time()["elapsed"]
  source(step_files[[step]])
  cat(sprintf("Step %s done in %.1f s\n", step,
              proc.time()["elapsed"] - tick))
}

stop_workers()

The population targets are reported in Table 14.1.

tb_truths <- unique(truths[, c("d", "b2", "delta", "zeta", "tau")])
tb_truths <- tb_truths[order(tb_truths$d, tb_truths$b2), ]
rownames(tb_truths) <- NULL
kbl(
  tb_truths, booktabs = TRUE, digits = 4, escape = FALSE,
  col.names = c("$d$", "$b_2$", "$\\delta$", "$\\zeta$", "$\\tau$")
) |>
  kable_styling(full_width = FALSE)
Table 14.1: Population targets (Monte Carlo approximation with 120,000 draws), by mediator dimension \(d\) and strength \(b_2\) of the second-order edge.
$d$ $b_2$ $\delta$ $\zeta$ $\tau$
4 0.00 0.0285 0.1333 0.1618
4 0.16 0.0419 0.1289 0.1707
4 0.35 0.0571 0.1235 0.1805
8 0.00 0.0362 0.1323 0.1685
8 0.16 0.0573 0.1252 0.1824
8 0.35 0.0841 0.1158 0.2000
12 0.00 0.0387 0.1320 0.1707
12 0.16 0.0617 0.1242 0.1859
12 0.35 0.0937 0.1126 0.2062

14.2 Results

14.2.1 Aggregate Components and Sample Size

Figure 14.1 shows the MSE of \(\widehat\delta\) against the sample size, for the reference configuration \(d = 8\) and \(b_2 = 0.16\). Comparing the two panels separates the transport error (oracle outcome regressions) from the additional regression error (fitted GLMs).

ss <- summary_results[summary_results$d == d_ref & summary_results$b2 == b2_ref, ]
bb <- bv[bv$d == d_ref & bv$b2 == b2_ref, ]
plot_delta_mse(ss, qs = sort(unique(bb$q)), file = NULL)
Figure 14.1: MSE of the mediator-driven contribution against the number of observations per group, \(d=8\), \(b_2=0.16\), for each graph order \(q\) and the direct estimator.

Table 14.2 reports the bias and MSE of the three components for \(q = 1\), \(q = 2\) and the direct estimator, with the Monte Carlo standard error (MCSE) of the MSE of \(\widehat\delta\).

tb <- ss[ss$fit == "oracle" & ss$method %in% c("q=1", "q=2", "direct"),
         c("n", "method", "bias_delta", "mse_delta", "mcse_mse_delta",
           "mse_zeta", "mse_tau")]
tb <- tb[order(tb$n, match(tb$method, c("q=1", "q=2", "direct"))), ]
tb[, c("mse_delta", "mcse_mse_delta", "mse_zeta", "mse_tau")] <-
  1e4 * tb[, c("mse_delta", "mcse_mse_delta", "mse_zeta", "mse_tau")]
rownames(tb) <- NULL
kbl(
  tb, booktabs = TRUE, digits = c(0, 0, 5, 3, 3, 3, 3), escape = FALSE,
  col.names = c("$n$", "Method", "Bias $\\widehat\\delta$",
                "MSE $\\widehat\\delta$", "MCSE", "MSE $\\widehat\\zeta$",
                "MSE $\\widehat\\tau$")
) |>
  kable_styling(full_width = FALSE)
Table 14.2: Bias and MSE of the estimated components, \(d=8\), \(b_2=0.16\), oracle outcome regressions (\(B=200\) replications). MSE values are multiplied by \(10^4\).
$n$ Method Bias $\widehat\delta$ MSE $\widehat\delta$ MCSE MSE $\widehat\zeta$ MSE $\widehat\tau$
80 q=1 -0.02474 8.410 0.576 1.039 4.374
80 q=2 -0.01095 4.408 0.408 0.409 2.962
80 direct 0.00041 3.168 0.294 0.163 2.586
200 q=1 -0.02025 4.958 0.289 0.616 2.388
200 q=2 -0.00753 1.730 0.172 0.169 1.127
200 direct 0.00030 1.106 0.103 0.069 0.904
400 q=1 -0.01865 3.865 0.171 0.468 1.802
400 q=2 -0.00678 0.991 0.094 0.106 0.612
400 direct -0.00063 0.513 0.052 0.038 0.425
800 q=1 -0.01613 2.845 0.112 0.356 1.277
800 q=2 -0.00445 0.537 0.047 0.057 0.334
800 direct 0.00006 0.333 0.032 0.023 0.264

At \(n = 800\), the MSE of \(\widehat\delta\) with oracle regressions is \(2.845\times 10^{-4}\) for \(q=1\), \(5.369\times 10^{-5}\) for the correct graph \(q=2\), and \(3.333\times 10^{-5}\) for the direct estimator. Direct standardization is often the most accurate estimator of the aggregate components: for averages, it agrees with any exact balanced empirical OT coupling. Its limitation is that it provides no individual profiles.

14.2.2 Individual Profiles and the Bias–Variance Trade-off

For individual profiles, the criterion is different (Figure 14.2). With a small sample, a sparser graph can reconstruct profiles better despite its structural bias.

plot_profile_mse(bb, file = NULL)
Figure 14.2: Profile MSE on the validation units against the number of observations per group, \(d=8\), \(b_2=0.16\).

Figure 14.3 splits the profile MSE into squared bias and variance. This decomposition explains the mechanism of regularization by the graph: adding parents reduces the structural bias but increases the variance of the conditional estimators.

plot_bias_variance(bb, file = NULL)
Figure 14.3: Squared bias (solid) and variance (light) of the transported profiles, \(d=8\), \(b_2=0.16\), by sample size and graph order. With the divisor \(B\), squared bias plus variance equals the average profile MSE.
tb_bv <- bb[order(bb$n, bb$q), c("n", "q", "bias2", "variance", "profile_mse")]
rownames(tb_bv) <- NULL
kbl(
  tb_bv, booktabs = TRUE, digits = c(0, 0, 5, 5, 5), escape = FALSE,
  col.names = c("$n$", "$q$", "Squared bias", "Variance", "Profile MSE")
) |>
  kable_styling(full_width = FALSE)
Table 14.3: Squared bias, variance and profile MSE of the transported profiles, \(d=8\), \(b_2=0.16\).
$n$ $q$ Squared bias Variance Profile MSE
80 0 0.08247 0.01042 0.09290
80 1 0.01057 0.02469 0.03525
80 2 0.00656 0.03810 0.04467
80 4 0.01253 0.05797 0.07050
200 0 0.08231 0.00423 0.08653
200 1 0.00715 0.01243 0.01958
200 2 0.00323 0.02065 0.02387
200 4 0.00618 0.03588 0.04207
400 0 0.08228 0.00205 0.08432
400 1 0.00588 0.00709 0.01296
400 2 0.00219 0.01279 0.01498
400 4 0.00430 0.02419 0.02849
800 0 0.08243 0.00110 0.08354
800 1 0.00478 0.00405 0.00883
800 2 0.00140 0.00779 0.00919
800 4 0.00288 0.01632 0.01919

14.2.3 Strength of the Omitted Dependence

Table 14.4 and Figure 14.4 show how the ranking of the two graphs changes when the omitted dependence becomes stronger (\(d = 8\), \(n = 800\)).

graph_table <- function(by, fixed) {
  s <- summary_results[summary_results$fit == "oracle", ]
  for (nm in names(fixed)) s <- s[s[[nm]] == fixed[[nm]], ]
  xs <- sort(unique(s[[by]]))
  get <- function(m, y) s[[y]][s$method == m][match(xs, s[[by]][s$method == m])]
  data.frame(x = xs,
             prof_q1 = get("q=1", "mse_profile"), prof_q2 = get("q=2", "mse_profile"),
             delta_q1 = get("q=1", "mse_delta"), delta_q2 = get("q=2", "mse_delta"),
             delta_dir = get("direct", "mse_delta"))
}
tb_strength <- graph_table("b2", list(d = d_ref, n = n_max))
kbl(
  tb_strength, booktabs = TRUE, digits = c(2, 5, 5, 6, 6, 6), escape = FALSE,
  col.names = c("$b_2$", "$q=1$", "$q=2$", "$q=1$", "$q=2$", "Direct")
) |>
  add_header_above(c(" " = 1, "Profile MSE" = 2, "Aggregate MSE of $\\widehat\\delta$" = 3),
                   escape = FALSE) |>
  kable_styling(full_width = FALSE)
Table 14.4: Graph trade-off for \(d=8\) and \(n=800\) (\(B=200\) replications; oracle outcome regression). All entries are mean squared errors.
Profile MSE
Aggregate MSE of $\widehat\delta$
$b_2$ $q=1$ $q=2$ $q=1$ $q=2$ Direct
0.00 0.00443 0.00866 0.000033 2.9e-05 2.9e-05
0.16 0.00883 0.00919 0.000285 5.4e-05 3.3e-05
0.35 0.02186 0.01160 0.000852 7.2e-05 2.9e-05
plot_strength(summary_results, bv, d = d_ref, n = n_max, file = NULL)
Figure 14.4: Graph complexity and omitted second-parent dependence, \(d=8\), \(n=800\), \(B=200\). Oracle and fitted-GLM aggregate MSEs, profile MSE, and conditional-rank MSE. Ranks are measured against the known generating ranks.

For an absent or weak second-parent effect, the simpler graph yields a smaller profile MSE; for \(b_2 = 0.35\), retaining the second parent lowers it substantially. The paired differences of Table 14.5 quantify this change of sign with its Monte Carlo uncertainty. In contrast, the aggregate contribution can favor the correct graph even when the simpler graph has a lower profile MSE: the two criteria are different target risks, and a profile reconstruction criterion is not equivalent to estimating an average nonlinear outcome functional.

tb_p <- paired[paired$d == d_ref & paired$n == n_max & paired$fit == "oracle", ]
tb_p$metric <- factor(tb_p$metric, levels = c("profile_mse", "err_delta2", "rank_mse"),
                      labels = c("Profile MSE", "Squared error of delta", "Rank MSE"))
tb_p <- tb_p[order(tb_p$metric, tb_p$b2), c("metric", "b2", "difference", "lo", "hi")]
rownames(tb_p) <- NULL
kbl(
  tb_p, booktabs = TRUE, digits = c(0, 2, 6, 6, 6), escape = FALSE,
  col.names = c("Criterion", "$b_2$", "Difference", "Lower 95%", "Upper 95%")
) |>
  kable_styling(full_width = FALSE)
Table 14.5: Paired differences \(q=1\) minus \(q=2\) on the same replications, \(d=8\), \(n=800\), oracle outcome regressions, with normal-approximation Monte Carlo 95% intervals. A positive difference favors \(q=2\). The intervals condition on the validation units and on the Monte Carlo reference targets; they are not population confidence intervals.
Criterion $b_2$ Difference Lower 95% Upper 95%
Profile MSE 0.00 -0.004228 -0.004351 -0.004105
Profile MSE 0.16 -0.000362 -0.000530 -0.000193
Profile MSE 0.35 0.010258 0.009928 0.010587
Squared error of delta 0.00 0.000004 0.000001 0.000008
Squared error of delta 0.16 0.000231 0.000215 0.000246
Squared error of delta 0.35 0.000780 0.000747 0.000812
Rank MSE 0.00 -0.001949 -0.001993 -0.001905
Rank MSE 0.16 -0.000602 -0.000655 -0.000549
Rank MSE 0.35 0.004763 0.004682 0.004844

Figure 14.5 shows the paired difference for the aggregate component in the reference configuration, as a function of the sample size.

plot_paired_difference(
  paired[paired$d == d_ref & paired$b2 == b2_ref & paired$fit == "oracle" &
           paired$metric == "err_delta2", ],
  file = NULL
)
Figure 14.5: Paired difference in squared error of \(\widehat\delta\), \(q=1\) minus \(q=2\), \(d=8\), \(b_2=0.16\), oracle outcome regressions, with Monte Carlo 95% intervals.

14.2.4 Mediator Dimension

Table 14.6 and Figure 14.6 report the effect of the mediator dimension at \(n = 800\) and \(b_2 = 0.16\).

tb_dim <- graph_table("d", list(b2 = b2_ref, n = n_max))
kbl(
  tb_dim, booktabs = TRUE, digits = c(0, 5, 5, 6, 6, 6), escape = FALSE,
  col.names = c("$d$", "$q=1$", "$q=2$", "$q=1$", "$q=2$", "Direct")
) |>
  add_header_above(c(" " = 1, "Profile MSE" = 2, "Aggregate MSE of $\\widehat\\delta$" = 3),
                   escape = FALSE) |>
  kable_styling(full_width = FALSE)
Table 14.6: Effect of mediator dimension at \(n=800\), \(b_2=0.16\), oracle outcome regression (\(B=200\) replications). The target outcome functional contains the dimension-dependent average \(H_d\); these values therefore do not by themselves identify a convergence rate as a function of \(d\).
Profile MSE
Aggregate MSE of $\widehat\delta$
$d$ $q=1$ $q=2$ $q=1$ $q=2$ Direct
4 0.00537 0.00623 0.000190 5.5e-05 5.0e-05
8 0.00883 0.00919 0.000285 5.4e-05 3.3e-05
12 0.00989 0.01062 0.000294 4.4e-05 2.2e-05
plot_dimension(summary_results, bv, b2 = b2_ref, n = n_max,
               file_delta = NULL, file_profile = NULL)
Figure 14.6: Effect of the mediator dimension on the aggregate MSE of \(\widehat\delta\) (left) and on the profile MSE (right), \(n=800\), \(b_2=0.16\). Different graphs can minimize these two criteria.
(a) Aggregate estimation
(b) Profile reconstruction

Across \(d = 4, 8, 12\), the \(q = 2\) graph keeps a markedly lower aggregate MSE than \(q = 1\) when \(b_2 = 0.16\), even though the simpler graph can still have a smaller profile MSE. This is consistent with the distinction between the size of the graph and the local parent dimension, but it does not establish a dimension-free convergence rate: the specification with a fixed number of parents and the normalization in \(H_d\) prevent such an interpretation.

14.2.5 All Scenarios

tb_all <- summary_results[summary_results$fit == "oracle" &
                            summary_results$method %in% c("q=1", "q=2"),
                          c("d", "b2", "n", "method", "bias_delta", "mse_delta",
                            "mcse_mse_delta", "mse_profile", "mse_rank")]
tb_all <- tb_all[order(tb_all$d, tb_all$b2, tb_all$n, tb_all$method), ]
rownames(tb_all) <- NULL
kbl(
  tb_all, booktabs = TRUE, digits = c(0, 2, 0, 0, 6, 7, 7, 5, 5), escape = FALSE,
  col.names = c("$d$", "$b_2$", "$n$", "Method", "Bias $\\widehat\\delta$",
                "MSE $\\widehat\\delta$", "MCSE", "Profile MSE", "Rank MSE")
) |>
  kable_styling(full_width = FALSE) |>
  scroll_box(height = "500px")
Table 14.7: Results for all the scenarios, oracle outcome regressions, \(q=1\) and \(q=2\).
$d$ $b_2$ $n$ Method Bias $\widehat\delta$ MSE $\widehat\delta$ MCSE Profile MSE Rank MSE
4 0.00 80 q=1 -0.009207 0.0003175 3.27e-05 0.02071 0.00898
4 0.00 80 q=2 -0.004981 0.0004412 5.40e-05 0.02908 0.01288
4 0.00 200 q=1 -0.006657 0.0001425 1.43e-05 0.01025 0.00457
4 0.00 200 q=2 -0.003492 0.0001852 2.25e-05 0.01552 0.00711
4 0.00 400 q=1 -0.004871 0.0000730 6.60e-06 0.00581 0.00254
4 0.00 400 q=2 -0.002529 0.0000925 9.10e-06 0.00916 0.00431
4 0.00 800 q=1 -0.003595 0.0000355 3.20e-06 0.00325 0.00144
4 0.00 800 q=2 -0.001451 0.0000472 4.70e-06 0.00563 0.00271
4 0.16 80 q=1 -0.019980 0.0006837 5.51e-05 0.02630 0.01022
4 0.16 80 q=2 -0.008031 0.0005024 5.09e-05 0.03266 0.01363
4 0.16 200 q=1 -0.017286 0.0004153 2.89e-05 0.01347 0.00530
4 0.16 200 q=2 -0.005793 0.0002314 2.32e-05 0.01703 0.00718
4 0.16 400 q=1 -0.014092 0.0002551 1.65e-05 0.00870 0.00349
4 0.16 400 q=2 -0.003349 0.0001126 1.19e-05 0.01095 0.00449
4 0.16 800 q=1 -0.012681 0.0001900 9.90e-06 0.00537 0.00232
4 0.16 800 q=2 -0.002378 0.0000548 6.00e-06 0.00623 0.00273
4 0.35 80 q=1 -0.030044 0.0012135 8.31e-05 0.03377 0.01185
4 0.35 80 q=2 -0.009325 0.0006161 6.60e-05 0.03463 0.01329
4 0.35 200 q=1 -0.026818 0.0008291 3.76e-05 0.01970 0.00710
4 0.35 200 q=2 -0.007330 0.0002307 1.84e-05 0.01797 0.00694
4 0.35 400 q=1 -0.025015 0.0006775 2.68e-05 0.01426 0.00544
4 0.35 400 q=2 -0.005396 0.0001043 1.19e-05 0.01091 0.00436
4 0.35 800 q=1 -0.022819 0.0005479 1.69e-05 0.01104 0.00441
4 0.35 800 q=2 -0.004006 0.0000616 6.00e-06 0.00678 0.00276
8 0.00 80 q=1 -0.012056 0.0003392 3.30e-05 0.02689 0.01030
8 0.00 80 q=2 -0.007007 0.0003356 3.08e-05 0.04063 0.01651
8 0.00 200 q=1 -0.008682 0.0001493 1.26e-05 0.01337 0.00512
8 0.00 200 q=2 -0.005382 0.0001303 1.31e-05 0.02240 0.00915
8 0.00 400 q=1 -0.006262 0.0000868 7.80e-06 0.00760 0.00297
8 0.00 400 q=2 -0.004043 0.0000773 8.10e-06 0.01377 0.00574
8 0.00 800 q=1 -0.003732 0.0000332 2.80e-06 0.00443 0.00169
8 0.00 800 q=2 -0.001722 0.0000291 2.60e-06 0.00866 0.00364
8 0.16 80 q=1 -0.024742 0.0008410 5.76e-05 0.03525 0.01190
8 0.16 80 q=2 -0.010947 0.0004408 4.08e-05 0.04467 0.01642
8 0.16 200 q=1 -0.020247 0.0004958 2.89e-05 0.01958 0.00648
8 0.16 200 q=2 -0.007534 0.0001730 1.72e-05 0.02387 0.00892
8 0.16 400 q=1 -0.018648 0.0003865 1.71e-05 0.01296 0.00428
8 0.16 400 q=2 -0.006780 0.0000991 9.40e-06 0.01498 0.00560
8 0.16 800 q=1 -0.016127 0.0002845 1.12e-05 0.00883 0.00299
8 0.16 800 q=2 -0.004449 0.0000537 4.70e-06 0.00919 0.00359
8 0.35 80 q=1 -0.039614 0.0017834 8.32e-05 0.05429 0.01651
8 0.35 80 q=2 -0.014869 0.0004920 4.21e-05 0.05429 0.01664
8 0.35 200 q=1 -0.034723 0.0013124 5.16e-05 0.03478 0.01163
8 0.35 200 q=2 -0.011865 0.0002685 2.16e-05 0.02919 0.00919
8 0.35 400 q=1 -0.030761 0.0009905 2.80e-05 0.02687 0.00954
8 0.35 400 q=2 -0.008130 0.0001273 1.04e-05 0.01905 0.00573
8 0.35 800 q=1 -0.028733 0.0008517 2.08e-05 0.02186 0.00838
8 0.35 800 q=2 -0.006389 0.0000719 5.70e-06 0.01160 0.00361
12 0.00 80 q=1 -0.011067 0.0002925 2.77e-05 0.02844 0.01070
12 0.00 80 q=2 -0.005560 0.0002667 3.10e-05 0.04477 0.01776
12 0.00 200 q=1 -0.008663 0.0001344 1.07e-05 0.01391 0.00522
12 0.00 200 q=2 -0.005737 0.0001116 9.50e-06 0.02428 0.00968
12 0.00 400 q=1 -0.007284 0.0000919 8.10e-06 0.00795 0.00307
12 0.00 400 q=2 -0.004883 0.0000725 7.10e-06 0.01530 0.00630
12 0.00 800 q=1 -0.005030 0.0000415 3.10e-06 0.00464 0.00178
12 0.00 800 q=2 -0.003074 0.0000303 2.70e-06 0.00957 0.00401
12 0.16 80 q=1 -0.027481 0.0009426 5.55e-05 0.03859 0.01258
12 0.16 80 q=2 -0.013225 0.0004399 3.78e-05 0.05069 0.01790
12 0.16 200 q=1 -0.022084 0.0005584 2.67e-05 0.02117 0.00702
12 0.16 200 q=2 -0.009018 0.0001717 1.46e-05 0.02725 0.00986
12 0.16 400 q=1 -0.020115 0.0004389 1.67e-05 0.01428 0.00478
12 0.16 400 q=2 -0.007954 0.0001063 8.20e-06 0.01703 0.00614
12 0.16 800 q=1 -0.016678 0.0002943 9.90e-06 0.00989 0.00344
12 0.16 800 q=2 -0.004746 0.0000444 3.90e-06 0.01062 0.00395
12 0.35 80 q=1 -0.043343 0.0020704 8.63e-05 0.06736 0.01731
12 0.35 80 q=2 -0.016641 0.0005339 4.31e-05 0.06299 0.01697
12 0.35 200 q=1 -0.035844 0.0013715 4.88e-05 0.04652 0.01194
12 0.35 200 q=2 -0.011070 0.0002218 1.78e-05 0.03560 0.00926
12 0.35 400 q=1 -0.033970 0.0011994 3.26e-05 0.03730 0.00984
12 0.35 400 q=2 -0.010745 0.0001709 1.18e-05 0.02252 0.00575
12 0.35 800 q=1 -0.029921 0.0009180 2.03e-05 0.03119 0.00852
12 0.35 800 q=2 -0.006877 0.0000748 5.60e-06 0.01392 0.00358

14.3 Additional Experiments

The replication codes also run smaller experiments. They complement the main study but should be read with their limitations, recalled below.

14.3.1 Bandwidth Sensitivity

The MSE of \(\widehat\delta\) (oracle regressions) is computed for bandwidth multipliers \(0.8\), \(1.2\) and \(1.8\), for \(q=1\) and \(q=2\), with \(d = 8\) and \(b_2 = 0.16\) (Figure 14.7 and Table 14.8). Only the aggregate component is evaluated.

band_summary <- read.csv(file.path(res_dir, "bandwidth_summary.csv"))
s0 <- band_summary[band_summary$n == max(band_summary$n), ]
hh <- sort(unique(s0$hscale))
par(mar = c(3.1, 4.1, 2.1, 0.1))
line_plot(hh, curve_matrix(s0, "hscale", hh, "q", c(1L, 2L), "mse_delta"),
          c("q=1", "q=2"), xlab = "Bandwidth multiplier",
          ylab = "MSE of $\\hat{\\delta}$",
          main = paste0("Kernel sensitivity, $n=", max(s0$n), "$"), cex = .8)
Figure 14.7: Sensitivity of the MSE of \(\widehat\delta\) to the bandwidth multiplier, at the largest sample size of the study (\(d=8\), \(b_2=0.16\), oracle regressions).
tb_band <- band_summary[order(band_summary$n, band_summary$hscale, band_summary$q), ]
rownames(tb_band) <- NULL
kbl(tb_band, booktabs = TRUE, digits = c(0, 1, 0, 7), escape = FALSE,
    col.names = c("$n$", "Bandwidth multiplier", "$q$", "MSE $\\widehat\\delta$")) |>
  kable_styling(full_width = FALSE)
Table 14.8: MSE of \(\widehat\delta\) by sample size, bandwidth multiplier and graph order (\(d=8\), \(b_2=0.16\), oracle regressions).
$n$ Bandwidth multiplier $q$ MSE $\widehat\delta$
200 0.8 1 0.0003475
200 0.8 2 0.0001419
200 1.2 1 0.0004777
200 1.2 2 0.0001638
200 1.8 1 0.0008294
200 1.8 2 0.0002700
400 0.8 1 0.0002718
400 0.8 2 0.0000776
400 1.2 1 0.0003766
400 1.2 2 0.0000947
400 1.8 1 0.0006547
400 1.8 2 0.0001737
800 0.8 1 0.0002306
800 0.8 2 0.0000502
800 1.2 1 0.0003083
800 1.2 2 0.0000611
800 1.8 1 0.0005152
800 1.8 2 0.0001147

14.3.2 Mixed-Type Example

This experiment uses the data-generating process of the mixed-type example of Chapter 13 (two Gaussian mediators and one categorical mediator, \(n_0 = 400\), \(n_1 = 200\)). The continuous mediators are transported with the kernel ST estimator (\(X_1 \to X_2\)), and the categorical mediator with a maximal coupling: a randomized coupling that changes the category as rarely as possible, and not the simplex transport used in the paper. The categorical probabilities and the outcome models are the true ones. The results (Table 14.9) are therefore an optimistic check of ST, not a reproduction of the comparison of Chapter 13.

mixed_summary <- read.csv(file.path(res_dir, "mixed_summary.csv"))
kbl(mixed_summary, booktabs = TRUE, digits = c(0, 4, 4, 4, 6, 6), escape = FALSE,
    col.names = c("Method", "$\\widehat\\delta$", "$\\widehat\\zeta$",
                  "$\\widehat\\tau$", "MSE $\\widehat\\delta$",
                  "MSE $\\widehat\\zeta$")) |>
  kable_styling(full_width = FALSE)
Table 14.9: Mixed-type example, average estimates and MSE across replications (oracle regressions and true categorical probabilities).
Method $\widehat\delta$ $\widehat\zeta$ $\widehat\tau$ MSE $\widehat\delta$ MSE $\widehat\zeta$
direct 0.0097 0.2378 0.2475 0.000257 0.000548
ST mixed maximal coupling 0.0071 0.2459 0.2530 0.000262 0.000603

14.3.3 Entropic Optimal Transport

ST (\(q=2\)) is compared with the barycentric projection of an entropically regularized OT coupling (Sinkhorn algorithm), on the data-generating process of the main study (\(d = 4\), \(b_2 = 0.16\), \(n = 100\)). The reference is the direct estimate on the same sample, so Table 14.10 measures how far each set of transported profiles moves the aggregate component away from the empirical target, not the estimation error. The regularization is strong (one quarter of the median squared distance), which pulls the projections toward the target mean.

ot_raw <- read.csv(file.path(res_dir, "regularized_OT_comparison.csv"))
tb_ot <- do.call(rbind, lapply(split(ot_raw, ot_raw$method), function(v) {
  data.frame(method = v$method[1], mean_diff = mean(v$difference_from_direct),
             sd_diff = sd(v$difference_from_direct),
             max_margin_error = if (all(is.na(v$margin_error))) NA else max(v$margin_error, na.rm = TRUE))
}))
rownames(tb_ot) <- NULL
kbl(tb_ot, booktabs = TRUE, digits = c(0, 5, 5, 8),
    col.names = c("Method", "Mean difference", "SD", "Max. margin error")) |>
  kable_styling(full_width = FALSE)
Table 14.10: Difference between the estimate of \(\delta\) and the direct estimate on the same sample (mean and standard deviation across replications), and maximum error on the margins of the Sinkhorn coupling.
Method Mean difference SD Max. margin error
direct 0.00000 0.00000 NA
regularized global OT barycenter -0.01561 0.00322 0
ST q=2 -0.00669 0.00421 NA

14.3.4 COMPAS: Exploratory Analysis on the Public Data

This analysis uses the public ProPublica data (not the fairadapt sample of Chapter 15), with equal-size subsamples of non-Caucasian (source) and Caucasian (target) defendants. Age and prior counts are transported with the kernel ST estimator, the charge degree with a maximal coupling, and the outcome models are logistic GLMs. It is a single point estimate, without uncertainty quantification (Table 14.11); prior counts are a count variable with many zeros, which the continuous quantile transport treats approximately.

compas_file <- file.path(res_dir, "compas_exploratory_results.csv")
if (file.exists(compas_file)) {
  tb_compas <- read.csv(compas_file)[, c("method", "n_per_group", "delta", "zeta", "tau")]
  kbl(tb_compas, booktabs = TRUE, digits = c(0, 0, 4, 4, 4), escape = FALSE,
      col.names = c("Method", "$n$ per group", "$\\widehat\\delta$",
                    "$\\widehat\\zeta$", "$\\widehat\\tau$")) |>
    kable_styling(full_width = FALSE)
} else {
  cat("COMPAS analysis not run:", readLines(file.path(res_dir, "COMPAS_STATUS.txt")))
}
Table 14.11: Exploratory decomposition on the public ProPublica COMPAS data.
Method $n$ per group $\widehat\delta$ $\widehat\zeta$ $\widehat\tau$
ST conditional category kernel 750 -0.0917 -0.0275 -0.1192
direct standardization 750 -0.1006 -0.0287 -0.1293

14.3.5 Analytic Checks

Three exact examples complement the simulations. In the two-dimensional Gaussian case (Table 14.12), the sequential (Knothe–Rosenblatt) map and the Brenier OT map reach the same target law; Brenier has the lower displacement cost, but only ST preserves the conditional residual of the second coordinate. With a single Gaussian mediator, a linear outcome mean and no correlation between the mediator and outcome disturbances, i.e. \(\operatorname{Cov}(\varepsilon_X,\varepsilon_Y)=0\) (Table 14.13), transport recovers the exact contributions \(\delta^\dagger=\alpha\beta\) and \(\zeta^\dagger=\gamma\). With correlated disturbances, these would become \(\alpha(\beta+\kappa)\) and \(\gamma-\alpha\kappa\), with \(\kappa=\operatorname{Cov}(\varepsilon_X,\varepsilon_Y)/\operatorname{Var}(\varepsilon_X)\).

kbl(read.csv(file.path(res_dir, "gaussian_exact.csv")), booktabs = TRUE, digits = 4,
    col.names = c("Method", "Squared displacement", "Conditional-residual MSE")) |>
  kable_styling(full_width = FALSE)
Table 14.12: Exact comparison of sequential transport and Brenier OT, from \(N(0, I_2)\) to \(N(0, \Sigma)\) with \(\Sigma_{11}=1\), \(\Sigma_{12}=1\), \(\Sigma_{22}=2\).
Method Squared displacement Conditional-residual MSE
ST exact 1.0000 0.0000
Brenier OT exact 0.5279 0.2111
kbl(read.csv(file.path(res_dir, "gaussian_mediation.csv")), booktabs = TRUE, digits = 4,
    col.names = c("Component", "Exact", "Transported", "Direct")) |>
  kable_styling(full_width = FALSE)
Table 14.13: Gaussian mediation with one mediator (\(\alpha=0.7\), \(\beta=1.3\), \(\gamma=-0.25\); the outcome mean is linear and the disturbances are uncorrelated, so \(\delta^\dagger=\alpha\beta\) and \(\zeta^\dagger=\gamma\)). The transported column is exact by construction; only the direct column carries sampling noise.
Component Exact Transported Direct
delta 0.91 0.91 0.9197
zeta -0.25 -0.25 -0.2500
tau 0.66 0.66 0.6697
kbl(read.csv(file.path(res_dir, "nonidentification_example.csv")), booktabs = TRUE,
    digits = 3,
    col.names = c("Model", "Mean, group 0", "Mean, group 1",
                  "Mean individual change", "Mean squared individual change")) |>
  kable_styling(full_width = FALSE)
Table 14.14: Two structural models with the same observed group laws: \(X=U\) (M) and \(X=(2A-1)U\) (M’), with \(U \sim N(0,1)\).
Model Mean, group 0 Mean, group 1 Mean individual change Mean squared individual change
M: X=U -0.001 0.002 0.000 0.000
Mprime: X=(2A-1)U 0.001 0.002 0.001 4.015