Files
models/models/tea/association.py
T

390 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The EEG–ADOS-2 association (core.tea.association says what it relates): per biomarker,
zone and outcome, how a child's deviation from the age curve (z) goes with an altered
ADOS-2 item or a high CSS, adjusted for age and module.
- An item: Firth's penalised logistic regression of "altered" on z (the principal model; its
odds ratio, a 95 % profile-likelihood interval and a likelihood-ratio p), with a
cumulative-logit model of the item's level as sensitivity; the CSS the other way round.
- q: Benjamini–Hochberg within each biomarker.
- A child's probability: the principal model at her z (Firth's with the FLIC intercept, so
its probabilities average to the observed rate), and the reference child's (z = 0, the
cohort's mean age, the commonest module).
The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py)."""
import warnings
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from scipy import optimize, stats
from scipy.special import expit
from statsmodels.stats.multitest import multipletests
from core.tea import association as spec
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8
TOO_FEW = "too few data or no variation"
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
"""Item `number`'s algorithm score for each child whose module administers it."""
name, modules = spec.ITEMS[number]
if name not in frame or "module" not in frame:
return pd.Series(np.nan, index=frame.index)
v = pd.to_numeric(frame[name], errors="coerce")
v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2)
return v.where(frame["module"].isin(modules))
def has_items(frame: pd.DataFrame) -> bool:
scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1)
return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN
@dataclass
class Design:
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
the cohort's mean and each categorical one against its commonest level."""
predictor: str
numeric: dict[str, float] = field(default_factory=dict)
categorical: dict[str, list[str]] = field(default_factory=dict)
reference: dict[str, str] = field(default_factory=dict)
@classmethod
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
d = cls(predictor)
for a in (a for a in spec.ADJUST if a in t):
v = t[a]
if pd.api.types.is_numeric_dtype(v):
if v.astype(float).std() > 0:
d.numeric[a] = float(v.astype(float).mean())
continue
commonest = v.value_counts().index[0]
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
if levels:
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
return d
@property
def names(self) -> list[str]:
return [
"intercept",
self.predictor,
*self.numeric,
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
]
def matrix(self, t: pd.DataFrame) -> np.ndarray:
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()]
known = np.ones(len(t), bool)
for a, levels in self.categorical.items():
v = t[a].astype(str)
cols += [(v == x).to_numpy(float) for x in levels]
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy()
X = np.column_stack(cols)
X[~known] = np.nan
return X
def state(self) -> dict:
return {
"predictor": self.predictor,
"numeric": self.numeric,
"categorical": self.categorical,
"reference": self.reference,
}
@classmethod
def from_state(cls, s: dict) -> "Design":
return cls(
s["predictor"],
dict(s["numeric"]),
{k: list(v) for k, v in s["categorical"].items()},
dict(s["reference"]),
)
# Firth: the log-likelihood penalised by half the log-determinant of the information.
def _penalised(b, X, y) -> float:
eta = X @ b
w = expit(eta) * (1 - expit(eta))
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
def _gradient(b, X, y):
"""The penalised score and the information at `b`."""
p = expit(X @ b)
w = p * (1 - p)
info = X.T @ (X * w[:, None])
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
return X.T @ (y - p + leverage * (0.5 - p)), info
def _firth_fit(X, y, max_iter=200, tol=1e-10):
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
b = np.zeros(X.shape[1])
best = _penalised(b, X, y)
for _ in range(max_iter):
score, info = _gradient(b, X, y)
step, t = np.linalg.solve(info, score), 1.0
while t > 1e-8:
trial = _penalised(b + t * step, X, y)
if trial >= best - 1e-12:
break
t /= 2
b, best = b + t * step, trial
if np.max(np.abs(t * step)) < tol:
break
return b, best
def _firth_profile(value, j, X, y, start) -> float:
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
free = [k for k in range(X.shape[1]) if k != j]
def negative(bf):
b = np.empty(X.shape[1])
b[free], b[j] = bf, value
v = _penalised(b, X, y)
if not np.isfinite(v):
return 1e10, np.zeros(len(free))
return -v, -_gradient(b, X, y)[0][free]
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
each side of `centre`, searched in steps of `scale` (infinite if never)."""
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
limits = []
for sign in (-1, 1):
previous, limit = centre, sign * np.inf
for k in range(1, 80):
v = centre + sign * scale * k
if drop(v) > 0:
limit = optimize.brentq(drop, min(previous, v), max(previous, v))
break
previous = v
limits.append(limit)
return limits[0], limits[1]
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
return {
"model": model,
"n": n,
"coef": round(float(coef), 4),
"odds_ratio": round(float(np.exp(coef)), 4),
"ci_low": round(float(np.exp(low)), 4),
"ci_high": round(float(np.exp(high)), 4),
"p": round(p, 5),
"adjusted_for": ", ".join(design.names[2:]),
"reason": "",
**extra,
"state": {"design": design.state(), **state},
}
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW}
design = Design.of(d, predictor)
X = design.matrix(d)
b, top = _firth_fit(X, y)
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731
low, high = _interval(profile, b[1], top, max(se, 0.05))
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
# FLIC: the intercept refitted so the probabilities add up to the events.
eta = X[:, 1:] @ b[1:]
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing.
def _ordinal_nll(par, X, y, K) -> float:
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
eta = X @ par[K - 1 :]
n = len(y)
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
return -float(
np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None)))
)
def _ordinal_fit(X, y, K, fixed=None):
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
if fixed is None:
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
return r.x, float(r.fun)
j, value = fixed
free = [k for k in range(len(start)) if k != K - 1 + j]
def nll(q):
par = np.empty(len(start))
par[free], par[K - 1 + j] = q, value
return _ordinal_nll(par, X, y, K)
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW}
design = Design.of(d, predictor)
X = design.matrix(d)[:, 1:]
K = len(levels)
y = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _ordinal_fit(X, y, K)
beta = par[K - 1 :]
if abs(beta[0]) > 20:
return {**out, "reason": "does not converge (separation)"}
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731
low, high_ = _interval(profile, beta[0], -nll, 0.1)
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
inside = 0 < k < K
state = {
"beta": [float(v) for v in beta],
"threshold": float(theta[k - 1]) if inside else None,
"always": None if inside else float(k == 0),
}
return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K)
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
"""Each child's probability of the outcome under `fit`, and the reference child's."""
s = fit["state"]
X = Design.from_state(s["design"]).matrix(t)
if fit["model"] == "firth":
return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float(
expit(s["intercept"])
)
if s["threshold"] is None:
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]
return (
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
float(1 - expit(s["threshold"])),
)
def _guarded(fit, *args) -> dict:
try:
return fit(*args)
except (np.linalg.LinAlgError, ValueError) as error:
model = "firth" if fit is firth else "ordinal"
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
"""Every pair's principal and sensitivity models and its q: what the association is."""
if level == "auto":
level = "item" if has_items(cohort) else "domain"
rows = []
for pair in spec.pairs(level):
if pair["predictor"] not in cohort:
continue
d = cohort.copy()
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
if pair["kind"] == "item":
d["_level"] = item_scores(cohort, pair["outcome"])
d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna())
principal = _guarded(firth, d, "_yes", pair["predictor"])
sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED)
else:
d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce")
d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna())
principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH)
sensitivity = _guarded(firth, d, "_yes", pair["predictor"])
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
biomarkers = np.array([r["biomarker"] for r in rows])
q = np.full(len(rows), np.nan)
for b in dict.fromkeys(biomarkers):
mine = (biomarkers == b) & np.isfinite(p)
if mine.any():
q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5)
for r, v in zip(rows, q, strict=True):
r["q"] = None if np.isnan(v) else float(v)
return {"level": level, "n": len(cohort), "rows": rows}
def outcome_code(row: dict) -> str:
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
def associations(fitted: dict) -> list[dict]:
"""One row per pair: what the governance report and the record show."""
out = []
for r in fitted["rows"]:
f, s = r["principal"], r["sensitivity"]
ratio, other = f.get("odds_ratio"), s.get("odds_ratio")
out.append(
{
"biomarker": r["biomarker"],
"zone": r["zone"],
"kind": r["kind"],
"outcome": r["outcome"],
"outcome_code": outcome_code(r),
"event": f">={spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH}",
"model": f["model"],
"n": f["n"],
"odds_ratio": ratio,
"ci_low": f.get("ci_low"),
"ci_high": f.get("ci_high"),
"p": f.get("p"),
"q": r["q"],
"sens_model": s["model"],
"sens_odds_ratio": other,
"same_direction": None
if ratio is None or other is None
else bool(np.sign(ratio - 1) == np.sign(other - 1)),
"reason": f.get("reason", ""),
}
)
return out
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]:
"""Each child's probability under every estimated pair, and the reference child's."""
out = []
for r in fitted["rows"]:
f = r["principal"]
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
continue
t = cohort
if r["kind"] == "item":
t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])]
t = t[t[r["predictor"]].notna()]
if not len(t):
continue
found, reference = probability(f, t)
for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True):
if np.isfinite(p):
out.append(
{
"key": key,
"biomarker": r["biomarker"],
"zone": r["zone"],
"outcome_code": outcome_code(r),
"z": float(z),
"probability": round(float(p), 4),
"reference_probability": round(reference, 4),
}
)
return out