axiom-effect / src /axiom_effect /inference.py
maxpagels's picture
Release 1.1.0
a1a7e85 verified
Raw History Blame Contribute Delete
32.5 kB
"""
The table-level call: AxiomEffect on a real table, in the data's own units.
r = model.effect(df, treatment="price", outcome="sales") # no graph
r = model.effect(df, "price", "sales", graph=[("age", "price"), ...]) # a DAG you trust
r = model.effect(df, "price", "sales", graph=Axiom(...).discover(df)) # a discovered graph
print(r)
r.ate, r.att, r.cate, r.curve
What the graph does:
none every other column (or `covariates`) is taken as pre-treatment: none of them
may be caused by the treatment. Their roles are unknown to the model.
a DAG taken as true: the treatment's descendants (mediators, colliders, ...) are
dropped, since adjusting for them biases the effect, and the model is told every
remaining covariate's role (confounder, instrument, precision variable, noise).
No directed path from the treatment to the outcome: every effect is exactly 0.
discovered a discover() result from Axiom (axiom-discovery): its pair probabilities give each
covariate's role probabilities (averaged over DAGs sampled from them), and the
model reads them; nothing is dropped, since a discovered edge can be wrong.
For large tables (more than TRAIN_N[1] rows), inference keeps memory small (< 1 GB) by
partitioning the table into disjoint i.i.d. subsets of at most TRAIN_N[1] rows (stratified
by treatment arm for binary treatments so every subset preserves prevalence) and combining
their independent estimates.
"""
import warnings
from dataclasses import dataclass, field
from statistics import NormalDist
import numpy as np
from .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, roles
from .model import MID, N_FEATURES, QUANTILES
TRAIN_N = (128, 1536) # context rows; larger tables are split into strata of at most TRAIN_N[1] rows
TRAIN_COVARIATES = 84 # covariates seen in training (network accepts any number natively)
WIDE_N = TRAIN_N[1] # kept for compatibility with export_effect_hf / train_effect
NARROW_COVARIATES = 34
MIN_LEVELS = 10 # a continuous treatment needs at least this many distinct values
TRAIN_LEVELS = (0.02, 0.98) # continuous treatment values were asked about between these quantiles
CURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9)
CONTRAST_LEVELS = (0.25, 0.75)
E_CLIP = 0.01 # propensities clipped to [E_CLIP, 1 - E_CLIP] in the doubly robust estimate
PROPENSITY_FOLDS, PROPENSITY_RIDGE = 5, 1.0 # cross-fitted logistic propensity
Z90 = NormalDist().inv_cdf(0.95)
@dataclass(repr=False)
class EffectResult:
"""Result of `effect`, in the outcome's units throughout. Quantiles are QUANTILES (5, 25,
50, 75, 95%): the median is the estimate, the outer pair a 90% interval, the inner 50%."""
treatment: str
outcome: str
binary: bool
covariates: list # the columns adjusted for
dropped: list # columns a DAG marked as the treatment's descendants
graph: str # "none", "dag" or "discovered"
contrast: tuple # (a, b): the treatment values of the headline effect
quantiles: dict # estimand -> (len(QUANTILES),): "contrast", binary "att" / "atc"
cate: np.ndarray # (n,) each row's effect of moving the treatment from a to b
values: np.ndarray = None # continuous: the curve's treatment values
reference: float = None # continuous: where the curve starts
curve: np.ndarray = None # continuous: (K, len(QUANTILES)) effect of reference -> value
propensity: np.ndarray = None # binary: (n,) P(treated | covariates), cross-fitted logistic
roles: dict = field(default_factory=dict) # covariate -> role probabilities (ROLE_NAMES), with a graph
zero_by_graph: bool = False
n_rows: int = 0
n_subsets: int = 1
@property
def estimate(self):
return float(self.quantiles["contrast"][MID])
@property
def interval(self):
q = self.quantiles["contrast"]
return float(q[0]), float(q[-1])
@property
def interval50(self):
q = self.quantiles["contrast"]
return float(q[1]), float(q[-2])
@property
def ate(self):
"""(estimate, lo, hi) of the average effect over all rows, 90%."""
q = self.quantiles["contrast"]
return float(q[MID]), float(q[0]), float(q[-1])
@property
def att(self):
"""Binary: (estimate, lo, hi) of the average effect on the treated, 90%."""
q = self.quantiles.get("att")
return None if q is None else (float(q[MID]), float(q[0]), float(q[-1]))
def to_frame(self):
"""The estimands (binary) or the dose-response curve (continuous), as a DataFrame."""
import pandas as pd
if self.binary:
return pd.DataFrame([{"estimand": k, **{f"q{int(p * 100)}": float(v) for p, v in zip(QUANTILES, q)}}
for k, q in self.quantiles.items()])
return pd.DataFrame({self.treatment: self.values, **{f"q{int(p * 100)}": self.curve[:, k]
for k, p in enumerate(QUANTILES)}})
def __repr__(self):
g = lambda v: f"{v:.4g}"
sig = lambda v: ("+" if v > 0 else "") + g(v)
adj = ", ".join(self.covariates) or "nothing"
rows = f"{self.n_rows} rows" + (f" in {self.n_subsets} strata" if self.n_subsets > 1 else "")
head = [f"Effect of {self.treatment} on {self.outcome} ({rows}; graph: {self.graph}; adjusted for {adj})"]
if self.dropped:
head.append(f" not adjusted for (the graph says the treatment causes them): {', '.join(self.dropped)}")
if self.zero_by_graph:
return "\n".join(head + [f" 0: the graph has no directed path from {self.treatment} to {self.outcome}"])
iv = lambda q: f"{sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}] 50% [{g(q[1])}, {g(q[-2])}]"
a, b = self.contrast
if self.binary:
lines = head + [f" ATE ({g(a)} -> {g(b)}): {iv(self.quantiles['contrast'])}",
f" ATT (the treated): {iv(self.quantiles['att'])}",
f" ATC (the controls): {iv(self.quantiles['atc'])}"]
else:
lines = head + [f" {self.treatment} {g(a)} -> {g(b)}: {iv(self.quantiles['contrast'])}",
f" dose-response, from {self.treatment} = {g(self.reference)}:"]
lines += [f" {g(v):>10s} {sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}]"
for v, q in zip(self.values, self.curve)]
lines.append(f" per-row effects (CATE): median {sig(np.median(self.cate))}, "
f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}")
return "\n".join(lines)
def _table(data, names):
"""(n, d) float64 values and column names from a DataFrame or an array."""
if hasattr(data, "columns") and hasattr(data, "to_numpy"):
names = list(map(str, data.columns)) if names is None else list(names)
data = data.to_numpy(dtype=np.float64, na_value=np.nan)
X = np.asarray(data, dtype=np.float64)
if X.ndim != 2 or X.shape[1] < 2:
raise ValueError(f"expected an (n, d) table with d >= 2, got shape {X.shape}")
names = [f"X{k + 1}" for k in range(X.shape[1])] if names is None else list(map(str, names))
if len(names) != X.shape[1] or len(set(names)) != len(names):
raise ValueError(f"need {X.shape[1]} distinct column names; got {names}")
return X, names
def _column(v, names, what):
if isinstance(v, (int, np.integer)) and not isinstance(v, bool):
if not 0 <= v < len(names):
raise ValueError(f"{what} index {v} is out of range for {len(names)} columns")
return int(v)
if str(v) not in names:
raise ValueError(f"{what} {v!r} is not a column; columns are {names}")
return names.index(str(v))
def _reorder(M, graph_names, names):
"""A (d, d, ...) array over graph_names in the table's column order."""
graph_names = list(map(str, graph_names))
if sorted(graph_names) != sorted(names):
raise ValueError(f"the graph's variables {graph_names} are not the table's columns {names}")
p = [graph_names.index(name) for name in names]
return np.asarray(M)[np.ix_(p, p)]
def _is_discovered(graph):
"""Whether the graph is a discover() result (axiom's CausalGraph), read by its attributes."""
return hasattr(graph, "probs") and hasattr(graph, "names")
def _adjacency(graph, names):
"""(d, d) 0/1 DAG in the table's column order from an edge list of (cause, effect) names,
a (d, d) matrix or an adjacency DataFrame."""
d, index = len(names), {name: k for k, name in enumerate(names)}
if hasattr(graph, "columns") and hasattr(graph, "index"):
if list(map(str, graph.index)) != list(map(str, graph.columns)):
raise ValueError("an adjacency DataFrame needs the same variables, in the same order, as index and columns")
A = _reorder(graph.to_numpy(), graph.columns, names)
elif isinstance(graph, (list, tuple)) and all(
isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(v, str) for v in e) for e in graph):
A = np.zeros((d, d), dtype=np.int64)
for a, b in graph:
for v in (a, b):
if v not in index:
raise ValueError(f"edge ({a!r}, {b!r}): {v!r} is not a column; columns are {names}")
A[index[a], index[b]] = 1
else:
A = np.asarray(graph)
if A.shape != (d, d):
raise ValueError(f"a {d}-column table needs a ({d}, {d}) adjacency matrix; got shape {A.shape}")
A = (np.asarray(A, dtype=float) != 0).astype(np.int64)
if np.any(np.diag(A)):
raise ValueError("the graph has a self-loop")
if not is_dag(A):
raise ValueError("the graph has a directed cycle; the effect model needs a DAG")
return A
def _standardize(v):
mu, sd = v.mean(0), v.std(0)
return (v - mu) / np.where(sd > 0, sd, 1.0), mu, np.where(sd > 0, sd, 1.0)
def _combine(qs, counts):
"""Quantiles of one estimand from disjoint query strata: the count-weighted mean of the
medians, and each quantile's distance from the median combined as for a mean of
independent estimates, sqrt(sum (m_k d_k)^2) / sum m_k."""
qs, m = np.asarray(qs), np.asarray(counts, dtype=float)
if len(qs) == 1:
return qs[0]
mid = (m * qs[:, MID]).sum() / m.sum()
off = qs - qs[:, MID:MID + 1]
return mid + np.sign(off.mean(0)) * np.sqrt(((m[:, None] * off) ** 2).sum(0)) / m.sum()
def _disjoint_strata(T, binary, max_ctx, rng):
"""Partition `n` rows into disjoint i.i.d. subsets of at most `max_ctx` rows (stratified by
treatment arm for binary treatments so every subset preserves prevalence).
Returns [(rows, rows)]."""
n = len(T)
if n <= max_ctx:
all_rows = np.arange(n)
return [(all_rows, all_rows)]
n_strata = -(-n // max_ctx)
if binary:
mid = (T.min() + T.max()) / 2
tr = rng.permutation(np.flatnonzero(T > mid))
ct = rng.permutation(np.flatnonzero(T <= mid))
parts = [np.concatenate([a, b]) for a, b in zip(np.array_split(tr, n_strata), np.array_split(ct, n_strata))]
else:
parts = np.array_split(rng.permutation(n), n_strata)
return [(p, p) for p in parts]
def _kmeans_clusters(Z, k, rng, iters=15):
"""Partition rows of `Z` (n, p) into up to `k` clusters via k-means++ and Lloyd iterations."""
n, p = Z.shape
z_norm = (Z * Z).sum(1)
centers = np.empty((k, p), dtype=Z.dtype)
centers[0] = Z[rng.integers(n)]
min_d2 = np.maximum(z_norm + float((centers[0] ** 2).sum()) - 2.0 * (Z @ centers[0]), 0.0)
for j in range(1, k):
total = float(min_d2.sum())
idx = int(rng.choice(n, p=min_d2 / total)) if total > 0.0 else int(rng.integers(n))
centers[j] = Z[idx]
d2 = np.maximum(z_norm + float((centers[j] ** 2).sum()) - 2.0 * (Z @ centers[j]), 0.0)
min_d2 = np.minimum(min_d2, d2)
prev = None
for _ in range(iters):
c_norm = (centers * centers).sum(1)
labels = (z_norm[:, None] + c_norm[None, :] - 2.0 * (Z @ centers.T)).argmin(1)
if prev is not None and np.array_equal(labels, prev):
break
prev = labels
for j in range(k):
mask = labels == j
if mask.any():
centers[j] = Z[mask].mean(0)
return [np.flatnonzero(labels == j) for j in range(k) if (labels == j).any()]
def _local_strata(C, T, binary, max_ctx, rng, global_frac=0.25):
"""Partition `n` rows into disjoint covariate-space query clusters and pair each cluster with
a `max_ctx` context mixing `global_frac` globally stratified anchor rows (preserving full-table
covariate support, scaling, and correlations) and `1 - global_frac` nearest neighbors (for
local nonlinear / CATE resolution). Falls back to `_disjoint_strata` when `n <= max_ctx` or
there are no varying covariates."""
n = len(T)
if n <= max_ctx:
all_rows = np.arange(n)
return [(all_rows, all_rows)]
if C.shape[1] == 0:
return _disjoint_strata(T, binary, max_ctx, rng)
sd = C.std(0)
Z = np.clip((C - C.mean(0)) / np.where(sd > 0, sd, 1.0), -5.0, 5.0)
if not np.any(Z):
return _disjoint_strata(T, binary, max_ctx, rng)
n_clusters = -(-n // max_ctx)
clusters = _kmeans_clusters(Z, n_clusters, rng)
z_norm = (Z * Z).sum(1)
n_global = int(round(max_ctx * global_frac))
n_local = max_ctx - n_global
if binary:
mid = (T.min() + T.max()) / 2
tr = np.flatnonzero(T > mid)
ct = np.flatnonzero(T <= mid)
exp_n1 = int(round(max_ctx * len(tr) / n))
min_arm1 = min(len(tr), max(16, min(exp_n1, max_ctx // 10)))
min_arm0 = min(len(ct), max(16, min(max_ctx - exp_n1, max_ctx // 10)))
def _nearest(pool, d2_all, k):
if k <= 0:
return np.empty(0, dtype=np.int64)
if k >= len(pool):
return pool
return pool[np.argpartition(d2_all[pool], k - 1)[:k]]
strata = []
for q_rows in clusters:
center = Z[q_rows].mean(0)
d2 = z_norm + float((center ** 2).sum()) - 2.0 * (Z @ center)
if n_global > 0:
if binary:
g1 = int(np.clip(round(n_global * len(tr) / n), min(len(tr), 1), min(len(tr), n_global - 1)))
g0 = min(len(ct), n_global - g1)
g1 = min(len(tr), n_global - g0)
anchor = np.concatenate([rng.choice(tr, g1, replace=False), rng.choice(ct, g0, replace=False)])
else:
anchor = rng.choice(n, n_global, replace=False)
else:
anchor = np.empty(0, dtype=np.int64)
rem = np.ones(n, dtype=bool)
rem[anchor] = False
d2_rem = np.where(rem, d2, np.inf)
nn = np.argpartition(d2_rem, n_local - 1)[:n_local]
if binary:
anchor_n1 = int((T[anchor] > mid).sum())
total_n1 = anchor_n1 + int((T[nn] > mid).sum())
total_n0 = max_ctx - total_n1
if total_n1 >= min_arm1 and total_n0 >= min_arm0:
local = nn
else:
rem_tr, rem_ct = tr[rem[tr]], ct[rem[ct]]
target_n1 = int(np.clip(total_n1, min_arm1, max_ctx - min_arm0))
need1 = int(np.clip(target_n1 - anchor_n1, 0, min(len(rem_tr), n_local)))
need0 = min(len(rem_ct), n_local - need1)
need1 = n_local - need0
local = np.concatenate([_nearest(rem_tr, d2, need1), _nearest(rem_ct, d2, need0)])
ctx_rows = np.concatenate([anchor, local])
else:
ctx_rows = np.concatenate([anchor, nn])
if T[ctx_rows].std() < 1e-8:
return _disjoint_strata(T, binary, max_ctx, rng)
strata.append((q_rows, ctx_rows))
return strata
def _logistic(X, t, ridge, iters=25):
"""Ridge-penalized logistic regression by Newton's method: weights (intercept first)."""
A = np.column_stack([np.ones(len(X)), X])
P = ridge * np.eye(A.shape[1])
P[0, 0] = 0.0
w = np.zeros(A.shape[1])
for _ in range(iters):
p = 1 / (1 + np.exp(-np.clip(A @ w, -30, 30)))
g = A.T @ (p - t) + P @ w
H = (A * (p * (1 - p))[:, None]).T @ A + P + 1e-9 * np.eye(A.shape[1])
step = np.linalg.solve(H, g)
w -= step
if np.abs(step).max() < 1e-8:
break
return w
def _propensity(C, t, seed=0):
"""(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds."""
n = len(t)
X = (C - C.mean(0)) / np.where(C.std(0) > 0, C.std(0), 1.0) if C.shape[1] else np.zeros((n, 0))
folds = np.random.default_rng(seed).permutation(n) % min(PROPENSITY_FOLDS, n)
e = np.empty(n)
for f in np.unique(folds):
fit, held = folds != f, folds == f
if 0 < t[fit].mean() < 1:
w = _logistic(X[fit], t[fit], PROPENSITY_RIDGE)
e[held] = 1 / (1 + np.exp(-np.clip(w[0] + X[held] @ w[1:], -30, 30)))
else:
e[held] = t[fit].mean()
return e
def _aipw(mu0, mu1, e, T, Y):
"""Doubly robust ATE and ATT from per-row predictions, with 90% influence-function intervals."""
e = np.clip(e, E_CLIP, 1 - E_CLIP)
psi = mu1 - mu0 + T * (Y - mu1) / e - (1 - T) * (Y - mu0) / (1 - e)
ate, se = psi.mean(), psi.std() / np.sqrt(len(Y))
p = T.mean()
att = (T * (Y - mu0) - (1 - T) * e / (1 - e) * (Y - mu0)).sum() / T.sum()
phi = (T * (Y - mu0 - att) - (1 - T) * e / (1 - e) * (Y - mu0)) / p
se_t = phi.std() / np.sqrt(len(Y))
return {"ate": (float(ate), float(ate - Z90 * se), float(ate + Z90 * se)),
"att": (float(att), float(att - Z90 * se_t), float(att + Z90 * se_t))}
def _rct_debiased(mu0, mu1, T, Y, t_int):
"""Prediction-powered / covariate-adjusted RCT ATE using AxiomEffect's own per-row
(mu0, mu1) predictions with optimal variance-minimizing shrinkage lambda in [0, 1].
Unbiased under arbitrary hidden confounding or covariate shift in the observational rows."""
m = np.asarray(t_int, dtype=bool)
e1 = m & (T > 0.5)
e0 = m & (T <= 0.5)
n1, n0 = int(e1.sum()), int(e0.sum())
if n1 < 2 or n0 < 2:
return None
n_e = n1 + n0
p = n1 / n_e
y1, m1 = Y[e1], mu1[e1]
y0, m0 = Y[e0], mu0[e0]
cov1 = float(np.cov(y1, m1, ddof=1)[0, 1])
var1 = float(np.var(m1, ddof=1))
cov0 = float(np.cov(y0, m0, ddof=1)[0, 1])
var0 = float(np.var(m0, ddof=1))
denom = var1 / n1 + var0 / n0
lam = float(np.clip((cov1 / n1 + cov0 / n0) / denom, 0.0, 1.0)) if denom > 1e-12 else 0.0
# Exact RCT-rectified influence function on the randomized cohort E
psi = (
lam * (mu1[m] - mu0[m])
+ (T[m] / p) * (Y[m] - lam * mu1[m])
- ((1.0 - T[m]) / (1.0 - p)) * (Y[m] - lam * mu0[m])
)
ate = float(psi.mean())
se = float(psi.std(ddof=1) / np.sqrt(n_e))
# Mild small-sample t-distribution correction (zero scipy dependency)
z = Z90 * float(np.sqrt(max(n_e - 1, 1) / max(n_e - 3, 1)))
lo, hi = ate - z * se, ate + z * se
return {"ate": (ate, lo, hi), "att": (ate, lo, hi), "lambda": lam}
def parse_interventions(interventions, n, names, t, cov):
"""Parse `interventions` into (t_int (n,) bool, w_int (n, len(cov)) bool).
Accepts:
- None -> (None, None)
- 1D bool array (n,): rows where `treatment` was experimentally intervened on
- 2D bool array (n, d): full table intervention mask matching `names`
- sequence of length n (same format as axiom-discovery): each entry is None / empty
(observational), a single column name/index, or a sequence/set of column names/indices.
"""
if interventions is None:
return None, None
d = len(names)
p = len(cov)
if isinstance(interventions, np.ndarray) and interventions.ndim == 2:
if interventions.shape != (n, d):
raise ValueError(f"2D interventions mask has shape {interventions.shape}, expected ({n}, {d})")
M = interventions.astype(bool)
return M[:, t], (M[:, cov] if p else np.zeros((n, 0), dtype=bool))
if isinstance(interventions, np.ndarray) and interventions.ndim == 1 and interventions.dtype == bool:
if len(interventions) != n:
raise ValueError(f"1D interventions mask has length {len(interventions)}, expected {n}")
return interventions.copy(), np.zeros((n, p), dtype=bool)
seq = list(interventions)
if len(seq) != n:
raise ValueError(f"interventions has length {len(seq)}, expected {n}")
if all(isinstance(v, (bool, np.bool_)) for v in seq):
return np.asarray(seq, dtype=bool), np.zeros((n, p), dtype=bool)
if seq and isinstance(seq[0], (list, tuple, np.ndarray)) and len(seq[0]) == d \
and all(isinstance(v, (bool, np.bool_, int, np.integer)) for v in seq[0]):
arr = np.asarray(seq)
if arr.ndim == 2 and arr.shape == (n, d) and np.isin(arr, [0, 1]).all():
M = arr.astype(bool)
return M[:, t], (M[:, cov] if p else np.zeros((n, 0), dtype=bool))
M = np.zeros((n, d), dtype=bool)
for i, entry in enumerate(seq):
if entry is None:
continue
if isinstance(entry, (str, int, np.integer)):
M[i, _column(entry, names, "intervention")] = True
else:
for col in entry:
if col is not None:
M[i, _column(col, names, "intervention")] = True
return M[:, t], (M[:, cov] if p else np.zeros((n, 0), dtype=bool))
def effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None,
reference=None, names=None, extrapolate=False, discovery_samples=64, tta=1, seed=0,
interventions=None):
"""The effect of setting `treatment` on `outcome` in a table (a DataFrame or an (n, d)
array; `names` for an array's columns), given an optional graph: a DAG as an edge list of
(cause, effect) names, a (d, d) matrix or an adjacency DataFrame, or a discover() result.
`covariates`: the columns to adjust for (default: all others).
`interventions`: optional per-row experimental intervention labels (1D bool mask for `treatment`,
2D `(n, d)` bool mask, or length-`n` sequence of column names/lists/None) for observational +
experimental data fusion. Returns an EffectResult."""
X, names = _table(data, names)
t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome")
if t == y:
raise ValueError("the treatment and the outcome are the same column")
cov = [c for c in range(len(names)) if c not in (t, y)] if covariates is None else \
[_column(c, names, "covariate") for c in covariates]
if t in cov or y in cov:
raise ValueError("the covariates must not include the treatment or the outcome")
kind, dropped, R, zero = "none", [], np.zeros((len(names), N_ROLES)), False
if graph is not None and _is_discovered(graph):
kind = "discovered"
probs = _reorder(graph.probs, graph.names, names)
R = discovered_roles(probs, t, y, discovery_samples, seed)
if probs[t, y, CONF] > 0.2:
warnings.warn(f"the discovered graph gives {names[t]} and {names[y]} a hidden common cause with "
f"probability {probs[t, y, CONF]:.2f}: adjusting for measured covariates cannot remove "
f"its bias", stacklevel=3)
elif graph is not None:
kind = "dag"
A = _adjacency(graph, names)
R = roles(A, t, y)
zero = y not in descendants(A, t)
dropped = [c for c in cov if R[c, 1] == 1]
cov = [c for c in cov if R[c, 1] == 0]
features = np.column_stack([np.full(len(cov), float(kind != "none")), R[cov]]).reshape(len(cov), N_FEATURES)
used = [t, y] + cov
if not np.isfinite(X[:, used]).all():
raise ValueError("missing or non-finite values in the treatment, the outcome or the covariates; "
"drop or impute those rows first")
n = len(X)
if n < TRAIN_N[0]:
warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3)
t_int_all, w_int_all = parse_interventions(interventions, n, names, t, cov)
C = X[:, cov]
if len(cov) > TRAIN_COVARIATES:
warnings.warn(f"{len(cov)} covariates, more than in training (up to {TRAIN_COVARIATES})", stacklevel=3)
T, Y = X[:, t], X[:, y]
levels = np.unique(T)
binary = len(levels) == 2
if not binary and len(levels) < MIN_LEVELS:
raise ValueError(f"the treatment has {len(levels)} distinct values: binary (2) and continuous (at least "
f"{MIN_LEVELS}) treatments are supported")
if binary:
vals = [float(levels[0]), float(levels[1])]
a, b = vals
curve_vals, ref = None, None
else:
lo, hi = np.quantile(T, TRAIN_LEVELS)
a, b = contrast if contrast is not None else tuple(float(v) for v in np.quantile(T, CONTRAST_LEVELS))
curve_vals = np.asarray(values if values is not None else np.quantile(T, CURVE_LEVELS), dtype=np.float64)
ref = float(np.median(T) if reference is None else reference)
asked = np.concatenate([[a, b, ref], curve_vals])
outside = asked[(asked < lo) | (asked > hi)]
if len(outside):
msg = (f"treatment value(s) {sorted(set(outside.round(6)))} outside its 2-98% quantiles "
f"[{lo:.4g}, {hi:.4g}]: the data hardly covers them")
if not extrapolate:
raise ValueError(msg + "; pass extrapolate=True to estimate anyway")
warnings.warn(msg, stacklevel=3)
vals = sorted(set(float(v) for v in asked))
k = {v: i for i, v in enumerate(vals)}
rng = np.random.default_rng(seed)
strata = _local_strata(C, T, binary, TRAIN_N[1], rng)
est = {"contrast": [], "att": [], "atc": []} if binary else {"contrast": [], "curve": []}
counts = {key: [] for key in est}
cate, mu0, mu1, prop_nn = np.empty(n), np.empty(n), np.empty(n), np.empty(n)
multi = len(strata) > 1
for idx_s, (q_rows, ctx_rows) in enumerate(strata):
same = len(q_rows) == len(ctx_rows) and np.array_equal(q_rows, ctx_rows)
self_idx = None
if not same:
pos = np.full(n, -1, dtype=np.int64)
pos[ctx_rows] = np.arange(len(ctx_rows), dtype=np.int64)
idx = pos[q_rows]
if (idx >= 0).any():
self_idx = idx
if cov:
Wz_ctx, wm, ws = _standardize(C[ctx_rows])
Wz_qry = None if same else (C[q_rows] - wm) / ws
else:
Wz_ctx = np.zeros((len(ctx_rows), 0))
Wz_qry = None if same else np.zeros((len(q_rows), 0))
Tz_ctx, tm, ts = _standardize(T[ctx_rows])
Yz_ctx, ym, ys = _standardize(Y[ctx_rows])
# On multi-stratum tables, keep per-cluster quantiles plug-in and apply dr_gate once globally
# after assembling full-table (mu0, mu1, prop_nn) so covariate-cluster splitting cannot distort ATT/ATE.
Tz_qry = None if (same or multi) else (T[q_rows] - tm) / ts
Yz_qry = None if (same or multi) else (Y[q_rows] - ym) / ys
vz = (np.array(vals) - tm) / ts
all_q = np.ones(len(q_rows), dtype=bool)
jobs = [(k[a], k[b], all_q, "contrast")]
if binary:
treated_q = T[q_rows] == levels[1]
if treated_q.any():
jobs.append((k[a], k[b], treated_q, "att"))
if (~treated_q).any():
jobs.append((k[a], k[b], ~treated_q, "atc"))
else:
jobs += [(k[ref], k[v], all_q, "curve") for v in curve_vals]
t_int_ctx = t_int_all[ctx_rows] if t_int_all is not None else None
w_int_ctx = w_int_all[ctx_rows] if (w_int_all is not None and cov) else None
out = model.predict(Wz_ctx, Tz_ctx, Yz_ctx, features, binary, vz,
[(i, j, r) for i, j, r, _ in jobs], W_qry=Wz_qry, self_idx=self_idx,
tta=tta, seed=seed + idx_s * 97, t_int=t_int_ctx, w_int=w_int_ctx,
T_qry=Tz_qry, Y_qry=Yz_qry)
Q = out["quantiles"] * ys
curve = []
for (_, _, r, name), q in zip(jobs, Q):
if name == "curve":
curve.append(q)
else:
est[name].append(q)
counts[name].append(r.sum())
if curve:
est["curve"].append(np.stack(curve))
counts["curve"].append(len(q_rows))
cate[q_rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ys
if binary:
mu0[q_rows], mu1[q_rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ym
if "propensity" in out:
prop_nn[q_rows] = out["propensity"]
quantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve" and est[name]}
if binary and multi and (t_int_all is None or not t_int_all.any()) and hasattr(model, "dr_blend"):
treated_all = (T == levels[1]).astype(float)
for key, target in (("contrast", "ate"), ("att", "att")):
if key in quantiles:
q_pi = quantiles[key]
est_dr = model.dr_blend(mu0, mu1, prop_nn, treated_all, Y, target=target)
quantiles[key] = q_pi + (est_dr - q_pi[MID])
result = EffectResult(names[t], names[y], binary, [names[c] for c in cov], [names[c] for c in dropped], kind,
(a, b), quantiles, cate, n_rows=n, n_subsets=len(strata),
roles={names[c]: dict(zip(ROLE_NAMES, map(float, R[c]))) for c in cov} if kind != "none" else {})
result.n_intervened = int(t_int_all.sum()) if t_int_all is not None else 0
if binary:
treated = (T == levels[1]).astype(float)
e = result.propensity = _propensity(C, treated, seed)
rct_deb = _rct_debiased(mu0, mu1, treated, Y, t_int_all) if t_int_all is not None else None
if rct_deb is not None:
# Zero-hyperparameter Empirical-Bayes (James-Stein) fusion of the neural zero-shot
# estimate and the unbiased RCT-rectified estimate: keeps neural variance reduction
# when obs+RCT agree, and falls back smoothly to unbiased RCT rectification under shift.
q_nn = result.quantiles["contrast"]
a_nn = float(q_nn[MID])
s_nn = float(max(q_nn[-1] - q_nn[0], 0.0) / (2.0 * Z90))
a_d, lo_d, hi_d = rct_deb["ate"]
s_d = float(max(hi_d - lo_d, 0.0) / (2.0 * Z90))
diff2 = (a_nn - a_d) ** 2
w = (s_d ** 2) / (s_d ** 2 + diff2 + 1e-12)
a_eb = w * a_nn + (1.0 - w) * a_d
s_eb = float(np.sqrt(w * (s_nn ** 2 + (a_nn - a_eb) ** 2) + (1.0 - w) * (s_d ** 2 + (a_d - a_eb) ** 2)))
z50 = 0.6744897501960817
result.quantiles["contrast"] = np.array(
[a_eb - Z90 * s_eb, a_eb - z50 * s_eb, a_eb, a_eb + z50 * s_eb, a_eb + Z90 * s_eb],
dtype=float,
)
extreme = np.mean((e < 0.02) | (e > 0.98))
if extreme > 0.1 and rct_deb is None:
warnings.warn(f"{extreme:.0%} of rows have a predicted propensity outside 2-98%: poor overlap, the "
f"estimates there rest on extrapolation", stacklevel=3)
else:
result.values, result.reference = curve_vals, ref
C_arr = np.asarray(est["curve"]) # (strata, K, Q)
result.curve = np.stack([_combine(C_arr[:, j], counts["curve"]) for j in range(C_arr.shape[1])])
result.curve[curve_vals == ref] = 0.0
if zero:
warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0",
stacklevel=3)
result.zero_by_graph = True
result.quantiles = {name: np.zeros(len(QUANTILES)) for name in result.quantiles}
result.cate = np.zeros(n)
if result.curve is not None:
result.curve = np.zeros_like(result.curve)
return result