ADOS-2 association 0.4.0: spikes present or not by group, composites of items, few events flagged, exploratory pairs apart from q, leave-one-out scoring, older fits refused; its models in their own module

This commit is contained in:
Roberto Treviño
2026-12-06 04:07:13 -06:00
parent e2487062ae
commit 8ed086bcbc
3 changed files with 444 additions and 328 deletions
+140 -313
View File
@@ -2,29 +2,28 @@
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.
- An item: Firth's penalised logistic regression of "altered" on z (the principal model),
with a cumulative-logit model of the item's level as sensitivity; the CSS, and a composite
of items with too few events (by how many are altered), the other way round.
- q: Benjamini–Hochberg within each biomarker, exploratory pairs apart.
- 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)."""
A child the association was fitted on is scored by the model refitted without her
(leave-one-out); spikes enter as present or not over a group of zones (`spikes_any`), and an
estimate on fewer than MIN_EVENTS children with (or without) the event is flagged. The
models are models.tea.logit's."""
import warnings
from dataclasses import dataclass, field
import hashlib
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"
from core.tea.reasons import INSUFFICIENT_DATA
from models.tea.eeg.spindles import ZONES
from models.tea.logit import firth, firth_fit, ordinal, ordinal_fit, probability, rows
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
@@ -42,244 +41,17 @@ def has_items(frame: pd.DataFrame) -> bool:
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 _state(model: str, t: pd.DataFrame, pair: dict) -> dict | None:
"""Only the scoring state of a pair's model refitted on `t` (leave-one-out)."""
try:
if model == "firth":
fitted = firth_fit(rows(t, "_yes", pair["predictor"]), "_yes", pair["predictor"])
return fitted and fitted[-1]
fitted = ordinal_fit(rows(t, "_level", pair["predictor"]), "_level", pair["predictor"],
_high(pair)) # fmt: skip
return fitted[-1] if isinstance(fitted, tuple) else None
except (np.linalg.LinAlgError, ValueError):
return None
def _guarded(fit, *args) -> dict:
@@ -290,41 +62,101 @@ def _guarded(fit, *args) -> dict:
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
def _high(pair: dict) -> int:
return {"composite": 1, "domain": spec.CSS_HIGH}.get(pair["kind"], spec.ALTERED)
def outcome(t: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
"""(event, level): the CSS high, or any of the items altered; the level is the CSS, the
item's score or how many of the items are altered."""
if pair["kind"] == "domain":
css = pd.to_numeric(t["css"] if "css" in t else np.nan, errors="coerce")
css = pd.Series(css, index=t.index)
return (css >= spec.CSS_HIGH).astype(float).where(css.notna()), css
scores = pd.concat([item_scores(t, n) for n in spec.outcome_items(pair)], axis=1)
complete = scores.notna().all(axis=1)
altered = (scores >= spec.ALTERED).sum(axis=1).astype(float).where(complete)
level = altered if pair["kind"] == "composite" else scores.iloc[:, 0]
return (altered >= 1).astype(float).where(complete), level
def _fit_pair(d: pd.DataFrame, pair: dict) -> dict:
"""A pair's principal and sensitivity models: the CSS and a composite with too few events
by its level (the cumulative logit), an item by whether it is altered (Firth); an
estimate on fewer than MIN_EVENTS children with (or without) the event is flagged."""
used = d[["_yes", pair["predictor"]]].dropna()
events = int(used["_yes"].sum())
without = len(used) - events
short = min(events, without) < spec.MIN_EVENTS
counted = short and pair["kind"] == "composite"
binary = _guarded(firth, d, "_yes", pair["predictor"])
graded = _guarded(ordinal, d, "_level", pair["predictor"], _high(pair))
principal, sensitivity = ((graded, binary) if pair["kind"] == "domain" or counted
else (binary, graded)) # fmt: skip
if short and principal.get("odds_ratio") is not None:
note = (f"{INSUFFICIENT_DATA}{events} con evento y {without} sin evento "
f"(mínimo {spec.MIN_EVENTS})") # fmt: skip
if counted:
note += "; se usa el número de reactivos alterados"
principal = {**principal, "reason": note}
return {**pair, "principal": principal, "sensitivity": sensitivity}
def spikes_any(features: dict) -> dict[str, float]:
"""Whether the EEG shows any spike while asleep over each group of zones (NaN when no
minute or electrode of the group was read), from the spikes' rates by electrode."""
minutes = features.get("minutes") or 0
out = {}
for group, zones in spec.SPIKE_GROUPS.items():
rates = [features.get(f"electrode_{e}") for z in zones for e in ZONES[z]]
counts = [r * minutes for r in rates if r is not None]
out[f"spikes_any_{group}"] = (float(any(n > 0 for n in counts))
if minutes > 0 and counts else np.nan) # fmt: skip
return out
def _key(key) -> str:
return hashlib.sha256(str(key).encode()).hexdigest()[:16]
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
"""Every pair's principal and sensitivity models and its q: what the association is."""
"""Every pair's principal and sensitivity models and its q (Benjamini–Hochberg within
each biomarker, exploratory pairs apart): what the association is."""
if level == "auto":
level = "item" if has_items(cohort) else "domain"
rows = []
for pair in spec.pairs(level):
tested, rows = spec.pairs(level), []
for pair in tested:
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})
d[pair["predictor"]] = pd.to_numeric(d[pair["predictor"]], errors="coerce").replace(
[np.inf, -np.inf], np.nan) # fmt: skip
d["_yes"], d["_level"] = outcome(d, pair)
rows.append(_fit_pair(d, pair))
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
biomarkers = np.array([r["biomarker"] for r in rows])
families = np.array([r["biomarker"] for r in rows])
tested_rows = np.array([r["kind"] != "exploratory" for r in rows], bool)
q = np.full(len(rows), np.nan)
for b in dict.fromkeys(biomarkers):
mine = (biomarkers == b) & np.isfinite(p)
for b in dict.fromkeys(families):
mine = (families == b) & np.isfinite(p) & tested_rows
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}
return {"version": spec.VERSION, "level": level, "n": len(cohort), "rows": rows,
"pairs": tested, "keys": sorted(_key(k) for k in cohort.get("key", []))} # fmt: skip
def outcome_code(row: dict) -> str:
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
def check(fitted: dict) -> dict:
"""A saved association this version can score (one fitted before it must be retrained)."""
if fitted.get("version") != spec.VERSION:
raise ValueError(f"association {fitted.get('version', '0.1.0')} was fitted before "
f"{spec.VERSION}: retrain it") # fmt: skip
return fitted
def _event(pair: dict) -> str:
return f"alguno >={spec.ALTERED}" if pair["kind"] == "composite" else f">={_high(pair)}"
def associations(fitted: dict) -> list[dict]:
@@ -333,57 +165,52 @@ def associations(fitted: dict) -> list[dict]:
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", ""),
}
)
out.append({
"biomarker": r["biomarker"], "zone": r["zone"], "kind": r["kind"],
"outcome": r["outcome"], "outcome_code": spec.outcome_code(r), "event": _event(r),
"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", ""),
}) # fmt: skip
return out
def _scored(t: pd.DataFrame, fitted: dict, pair: dict) -> tuple[np.ndarray, float]:
"""Each child's probability under the pair's principal model; a child the association
was fitted on, under the model refitted without her (leave-one-out)."""
f = pair["principal"]
found, reference = probability(f["model"], f["state"], t)
keys = set(fitted.get("keys", ()))
child = t["person"] if "person" in t else t["key"]
trained = t["key"].map(_key).isin(keys).to_numpy()
for name in child[trained].unique():
own = (child == name).to_numpy()
state = _state(f["model"], t[trained & ~own], pair)
found[own] = np.nan if state is None else probability(f["model"], state, t[own])[0]
return found, reference
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:
for r in check(fitted)["rows"]:
if r["principal"].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()]
for n in spec.outcome_items(r):
t = t[t["module"].isin(spec.ITEMS[n][1])]
t = t[pd.to_numeric(t[r["predictor"]], errors="coerce").notna()].copy()
if not len(t):
continue
found, reference = probability(f, t)
t["_yes"], t["_level"] = outcome(t, r)
found, reference = _scored(t, fitted, r)
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),
}
)
out.append({"key": key, "biomarker": r["biomarker"], "zone": r["zone"],
"outcome_code": spec.outcome_code(r), "z": float(z),
"probability": round(float(p), 4),
"reference_probability": round(reference, 4)}) # fmt: skip
return out
+17 -15
View File
@@ -5,6 +5,7 @@ analysed EEG against the child's age. The math is the old platform's, proved on
cohort by models/tests/test_eeg.py."""
import hashlib
import json
from dataclasses import dataclass
from datetime import date
@@ -152,8 +153,8 @@ class Association(mlflow.pyfunc.PythonModel):
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""(fit, scored): every valid EEG of a child with an ADOS-2 (known by `as_of`), her age,
module, items, CSS and the z of each biomarker; fitted on each child's first EEG with
any z, every EEG scored."""
module, items, CSS, the z of each biomarker and whether it shows spikes; fitted on each
child's first EEG with any, every EEG scored (her own refitted without her)."""
day = str(as_of) if as_of else None
rows = []
for r in eeg.association_inputs(relation.BIOMARKERS):
@@ -166,17 +167,18 @@ def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.Data
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
scored = ados2.score(row, date.fromisoformat(r["birth_date"]))
css = scored and scored.css
spikes = json.loads(r["features"] or "{}").get("eeg-spikes", {})
rows.append({"key": r["edf"], "person": r["person_id"], "age_months": r["age_months"],
"module": a.get("module"), "css": css,
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
**{k: v for k, v in r.items() if k.startswith("z_")}}) # fmt: skip
**{k: v for k, v in r.items() if k.startswith("z_")},
**association.spikes_any(spikes)}) # fmt: skip
scored = pd.DataFrame(rows)
if scored.empty:
return scored, scored
predictors = [c for c in scored.columns if c.startswith("z_")]
predictors = [c for c in scored.columns if c.startswith(("z_", "spikes_any_"))]
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
return fit.drop(columns=["person"]), scored.drop(columns=["person"])
return scored[with_z].drop_duplicates("person").reset_index(drop=True), scored
def _train_association(as_of: date | None = None) -> int:
@@ -189,8 +191,10 @@ def _train_association(as_of: date | None = None) -> int:
pairs = association.associations(fitted)
estimated = [p for p in pairs if p["odds_ratio"] is not None]
technical = {
"model": ASSOCIATION, "method": "Firth logistic (items) / cumulative logit (CSS), "
"adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
"model": ASSOCIATION, "version": relation.VERSION,
"method": "Firth logistic (items) / cumulative logit (CSS, and composites with few "
"events), adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg "
"q within each biomarker; each child scored leave-one-out",
"cohort": "site: children with an ADOS-2 and a valid EEG",
"as_of": str(as_of or date.today()),
"children": int(fitted["n"]), "level": fitted["level"], "pairs": len(pairs),
@@ -220,13 +224,11 @@ def _score_association() -> int | None:
"metric": relation.BIOMARKERS[p["biomarker"]], "principal": p["model"],
"sensitivity": p["sens_model"]}
for p in association.associations(fitted) if p["odds_ratio"] is not None] # fmt: skip
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, or the CSS
if not scored.empty:
keys = scored["key"].tolist()
for n in relation.ITEMS:
items = association.item_scores(scored, n).tolist()
observed[relation.item_code(n)] = dict(zip(keys, items, strict=True))
observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), strict=True))
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, how many of a
if not scored.empty: # composite's items are altered, or the CSS
for r in fitted["rows"]:
level = association.outcome(scored, r)[1].tolist()
observed[relation.outcome_code(r)] = dict(zip(scored["key"], level, strict=True))
scores = []
for one in association.score(fitted, scored) if not scored.empty else []:
seen = observed.get(one["outcome_code"], {}).get(one["key"])
+287
View File
@@ -0,0 +1,287 @@
"""The two models the EEG–ADOS-2 association fits (models.tea.association), adjusted for
age and module (core.tea.association.ADJUST):
- Firth's penalised logistic regression of an event (its odds ratio, a 95 % profile-
likelihood interval and a likelihood-ratio p); its probabilities with the FLIC intercept, so
they average to the observed rate;
- the cumulative logit of a level, P(level >= high) its probability.
Each fit keeps a scoring `state`: what `probability` needs, for any child and the reference
child (z = 0, the cohort's mean age, the commonest module)."""
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 core.tea.association import ADJUST
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8
TOO_FEW = "too few data or no variation"
SEPARATION = "does not converge (separation)"
@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 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 _newton(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 rows(t: pd.DataFrame, outcome: str, predictor: str) -> pd.DataFrame:
return t[[outcome, predictor, *(a for a in ADJUST if a in t)]].dropna()
def firth_fit(d: pd.DataFrame, outcome: str, predictor: str):
"""Firth's fit on complete rows `d`: the design, its matrix, the coefficients, the
penalised maximum and the scoring state (FLIC: the intercept refitted so the
probabilities add up to the events); None when it can't be fitted."""
y = d[outcome].to_numpy(float)
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
return None
design = Design.of(d, predictor)
X = design.matrix(d)
b, top = _newton(X, y)
eta = X[:, 1:] @ b[1:]
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
state = {"design": design.state(), "beta": [float(v) for v in b[1:]],
"intercept": float(intercept)} # fmt: skip
return design, X, y, b, top, state
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
d = rows(t, outcome, predictor)
out = {"model": "firth", "n": len(d), "events": int(d[outcome].sum())}
if (fitted := firth_fit(d, outcome, predictor)) is None:
return {**out, "reason": TOO_FEW}
design, X, y, b, top, state = fitted
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))
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 _cumulative(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_fit(d: pd.DataFrame, outcome: str, predictor: str, high: float):
"""The cumulative logit's fit on complete rows `d` (None when it can't be fitted, or
when it separates): the design, its matrix, levels, the parameters, the minimum and the
scoring state (P(level >= high))."""
levels = np.sort(d[outcome].unique())
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return None
design = Design.of(d, predictor)
X, K = design.matrix(d)[:, 1:], len(levels)
y = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _cumulative(X, y, K)
if abs(par[K - 1]) > 20:
return "separation"
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
inside = 0 < k < K
state = {"design": design.state(), "beta": [float(v) for v in par[K - 1 :]],
"threshold": float(theta[k - 1]) if inside else None,
"always": None if inside else float(k == 0)} # fmt: skip
return design, X, y, K, par, nll, state
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
d = rows(t, outcome, predictor)
out = {"model": "ordinal", "n": len(d), "levels": int(d[outcome].nunique())}
fitted = ordinal_fit(d, outcome, predictor, high)
if fitted is None or fitted == "separation":
return {**out, "reason": TOO_FEW if fitted is None else SEPARATION}
design, X, y, K, par, nll, state = fitted
with warnings.catch_warnings():
warnings.simplefilter("ignore")
profile = lambda v: -_cumulative(X, y, K, fixed=(0, v))[1] # noqa: E731
low, high_ = _interval(profile, par[K - 1], -nll, 0.1)
if not (np.isfinite(low) and np.isfinite(high_)):
return {**out, "reason": SEPARATION}
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
return _summary("ordinal", len(d), par[K - 1], low, high_, p, design, state, levels=K)
def probability(model: str, state: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
"""Each child's probability of the outcome under a fitted state, and the reference
child's (z = 0, the cohort's mean age, the commonest module)."""
X = Design.from_state(state["design"]).matrix(t)
if model == "firth":
return (expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"])),
float(expit(state["intercept"]))) # fmt: skip
if state["threshold"] is None:
always = state["always"]
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, always), always
return (1 - expit(state["threshold"] - X[:, 1:] @ np.asarray(state["beta"])),
float(1 - expit(state["threshold"]))) # fmt: skip