Source code for penalized_stream._sup_score

"""The sup-score test of Belloni, Chen, Chernozhukov and Hansen (2012) and
Chernozhukov, Hansen and Spindler (2015): inference on the effect of an
endogenous treatment that stays valid however weak the instruments are.

Under the null that the effect is a, e(a) = rho_y - a rho_d is uncorrelated
with every instrument, where rho_y and rho_d are the outcome's and the
treatment's residuals from their post-lasso fits on the controls selected
for them. The statistic is

    S(a) = max_j |sum_i w_i z_ij e_i(a)| / sqrt(V_j(a)),

the instruments z partialled only on the always-included regressors (and the
fixed effects or intercept), as lassopack's `ivlasso` does, and V_j(a) the
variance of instrument j's score: iid (sum w z_j^2 times the mean of w e^2),
heteroskedastic (sum w z_j^2 e^2) or clustered (sum over clusters of the
squared cluster sums). The critical value is either the bound
c Phi^-1(1 - gamma / (2p)) (lassopack's default, ``"bound"``) or the
multiplier bootstrap's (``"bootstrap"``).

Each score is linear in a and each variance quadratic, so one pass over the
saved rows gives three vectors (for the bound) or three p x p matrices (for
the bootstrap) from which the test follows at every a. With the bound, the
confidence set is the intersection of one quadratic inequality per
instrument, solved exactly; with the bootstrap, it is read off a grid. With
Gaussian multipliers the bootstrap's draws given the data are exactly
normal with the scores' covariance, so they are drawn from that covariance,
without another pass, and the same standard normal draws serve every point
of the grid.
"""

from __future__ import annotations

from dataclasses import dataclass, field

import numpy as np
import polars as pl
import scipy.sparse as sp
from scipy.stats import norm

from ._rigorous import _ClusterCodes
from ._solver import moments
from ._subset import row_batches

OPTIONS = ("null", "method", "level", "c", "draws", "grid", "seed")


[docs] @dataclass class SupScoreTest: """The sup-score test of the treatment's effect (``result.double_selection.sup_score``). `statistic`, `critical_value`, `p_value` and `rejected` are for the null value `null`; `confidence_set` is the set of values the test does not reject at `level`, a list of (low, high) intervals (``-inf`` or ``inf`` where unbounded; empty when it rejects every value). With the bootstrap the set is read off `grid`, and `at_grid_edge` says whether it reaches the grid's first or last value. `grid` has the test at each value.""" null: float statistic: float critical_value: float p_value: float rejected: bool confidence_set: list level: float method: str variance: str n_instruments: int c: float draws: int | None grid: pl.DataFrame = field(repr=False) at_grid_edge: tuple = (False, False) def summary_text(self) -> str: crit = (f"critical value {self.critical_value:.3f}" if self.method == "bound" else f"{self.draws} bootstrap draws") lines = [f" sup-score test ({self.method}, {self.variance}; {self.n_instruments} " f"instruments): effect = {self.null:g}: statistic {self.statistic:.3f}, " f"{crit}, p = {self.p_value:.4f}" + (" (rejected)" if self.rejected else "")] lines.append(f" sup-score {self.level:.0%} confidence set: {format_set(self)}") return "\n".join(lines)
def format_set(test: SupScoreTest) -> str: if not test.confidence_set: return "empty (every value rejected)" if test.confidence_set == [(-np.inf, np.inf)]: return "every value (the test rejects none)" parts = [] for lo, hi in test.confidence_set: if lo == hi: parts.append(f"{lo:.4g}") else: parts.append(("(-inf" if lo == -np.inf else f"[{lo:.4g}") + ", " + ("inf)" if hi == np.inf else f"{hi:.4g}]")) text = " U ".join(parts) lo_edge, hi_edge = test.at_grid_edge if lo_edge or hi_edge: text += " (reaches the grid's edge)" return text def check_options(options): options = dict(options or {}) unknown = [k for k in options if k not in OPTIONS] if unknown: raise ValueError(f"sup_score_options: unknown {unknown}; the options are " f"{list(OPTIONS)}") method = options.get("method", "bound") if method not in ("bound", "bootstrap"): raise ValueError(f"sup_score_options: method must be 'bound' or 'bootstrap'; " f"got {method!r}") level = float(options.get("level", 0.95)) if not 0.0 < level < 1.0: raise ValueError(f"sup_score_options: level must be between 0 and 1; got {level}") c = float(options.get("c", 1.1)) if c <= 0: raise ValueError(f"sup_score_options: c must be positive; got {c}") draws = int(options.get("draws", 500)) if draws < 1: raise ValueError(f"sup_score_options: draws must be positive; got {draws}") grid = options.get("grid") if grid is not None: if isinstance(grid, tuple) and len(grid) == 3: lo, hi, k = grid if not (hi > lo and int(k) >= 2): raise ValueError("sup_score_options: grid=(low, high, points) needs " "high > low and at least 2 points") else: grid = np.asarray(grid, dtype=float) if grid.ndim != 1 or grid.size == 0 or not np.all(np.isfinite(grid)): raise ValueError("sup_score_options: grid must be (low, high, points) or a " "list of finite values") return {"null": float(options.get("null", 0.0)), "method": method, "level": level, "c": c, "draws": draws, "grid": grid, "seed": options.get("seed")} @dataclass class _Sums: """Each instrument's score, A - a B, and its variance, C - 2a D + a^2 E; for the bootstrap, the scores' covariance Oyy - 2a Oyd + a^2 Odd.""" A: np.ndarray B: np.ndarray C: np.ndarray D: np.ndarray E: np.ndarray Omega: tuple | None def score(self, a): return self.A - a * self.B def var(self, a): return self.C - 2.0 * a * self.D + a * a * self.E def statistic(self, a): v = np.maximum(self.var(a), 0.0) with np.errstate(divide="ignore", invalid="ignore"): t = np.abs(self.score(a)) / np.sqrt(v) t = np.where(v > 0, t, 0.0) return float(t.max()) if t.size else 0.0 def accumulate(design, t_y, t_d, T_z, *, variance, cluster, bootstrap): """One pass over the saved rows: the sums of the scores and of their squares (or cross-products), for every instrument (the rows of T_z, each a combination of [outcome, covariates...] as t_y and t_d are).""" cp = design.cp order = [design.depvar, *design.names] m = moments(cp.total(), cp.sums.sum(axis=0), cp.weight_sums.sum(), int(cp.counts.sum()), standardize=False) mean = np.asarray(m.mean, dtype=float) weight = cp.weight_column q = T_z.shape[0] T = np.ascontiguousarray(np.vstack([t_y, t_d, T_z]).T) # (1 + k, 2 + q) A = np.zeros(q) B = np.zeros(q) Z2 = np.zeros(q) C = np.zeros(q) D = np.zeros(q) E = np.zeros(q) s = np.zeros(3) # sum w ry^2, ry rd, rd^2 Omega = [np.zeros((q, q)) for _ in range(3)] if bootstrap else None ZZ = np.zeros((q, q)) if bootstrap and variance == "iid" else None codes = _ClusterCodes(cluster) if variance == "cluster" else None Sy, Sd = [], [] for lf in row_batches(cp): frame = lf.collect() if frame.height == 0: continue M = frame.select(order).to_numpy(order="c").astype(np.float64, copy=False) - mean R = M @ T ry, rd, Z = R[:, 0], R[:, 1], R[:, 2:] w = (frame.get_column(weight).to_numpy().astype(np.float64) if weight else np.ones(frame.height)) wy, wd = w * ry, w * rd A += Z.T @ wy B += Z.T @ wd if variance == "cluster": g = codes(frame) ind = sp.csr_matrix((np.ones(len(g)), (g, np.arange(len(g)))), shape=(codes.n, len(g))) Sy.append((ind @ (Z * wy[:, None]), codes.n)) Sd.append((ind @ (Z * wd[:, None]), codes.n)) continue if variance == "iid": Z2 += (Z * Z).T @ w s += [wy @ ry, wy @ rd, wd @ rd] if bootstrap: ZZ += (Z * w[:, None]).T @ Z continue ZZw = Z * Z C += ZZw.T @ (wy * ry) D += ZZw.T @ (wy * rd) E += ZZw.T @ (wd * rd) if bootstrap: for o, r in zip(Omega, (wy * ry, wy * rd, wd * rd), strict=True): o += (Z * r[:, None]).T @ Z if variance == "cluster": G = codes.n Ky, Kd = np.zeros((G, q)), np.zeros((G, q)) for parts, K in ((Sy, Ky), (Sd, Kd)): for part, n_g in parts: K[:n_g] += part C, D, E = (Ky * Ky).sum(0), (Ky * Kd).sum(0), (Kd * Kd).sum(0) if bootstrap: Omega = [Ky.T @ Ky, Ky.T @ Kd, Kd.T @ Kd] elif variance == "iid": W = float(m.W) C, D, E = Z2 * s[0] / W, Z2 * s[1] / W, Z2 * s[2] / W if bootstrap: Omega = [ZZ * s[0] / W, ZZ * s[1] / W, ZZ * s[2] / W] return _Sums(A, B, C, D, E, tuple(Omega) if bootstrap else None) def _solve_quadratic(qa, qb, qc, scale): """{a : qa a^2 + qb a + qc <= 0} as a list of closed intervals.""" inf = np.inf if abs(qa) <= 1e-12 * scale: if abs(qb) <= 1e-12 * scale: return [(-inf, inf)] if qc <= 0 else [] r = -qc / qb return [(-inf, r)] if qb > 0 else [(r, inf)] disc = qb * qb - 4.0 * qa * qc if disc < 0: return [] if qa > 0 else [(-inf, inf)] sq = np.sqrt(disc) r1, r2 = sorted(((-qb - sq) / (2 * qa), (-qb + sq) / (2 * qa))) return [(r1, r2)] if qa > 0 else [(-inf, r1), (r2, inf)] def _intersect(a, b): out = [] for lo1, hi1 in a: for lo2, hi2 in b: lo, hi = max(lo1, lo2), min(hi1, hi2) if lo <= hi: out.append((lo, hi)) return sorted(out) def bound_set(sums: _Sums, k: float, usable): """The values a at which no instrument's |score| exceeds k times its standard deviation: (A_j - a B_j)^2 <= k^2 (C_j - 2a D_j + a^2 E_j).""" out = [(-np.inf, np.inf)] k2 = k * k for j in np.flatnonzero(usable): A, B, C, D, E = (float(v[j]) for v in (sums.A, sums.B, sums.C, sums.D, sums.E)) qa = B * B - k2 * E qb = -2.0 * (A * B - k2 * D) qc = A * A - k2 * C scale = B * B + k2 * E + abs(A * B) + k2 * abs(D) + 1e-300 out = _intersect(out, _solve_quadratic(qa, qb, qc, scale)) if not out: break return [(float(lo), float(hi)) for lo, hi in out] def _bootstrap_p(sums: _Sums, a, U, usable, stat): """The share of the multiplier bootstrap's maxima above `stat`.""" Oyy, Oyd, Odd = sums.Omega Omega = (Oyy - 2.0 * a * Oyd + a * a * Odd)[np.ix_(usable, usable)] sd = np.sqrt(np.maximum(np.diag(Omega), 0.0)) ok = sd > 0 if not ok.any(): return 1.0 Rm = Omega[np.ix_(ok, ok)] / np.outer(sd[ok], sd[ok]) lam, V = np.linalg.eigh((Rm + Rm.T) / 2) L = V * np.sqrt(np.maximum(lam, 0.0)) sims = np.abs(U[:, :L.shape[0]] @ L.T).max(axis=1) return float(np.mean(sims > stat)) def _grid_values(grid, center, se): if grid is None: half = 20.0 * se if np.isfinite(se) and se > 0 else max(abs(center), 1.0) return np.linspace(center - half, center + half, 101) if isinstance(grid, tuple): lo, hi, k = grid return np.linspace(float(lo), float(hi), int(k)) return np.sort(np.asarray(grid, dtype=float)) def _runs(values, accepted): """The runs of accepted grid values, as (first, last) pairs.""" out, start = [], None for i, ok in enumerate(accepted): if ok and start is None: start = i if not ok and start is not None: out.append((float(values[start]), float(values[i - 1]))) start = None if start is not None: out.append((float(values[start]), float(values[-1]))) return out def sup_score_test(sums: _Sums, *, options, variance, center, se): usable = (sums.C > 0) | (sums.E > 0) p = int(usable.sum()) if p == 0: raise ValueError("sup-score test: no instrument varies once the always-included " "regressors and fixed effects are partialled out") gamma = 1.0 - options["level"] c = options["c"] k = float(c * norm.ppf(1.0 - gamma / (2.0 * p))) method = options["method"] values = _grid_values(options["grid"], center, se) stats = np.array([sums.statistic(a) for a in values]) null = options["null"] stat0 = sums.statistic(null) if method == "bound": cset = bound_set(sums, k, usable) def pval(s): return float(min(1.0, 2.0 * p * norm.sf(s / c))) p0 = pval(stat0) rejected = stat0 > k pv = np.array([pval(s) for s in stats]) rej = stats > k edge = (False, False) draws = None else: draws = options["draws"] rng = np.random.default_rng(options["seed"]) U = rng.standard_normal((draws, p)) p0 = _bootstrap_p(sums, null, U, usable, stat0) rejected = p0 < gamma pv = np.array([_bootstrap_p(sums, a, U, usable, s) for a, s in zip(values, stats, strict=True)]) rej = pv < gamma cset = _runs(values, ~rej) edge = (bool(len(values) and not rej[0]), bool(len(values) and not rej[-1])) k = float("nan") grid = pl.DataFrame({"value": values, "statistic": stats, "p_value": pv, "rejected": rej}) return SupScoreTest(null=null, statistic=stat0, critical_value=k, p_value=p0, rejected=bool(rejected), confidence_set=cset, level=options["level"], method=method, variance=variance, n_instruments=p, c=c, draws=draws, grid=grid, at_grid_edge=edge)