Files
models/models/tea/association.py
T

217 lines
10 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),
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).
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 hashlib
import numpy as np
import pandas as pd
from statsmodels.stats.multitest import multipletests
from core.tea import association as spec
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:
"""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
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:
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 _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 (Benjamini–Hochberg within
each biomarker, exploratory pairs apart): what the association is."""
if level == "auto":
level = "item" if has_items(cohort) else "domain"
tested, rows = spec.pairs(level), []
for pair in tested:
if pair["predictor"] not in cohort:
continue
d = cohort.copy()
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)
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(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 {"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 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]:
"""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": 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 check(fitted)["rows"]:
if r["principal"].get("odds_ratio") is None or r["predictor"] not in cohort:
continue
t = cohort
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
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": spec.outcome_code(r), "z": float(z),
"probability": round(float(p), 4),
"reference_probability": round(reference, 4)}) # fmt: skip
return out