|
| 1 | +"""Mediation sensitivity analysis (Imai, Keele & Tingley, 2010). |
| 2 | +
|
| 3 | +Under sequential ignorability (SI), the average causal mediation |
| 4 | +effect (ACME) is identified. But SI is untestable. The sensitivity |
| 5 | +parameter ``ρ`` quantifies the degree of unobserved confounding |
| 6 | +between the mediator and the outcome (the correlation between their |
| 7 | +error terms). When ρ = 0, SI holds; as |ρ| increases, the ACME may |
| 8 | +shrink to zero and even flip sign. |
| 9 | +
|
| 10 | +- :func:`mediate_sensitivity` — over a grid of ρ values, re-estimate |
| 11 | + the ACME with an imputed correlation between mediator and outcome |
| 12 | + errors, and return the ACME as a function of ρ. |
| 13 | +- The ρ at which ACME = 0 is the *sensitivity point* (analogous to |
| 14 | + the E-value in observational studies). |
| 15 | +
|
| 16 | +References |
| 17 | +---------- |
| 18 | +Imai, K., Keele, L. & Tingley, D. (2010). "A General Approach to |
| 19 | + Causal Mediation Analysis." *Psych Methods*, 15(4), 309–334. |
| 20 | +Imai, K., Keele, L. & Yamamoto, T. (2010). "Identification, Inference |
| 21 | + and Sensitivity Analysis for Causal Mediation Effects." *Stat Sci*, |
| 22 | + 25(1), 51–71. |
| 23 | +""" |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +from dataclasses import dataclass |
| 27 | +from typing import Optional |
| 28 | + |
| 29 | +import numpy as np |
| 30 | +import pandas as pd |
| 31 | + |
| 32 | + |
| 33 | +@dataclass |
| 34 | +class MediateSensitivityResult: |
| 35 | + rho_grid: np.ndarray # (n_grid,) |
| 36 | + acme_at_rho: np.ndarray # (n_grid,) |
| 37 | + rho_at_zero: Optional[float] # ρ where ACME crosses zero |
| 38 | + acme_at_zero: float # ACME at ρ=0 (the baseline) |
| 39 | + |
| 40 | + def plot(self, ax=None, **kwargs): |
| 41 | + import matplotlib.pyplot as plt |
| 42 | + if ax is None: |
| 43 | + _, ax = plt.subplots(figsize=(6, 4)) |
| 44 | + ax.plot(self.rho_grid, self.acme_at_rho, "-", color="C0") |
| 45 | + ax.axhline(0, color="grey", linewidth=0.6) |
| 46 | + ax.axvline(0, color="grey", linewidth=0.6, linestyle="--") |
| 47 | + if self.rho_at_zero is not None: |
| 48 | + ax.axvline(self.rho_at_zero, color="C3", linewidth=1, linestyle="--", |
| 49 | + label=f"ACME=0 at ρ={self.rho_at_zero:.2f}") |
| 50 | + ax.legend() |
| 51 | + ax.set_xlabel("ρ (mediator-outcome error correlation)") |
| 52 | + ax.set_ylabel("ACME(ρ)") |
| 53 | + ax.set_title("Mediation sensitivity analysis") |
| 54 | + return ax |
| 55 | + |
| 56 | + def summary(self) -> str: |
| 57 | + lines = [ |
| 58 | + "Mediation Sensitivity (Imai et al. 2010)", |
| 59 | + "-" * 45, |
| 60 | + f"Baseline ACME (ρ=0) : {self.acme_at_zero: .4f}", |
| 61 | + ] |
| 62 | + if self.rho_at_zero is not None: |
| 63 | + lines.append(f"ρ at which ACME = 0 : {self.rho_at_zero: .4f}") |
| 64 | + lines.append( |
| 65 | + f"Interpretation: unobserved confounding with |ρ| > " |
| 66 | + f"{abs(self.rho_at_zero):.2f} would explain away the " |
| 67 | + f"estimated mediation effect." |
| 68 | + ) |
| 69 | + else: |
| 70 | + lines.append("ACME does not cross zero in [-0.9, 0.9].") |
| 71 | + return "\n".join(lines) |
| 72 | + |
| 73 | + def __repr__(self) -> str: |
| 74 | + return self.summary() |
| 75 | + |
| 76 | + |
| 77 | +def mediate_sensitivity( |
| 78 | + data: pd.DataFrame, |
| 79 | + y: str, |
| 80 | + treat: str, |
| 81 | + mediator: str, |
| 82 | + covariates: Optional[list] = None, |
| 83 | + rho_range: tuple = (-0.9, 0.9), |
| 84 | + n_grid: int = 41, |
| 85 | +) -> MediateSensitivityResult: |
| 86 | + """Sensitivity analysis for causal mediation. |
| 87 | +
|
| 88 | + For each candidate ρ (correlation between mediator and outcome |
| 89 | + errors), compute a bias-adjusted ACME. The method follows Imai, |
| 90 | + Keele & Yamamoto (2010): |
| 91 | +
|
| 92 | + 1. Fit the mediator model: ``M = α₀ + α₁ T + α₂ X + ε_M``. |
| 93 | + 2. Fit the outcome model: ``Y = β₀ + β₁ T + β₂ M + β₃ X + ε_Y``. |
| 94 | + 3. For each ρ, the bias in the ACME estimate is approximately |
| 95 | + ``ρ · σ_M · σ_Y / σ²_M`` (from the omitted-variable formula). |
| 96 | + Subtract this bias from the naïve ACME. |
| 97 | +
|
| 98 | + Parameters |
| 99 | + ---------- |
| 100 | + rho_range : (lo, hi) |
| 101 | + n_grid : int, default 41 |
| 102 | + """ |
| 103 | + if covariates is None: |
| 104 | + covariates = [] |
| 105 | + df = data[[y, treat, mediator] + covariates].dropna() |
| 106 | + Y = df[y].to_numpy(float) |
| 107 | + T = df[treat].to_numpy(float) |
| 108 | + M = df[mediator].to_numpy(float) |
| 109 | + n = len(df) |
| 110 | + |
| 111 | + # Design matrices |
| 112 | + X_cov = df[covariates].to_numpy(float) if covariates else np.empty((n, 0)) |
| 113 | + ones = np.ones((n, 1)) |
| 114 | + |
| 115 | + # Mediator model: M ~ T + X |
| 116 | + Xm = np.column_stack([ones, T, X_cov]) if X_cov.shape[1] else np.column_stack([ones, T]) |
| 117 | + beta_m = np.linalg.lstsq(Xm, M, rcond=None)[0] |
| 118 | + resid_m = M - Xm @ beta_m |
| 119 | + sigma_m = float(resid_m.std()) |
| 120 | + |
| 121 | + # Outcome model: Y ~ T + M + X |
| 122 | + Xy = np.column_stack([ones, T, M, X_cov]) if X_cov.shape[1] else np.column_stack([ones, T, M]) |
| 123 | + beta_y = np.linalg.lstsq(Xy, Y, rcond=None)[0] |
| 124 | + resid_y = Y - Xy @ beta_y |
| 125 | + sigma_y = float(resid_y.std()) |
| 126 | + |
| 127 | + # Naive ACME = alpha_1 * beta_2 (effect of T on M × effect of M on Y) |
| 128 | + alpha_1 = float(beta_m[1]) # T → M |
| 129 | + beta_2 = float(beta_y[2]) # M → Y (controlling for T) |
| 130 | + acme_naive = alpha_1 * beta_2 |
| 131 | + |
| 132 | + # Bias at ρ: Δ(ρ) ≈ ρ · σ_Y · sign(alpha_1) (simplified linear formula) |
| 133 | + # More precisely: if ρ ≠ 0, the unobserved path contributes |
| 134 | + # ρ * sigma_y * sigma_m to the covariance of (ε_M, ε_Y), which biases |
| 135 | + # β₂ by ρ * sigma_y / sigma_m per omitted-variable algebra. |
| 136 | + # ACME bias = alpha_1 * Δβ₂ = alpha_1 * ρ * sigma_y / sigma_m |
| 137 | + var_m = float(resid_m.var()) |
| 138 | + rho_grid = np.linspace(rho_range[0], rho_range[1], n_grid) |
| 139 | + acme_at_rho = np.empty(n_grid) |
| 140 | + for k, rho in enumerate(rho_grid): |
| 141 | + bias = alpha_1 * rho * sigma_y / max(sigma_m, 1e-12) |
| 142 | + acme_at_rho[k] = acme_naive - bias |
| 143 | + |
| 144 | + # Find ρ where ACME = 0 (linear interpolation) |
| 145 | + rho_at_zero = None |
| 146 | + for k in range(len(rho_grid) - 1): |
| 147 | + if acme_at_rho[k] * acme_at_rho[k + 1] <= 0: |
| 148 | + frac = acme_at_rho[k] / (acme_at_rho[k] - acme_at_rho[k + 1] + 1e-15) |
| 149 | + rho_at_zero = float(rho_grid[k] + frac * (rho_grid[k + 1] - rho_grid[k])) |
| 150 | + break |
| 151 | + |
| 152 | + return MediateSensitivityResult( |
| 153 | + rho_grid=rho_grid, |
| 154 | + acme_at_rho=acme_at_rho, |
| 155 | + rho_at_zero=rho_at_zero, |
| 156 | + acme_at_zero=float(acme_naive), |
| 157 | + ) |
0 commit comments