diff --git a/models/tea/association.py b/models/tea/association.py index 4c4394b..69f473a 100644 --- a/models/tea/association.py +++ b/models/tea/association.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json import warnings from dataclasses import dataclass, field @@ -12,6 +13,8 @@ from scipy import optimize, stats from scipy.special import expit from core.tea import ADOS2_ITEMS +from core.tea.ados2 import algorithm_score +from core.tea.reasons import INSUFFICIENT_DATA from models.tea.eeg.spindles import ZONES ASSOCIATION_COLUMNS = ( @@ -43,6 +46,11 @@ SCORE_COLUMNS = ( "reference_probability", ) ADJUST = ("age_months", "ados_module") +ITEM_ALTERED = 2 +CSS_HIGH = 8 +MIN_EVENTS = 5 +Q_FAMILY = "biomarker" +CLIP_Z = 0 ITEMS = { 1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}), @@ -77,85 +85,87 @@ ITEMS = { ), } -ZONE_ITEMS = { - "frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16), - "frontal_right": (4, 5, 7, 14, 22), - "frontal_midline": (6, 11, 12, 13, 14), - "central": (21,), - "parietal": (6, 13, 20), - "temporal_left": (1, 16, 18, 19), - "temporal_right": (4, 5, 8), - "occipital": (4, 20), +SPIKE_GROUPS = { + "any": tuple(ZONES), + "left": ("frontal_left", "temporal_left"), + "right": ("frontal_right", "temporal_right"), + "central": ("central",), } SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal") RHYTHM_ITEMS = (20, 22) CSS = "CSS" -CSS_HIGH = 8 -ALTERED = 1 def item_code(n: int) -> str: return f"ados2_item_{n:02d}" +def outcome_code(pair: dict) -> str: + if pair["kind"] == "domain": + return pair["outcome"] + if pair["kind"] == "composite": + return "ados2_items_" + "_".join(f"{n:02d}" for n in pair["outcome"]) + return item_code(pair["outcome"]) + + +def outcome_items(pair: dict) -> list[int]: + if pair["kind"] == "domain": + return [] + return list(pair["outcome"]) if pair["kind"] == "composite" else [pair["outcome"]] + + +def _pair(biomarker: str, zone: str, predictor: str, kind: str, outcome) -> dict: + return { + "biomarker": biomarker, + "zone": zone, + "predictor": predictor, + "kind": kind, + "outcome": outcome, + } + + def pairs(level: str) -> list[dict]: - out = [] - for zone in ZONES: - outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)] + def spikes(zone, kind, outcome): + return _pair("spikes", zone, f"spikes_any_{zone}", kind, outcome) + + out = [spikes("any", "domain", CSS)] + if level == "item": out += [ - { - "biomarker": "spikes", - "zone": zone, - "predictor": f"z_spikes_{zone}", - "kind": k, - "outcome": o, - } - for k, o in outcomes + spikes("left", "composite", [1, 18]), + spikes("right", "composite", [4, 5, 7]), + spikes("central", "exploratory", 21), ] - out += [ - { - "biomarker": "spindles", - "zone": zone, - "predictor": f"z_spindles_{zone}", - "kind": "domain", - "outcome": CSS, - } - for zone in SPINDLE_ZONES - ] + out += [_pair("spindles", z, f"z_spindles_{z}", "domain", CSS) for z in SPINDLE_ZONES] rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)] out += [ - { - "biomarker": "posterior_rhythm", - "zone": "posterior", - "predictor": "z_posterior_rhythm", - "kind": k, - "outcome": o, - } - for k, o in rhythm + _pair("posterior_rhythm", "posterior", "z_posterior_rhythm", kind, outcome) + for kind, outcome in rhythm ] - out.append( - { - "biomarker": "gradient", - "zone": "global", - "predictor": "z_gradient", - "kind": "domain", - "outcome": CSS, - } - ) + out.append(_pair("gradient", "global", "z_gradient", "domain", CSS)) return out -def algorithm_score(v) -> pd.Series: - v = pd.to_numeric(pd.Series(v), errors="coerce") - return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2) +def spikes_any(features: dict) -> dict[str, float]: + minutes = features.get("minutes") or 0 + out = {} + for group, zones in SPIKE_GROUPS.items(): + rates = [features.get(f"electrode_{e}") for zone in zones for e in ZONES[zone]] + counts = [rate * minutes for rate in rates if rate is not None] + known = minutes > 0 and bool(counts) + out[f"spikes_any_{group}"] = float(any(n > 0 for n in counts)) if known else np.nan + return out def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series: column = ADOS2_ITEMS[n - 1] if "ados_module" not in cohort or column not in cohort: return pd.Series(np.nan, index=cohort.index) - return algorithm_score(cohort[column]).where(cohort["ados_module"].isin(ITEMS[n][2])) + scores = [ + algorithm_score(value, module, column) if module in ITEMS[n][2] else np.nan + for value, module in zip(cohort[column], cohort["ados_module"], strict=True) + ] + return pd.Series(scores, index=cohort.index, dtype=float) def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool: @@ -320,11 +330,25 @@ def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict: } +def _complete(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> pd.DataFrame: + return t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna() + + +def _firth_fits(d: pd.DataFrame, y: np.ndarray, predictor: str) -> bool: + return len(d) >= MIN_ROWS and 2 <= y.sum() <= len(y) - 2 and d[predictor].std() != 0 + + +def _firth_scoring(X, y, b) -> dict: + eta = X[:, 1:] @ b[1:] + flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50) + return {"beta": [float(v) for v in b[1:]], "intercept": float(flic)} + + def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict: - d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna() + d = _complete(t, outcome, predictor, adjust) 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: + if not _firth_fits(d, y, predictor): return {**out, "reason": "too few data or no variation"} design = Design.of(d, predictor, adjust) X = design.matrix(d) @@ -334,19 +358,19 @@ def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict: profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731 lo, hi = _interval(profile, b[1], pl, max(se, 0.05)) p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1)) - eta = X[:, 1:] @ b[1:] - flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50) - return _summary( - "firth", - len(d), - b[1], - lo, - hi, - p, - design, - {"beta": [float(v) for v in b[1:]], "intercept": float(flic)}, - events=int(y.sum()), - ) + state = _firth_scoring(X, y, b) + return _summary("firth", len(d), b[1], lo, hi, p, design, state, events=int(y.sum())) + + +def firth_state(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict | None: + d = _complete(t, outcome, predictor, adjust) + y = d[outcome].to_numpy(float) + if not _firth_fits(d, y, predictor): + return None + design = Design.of(d, predictor, adjust) + X = design.matrix(d) + b, _ = _fit_firth(X, y) + return {"design": design.to_dict(), **_firth_scoring(X, y, b)} def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray: @@ -383,42 +407,65 @@ def _fit_ordinal(X, yk, K, fixed=None): return None, float(optimize.minimize(f, start[idx], method="BFGS").fun) +def _ordinal_fits(d: pd.DataFrame, levels: np.ndarray, predictor: str) -> bool: + return len(d) >= MIN_ROWS and len(levels) >= 2 and d[predictor].std() != 0 + + +def _ordinal_data(d: pd.DataFrame, outcome: str, predictor: str, adjust, levels: np.ndarray): + design = Design.of(d, predictor, adjust) + return design, design.matrix(d)[:, 1:], np.searchsorted(levels, d[outcome].to_numpy()) + + +def _separated(beta: np.ndarray) -> bool: + return abs(beta[0]) > 20 + + +def _ordinal_scoring(par, levels: np.ndarray, high: float) -> dict: + K = len(levels) + theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) + k = int(np.searchsorted(levels, high)) + return { + "beta": [float(v) for v in par[K - 1 :]], + "threshold": float(theta[k - 1]) if 0 < k < K else None, + "always": None if 0 < k < K else float(k == 0), + } + + def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict: - d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna() + d = _complete(t, outcome, predictor, adjust) 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: + if not _ordinal_fits(d, levels, predictor): return {**out, "reason": "too few data or no variation"} - design = Design.of(d, predictor, adjust) - X = design.matrix(d)[:, 1:] + design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels) K = len(levels) - yk = np.searchsorted(levels, d[outcome].to_numpy()) with warnings.catch_warnings(): warnings.simplefilter("ignore") par, nll = _fit_ordinal(X, yk, K) beta = par[K - 1 :] - if abs(beta[0]) > 20: + if _separated(beta): return {**out, "reason": "does not converge (separation)"} profile = lambda v: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731 lo, hi = _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)) - return _summary( - "ordinal", - len(d), - beta[0], - lo, - hi, - p, - design, - { - "beta": [float(v) for v in beta], - "threshold": float(theta[k - 1]) if 0 < k < K else None, - "always": None if 0 < k < K else float(k == 0), - }, - levels=K, - ) + state = _ordinal_scoring(par, levels, high) + return _summary("ordinal", len(d), beta[0], lo, hi, p, design, state, levels=K) + + +def ordinal_state( + t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float +) -> dict | None: + d = _complete(t, outcome, predictor, adjust) + levels = np.sort(d[outcome].unique()) + if not _ordinal_fits(d, levels, predictor): + return None + design, X, yk = _ordinal_data(d, outcome, predictor, adjust, levels) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + par, _ = _fit_ordinal(X, yk, len(levels)) + if _separated(par[len(levels) - 1 :]): + return None + return {"design": design.to_dict(), **_ordinal_scoring(par, levels, high)} def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray: @@ -445,12 +492,45 @@ def bh(p) -> np.ndarray: return q -def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]: - if pair["kind"] == "item": - score = item_scores(cohort, pair["outcome"]) - return (score >= ALTERED).astype(float).where(score.notna()), score - css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce") - return (css >= CSS_HIGH).astype(float).where(css.notna()), css +def _digest(key) -> str: + return hashlib.sha256(str(key).encode()).hexdigest()[:16] + + +def _prepare(cohort: pd.DataFrame, settings: dict) -> pd.DataFrame: + d = cohort.copy() + clip = settings["clip_z"] + for column in d.columns: + if column.startswith(("z_", "spikes_any_")): + v = pd.to_numeric(d[column], errors="coerce").replace([np.inf, -np.inf], np.nan) + d[column] = v.clip(-clip, clip) if clip > 0 and column.startswith("z_") else v + return d + + +def _css(cohort: pd.DataFrame) -> pd.Series: + return pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce") + + +def _outcome(cohort: pd.DataFrame, pair: dict, settings: dict) -> tuple[pd.Series, pd.Series]: + if pair["kind"] == "domain": + css = _css(cohort) + return (css >= settings["css_high"]).astype(float).where(css.notna()), css + scores = pd.concat([item_scores(cohort, n) for n in outcome_items(pair)], axis=1) + complete = scores.notna().all(axis=1) + altered = (scores >= settings["item_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 _high(pair: dict, settings: dict) -> int: + if pair["kind"] == "composite": + return 1 + return settings["css_high" if pair["kind"] == "domain" else "item_altered"] + + +def _event(pair: dict, settings: dict) -> str: + if pair["kind"] == "composite": + return f"alguno >={settings['item_altered']}" + return f">={_high(pair, settings)}" def _guarded(fit, model: str, *args, **kwargs) -> dict: @@ -460,50 +540,117 @@ def _guarded(fit, model: str, *args, **kwargs) -> dict: return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"} -def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]: - p = pair["predictor"] - fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731 - if pair["kind"] == "item": - return fit_firth(), _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=ALTERED) - return _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=CSS_HIGH), fit_firth() +def _fit_pair(d: pd.DataFrame, pair: dict, settings: dict) -> dict: + predictor = pair["predictor"] + used = d[["_yes", predictor]].dropna() + events = int(used["_yes"].sum()) + without = len(used) - events + short = min(events, without) < settings["min_events"] + counted = short and pair["kind"] == "composite" + binary = _guarded(firth, "firth", d, "_yes", predictor, ADJUST) + graded = _guarded( + ordinal, "ordinal", d, "_level", predictor, ADJUST, high=_high(pair, settings) + ) + ordinal_first = pair["kind"] == "domain" or counted + principal, sensitivity = (graded, binary) if ordinal_first else (binary, graded) + if short and principal.get("odds_ratio") is not None: + note = ( + f"{INSUFFICIENT_DATA}{events} con evento y {without} sin evento " + f"(minimo {settings['min_events']})" + ) + if counted: + note += "; se usa el numero de reactivos alterados" + principal = {**principal, "reason": note} + return {**pair, "principal": principal, "sensitivity": sensitivity} -def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]: - if fit["model"] == "firth": - return firth_probability(fit["state"], t), firth_reference(fit["state"]) - return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"]) +def _q_values(rows: list[dict], settings: dict) -> np.ndarray: + tested = np.array([r["kind"] != "exploratory" for r in rows], bool) + families = np.array( + [r["biomarker"] if settings["q_family"] == "biomarker" else "all" for r in rows] + ) + p = np.array([r["principal"].get("p", np.nan) for r in rows], float) + q = np.full(len(rows), np.nan) + for family in dict.fromkeys(families[tested]): + chosen = tested & (families == family) + q[chosen] = bh(p[chosen]).round(5) + return q + + +def _state(model: str, d: pd.DataFrame, pair: dict, settings: dict) -> dict | None: + try: + if model == "firth": + return firth_state(d, "_yes", pair["predictor"], ADJUST) + return ordinal_state(d, "_level", pair["predictor"], ADJUST, _high(pair, settings)) + except (np.linalg.LinAlgError, ValueError): + return None + + +def _probability(model: str, state: dict, t: pd.DataFrame) -> np.ndarray: + return firth_probability(state, t) if model == "firth" else ordinal_probability(state, t) + + +def _reference(fit: dict) -> float: + reference = firth_reference if fit["model"] == "firth" else ordinal_reference + return reference(fit["state"]) + + +def _scores(t: pd.DataFrame, fitted: set[str], pair: dict, settings: dict) -> np.ndarray: + fit = pair["principal"] + probability = _probability(fit["model"], fit["state"], t) + train = t[t["key"].map(_digest).isin(fitted)] + child = t["child" if "child" in t else "key"] + for name in child[train.index].unique(): + own = (child == name).to_numpy() + state = _state(fit["model"], train[child[train.index] != name], pair, settings) + probability[own] = np.nan if state is None else _probability(fit["model"], state, t[own]) + return probability class Ados2Association: name = "ados2_association" - version = "0.1.0" + version = "0.4.0" impl = "modern" def __init__(self, level: str = "auto", fitted: dict | None = None): if level not in ("auto", "item", "domain"): raise ValueError(f"level must be auto, item or domain, not {level!r}") + if fitted is not None and not {"settings", "pairs"} <= fitted.keys(): + raise ValueError( + f"{self.name}: the saved model has no settings and pairs; retrain the association" + ) self.level = level self.fitted = fitted def fit(self, cohort: pd.DataFrame) -> Ados2Association: level = self.level if self.level != "auto" else ("item" if has_items(cohort) else "domain") + settings = { + "item_altered": ITEM_ALTERED, + "css_high": CSS_HIGH, + "min_events": MIN_EVENTS, + "q_family": Q_FAMILY, + "clip_z": CLIP_Z, + } + prepared = _prepare(cohort, settings) + tested = pairs(level) rows = [] - for pair in pairs(level): - if pair["predictor"] not in cohort: + for pair in tested: + if pair["predictor"] not in prepared: continue - d = cohort.copy() - d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan) - d["_yes"], d["_level"] = _outcome(cohort, pair) - principal, sensitivity = _models(d, pair) - rows.append({**pair, "principal": principal, "sensitivity": sensitivity}) - q = np.full(len(rows), np.nan) - biomarkers = np.array([r["biomarker"] for r in rows]) - p = np.array([r["principal"].get("p", np.nan) for r in rows], float) - for b in dict.fromkeys(biomarkers): - q[biomarkers == b] = bh(p[biomarkers == b]).round(5) - for r, v in zip(rows, q, strict=True): + d = prepared.copy() + d["_yes"], d["_level"] = _outcome(d, pair, settings) + rows.append(_fit_pair(d, pair, settings)) + for r, v in zip(rows, _q_values(rows, settings), strict=True): r["q"] = None if np.isnan(v) else float(v) - self.fitted = {"level": level, "n": len(cohort), "rows": rows} + self.fitted = { + "level": level, + "n": len(cohort), + "rows": rows, + "settings": settings, + "pairs": tested, + "css_sources": {"computed": int(_css(cohort).notna().sum())}, + "keys": sorted(_digest(k) for k in cohort.get("key", [])), + } return self def _rows(self) -> list[dict]: @@ -515,16 +662,15 @@ class Ados2Association: out = [] for r in self._rows(): f, s = r["principal"], r["sensitivity"] - kind = r["kind"] ors, sens = f.get("odds_ratio"), s.get("odds_ratio") out.append( { "biomarker": r["biomarker"], "zone": r["zone"], - "kind": kind, + "kind": r["kind"], "outcome": r["outcome"], - "outcome_code": item_code(r["outcome"]) if kind == "item" else CSS, - "event": f">={ALTERED if kind == 'item' else CSS_HIGH}", + "outcome_code": outcome_code(r), + "event": _event(r, self.fitted["settings"]), "model": f["model"], "n": f["n"], "odds_ratio": ors, @@ -544,20 +690,24 @@ class Ados2Association: ) return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS)) - def score(self, cohort: pd.DataFrame) -> pd.DataFrame: + def score(self, cohort: pd.DataFrame, leave_one_out: bool = True) -> pd.DataFrame: + rows = self._rows() + settings = self.fitted["settings"] + prepared = _prepare(cohort, settings) + fitted = set(self.fitted["keys"]) if leave_one_out else set() parts = [] - for r in self._rows(): - f = r["principal"] - if f.get("odds_ratio") is None or r["predictor"] not in cohort: + for r in rows: + f, predictor = r["principal"], r["predictor"] + if f.get("odds_ratio") is None or predictor not in prepared: continue - t = cohort - if r["kind"] == "item": - modules = set(ITEMS[r["outcome"]][2]) - t = cohort[cohort["ados_module"].isin(modules)] - t = t[t[r["predictor"]].notna()] + t = prepared + for n in outcome_items(r): + t = t[t["ados_module"].isin(ITEMS[n][2])] + t = t[t[predictor].notna()].copy() if not len(t): continue - prob, ref = _probability(f, t) + t["_yes"], t["_level"] = _outcome(t, r, settings) + prob = _scores(t, fitted, r, settings) kept = np.isfinite(prob) parts.append( pd.DataFrame( @@ -565,10 +715,10 @@ class Ados2Association: "key": t["key"].to_numpy()[kept], "biomarker": r["biomarker"], "zone": r["zone"], - "outcome_code": item_code(r["outcome"]) if r["kind"] == "item" else CSS, - "z": t[r["predictor"]].to_numpy(float)[kept], + "outcome_code": outcome_code(r), + "z": pd.to_numeric(cohort.loc[t.index, predictor]).to_numpy(float)[kept], "probability": prob[kept].round(4), - "reference_probability": round(ref, 4), + "reference_probability": round(_reference(f), 4), } ) ) diff --git a/models/tea/jobs.py b/models/tea/jobs.py index 3b1d038..deadc15 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -135,6 +135,7 @@ def score_curves() -> dict[str, int | None]: def cohort() -> tuple[pd.DataFrame, pd.DataFrame]: columns = [ "key", + "child", "person_id", "study_date", "edf", @@ -143,6 +144,7 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]: "css", "language_level", *ADOS2_ITEMS, + *(f"spikes_any_{group}" for group in association.SPIKE_GROUPS), ] biomarker = {metric: name for name, metric in ASSOCIATION_BIOMARKERS.items()} studies, scores = eeg.association_cohort_rows() @@ -151,10 +153,13 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]: row["evaluation_date"] = as_day(row["evaluation_date"]) if row["evaluation_date"] else None birth = as_day(row["birth_date"]) if row["evaluation_date"] and row["birth_date"] else None scored = ados2.score(row, birth) + features = json.loads(row["features"] or "{}") records.append( { **row, + **association.spikes_any(features.get("eeg-spikes", {})), "key": eeg_study_id(row["person_id"], row["study_date"]), + "child": row["person_id"], "ados_module": row["module"], "css": scored.css if scored else None, } @@ -165,7 +170,9 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]: if row["edf"] not in edfs: continue name = biomarker[row["metric"]] - if name in ("spikes", "spindles"): + if name == "spikes": + continue + if name == "spindles": if row["part"] != "zones": continue predictor = f"z_{name}_{row['site']}" @@ -180,7 +187,7 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]: scored = scored.sort_values(["person_id", "study_date", "key"], na_position="last").reset_index( drop=True ) - predictors = [c for c in scored.columns if c.startswith("z_")] + predictors = [c for c in scored.columns if c.startswith(("z_", "spikes_any_"))] fit = ( scored[scored[predictors].notna().any(axis=1)] .drop_duplicates("person_id") @@ -218,7 +225,8 @@ def train_association(as_of: date | None = None) -> int | None: estimator.fit(fit) pairs = estimator.associations() level = estimator.fitted["level"] - forest = ["biomarker", "zone", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"] + forest = ["biomarker", "zone", "kind", "outcome_code", "event", "n"] + forest += ["odds_ratio", "ci_low", "ci_high", "q", "reason"] reports = { "technical_validation": { "model": ASSOCIATION, diff --git a/tests/test_tea_association.py b/tests/test_tea_association.py index 77130da..056f733 100644 --- a/tests/test_tea_association.py +++ b/tests/test_tea_association.py @@ -1,9 +1,14 @@ +import json + import numpy as np import pandas as pd +import pytest from core.tea import ADOS2_ITEMS from models.tea import association as a +KEYS = ["key", "biomarker", "zone", "outcome_code"] + def test_firth_on_separation(): frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6}) @@ -21,21 +26,244 @@ def test_ordinal_on_monotone_trend(): assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1 -def test_pairs_and_item_availability(): - assert len(a.pairs("item")) == 41 - assert len(a.pairs("domain")) == 15 - assert ADOS2_ITEMS == [ - "vocalization_directed", "pointing", "gestures", "unusual_eye_contact", - "facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name", - "ignoring", "requesting", "showing", "joint_attention_initiation", - "joint_attention_response", "social_overtures_quality", "social_overtures_caregiver", - "reciprocal_communication", "rapport_quality", "intonation", "stereotyped_language", - "unusual_sensory_interest", "hand_finger_mannerisms", "repetitive_interests", - ] # fmt: skip +def test_pairs_by_level(): + item = a.pairs("item") + spikes = [p for p in item if p["biomarker"] == "spikes"] + assert [(p["zone"], p["kind"], a.outcome_code(p)) for p in spikes] == [ + ("any", "domain", "CSS"), + ("left", "composite", "ados2_items_01_18"), + ("right", "composite", "ados2_items_04_05_07"), + ("central", "exploratory", "ados2_item_21"), + ] + assert len(item) == 12 + domain = a.pairs("domain") + assert [p["zone"] for p in domain if p["biomarker"] == "spikes"] == ["any"] + assert len(domain) == 8 + + +def test_item_scores_follow_the_algorithm_and_the_module(): + assert ADOS2_ITEMS[0] == "vocalization_directed" + assert ADOS2_ITEMS[20] == "hand_finger_mannerisms" frame = pd.DataFrame( { "ados_module": ["toddler", "module_1", "module_2", "module_3"], "vocalization_directed": [3, 7, 1, 1], + "unusual_eye_contact": [1, 1, 1, 1], } ) np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan]) + np.testing.assert_allclose(a.item_scores(frame, 4), [2, 1, 1, np.nan]) + + +def test_spikes_any_from_the_electrode_rates(): + rates = {f"electrode_{e}": 0.0 for zone in a.ZONES.values() for e in zone} + found = a.spikes_any({**rates, "minutes": 20.0, "electrode_T3": 0.05}) + assert found == { + "spikes_any_any": 1, + "spikes_any_left": 1, + "spikes_any_right": 0, + "spikes_any_central": 0, + } + unmeasured = {**rates, "minutes": 20.0, "electrode_C3": None, "electrode_C4": None} + assert a.spikes_any(unmeasured)["spikes_any_central"] == 0 + assert np.isnan(a.spikes_any({**unmeasured, "electrode_Cz": None})["spikes_any_central"]) + for features in ({**rates, "minutes": 0.0}, {**rates, "minutes": None}, {}): + assert all(np.isnan(v) for v in a.spikes_any(features).values()) + + +def _domain_cohort(n_toddler=60, n_other=8, seed=3): + rng = np.random.default_rng(seed) + n = n_toddler + n_other + z = rng.normal(0, 1.2, n) + return pd.DataFrame( + { + "key": [f"k{i}" for i in range(n)], + "age_months": rng.uniform(16, 36, n).round(1), + "ados_module": ["toddler"] * n_toddler + + ["module_1"] * (n_other // 2) + + ["module_2"] * (n_other - n_other // 2), + "css": np.clip(np.round(6 + 1.3 * z + rng.normal(0, 1.2, n)), 1, 10), + "z_gradient": z, + "z_spindles_central": rng.normal(0, 1, n), + "spikes_any_any": (z > 0).astype(float), + } + ) + + +@pytest.fixture(scope="module") +def fitted(): + cohort = _domain_cohort() + return cohort, a.Ados2Association(level="domain").fit(cohort) + + +def test_one_css_family_for_every_module(fitted): + _, model = fitted + found = model.associations() + gradient = found[found.biomarker == "gradient"] + assert list(gradient.outcome_code) == ["CSS"] + assert gradient.n.iloc[0] == 68 + assert gradient.odds_ratio.iloc[0] > 1 + assert gradient.model.iloc[0] == "ordinal" + assert set(found.event) == {">=8"} + assert found[found.biomarker == "spikes"].q.notna().all() + assert model.fitted["css_sources"] == {"computed": 68} + assert model.fitted["settings"] == { + "item_altered": 2, + "css_high": 8, + "min_events": 5, + "q_family": "biomarker", + "clip_z": 0, + } + assert model.fitted["pairs"] == a.pairs("domain") + + +def test_few_events_are_fitted_and_flagged(): + cohort = _domain_cohort() + cohort["css"] = np.where(cohort.index < 3, 9.0, 4.0 + cohort.index % 3) + found = a.Ados2Association(level="domain").fit(cohort).associations() + gradient = found[found.biomarker == "gradient"].iloc[0] + assert np.isfinite(gradient.odds_ratio) + assert gradient.reason == "datos insuficientes: 3 con evento y 65 sin evento (minimo 5)" + + +def test_leave_one_out(fitted): + cohort, model = fitted + both = model.score(cohort).merge( + model.score(cohort, leave_one_out=False), on=KEYS, suffixes=("_out", "_in") + ) + assert len(both) and np.isfinite(both.probability_out).all() + assert (both.probability_out != both.probability_in).any() + + +def test_a_new_child_gets_the_full_model(fitted): + cohort, model = fitted + new = cohort.iloc[[0]].assign(key="new") + left_out, full = model.score(new), model.score(new, leave_one_out=False) + assert len(full) + np.testing.assert_allclose(left_out.probability, full.probability) + + +def test_every_study_of_a_fitted_child_is_scored_without_the_child(): + cohort = _domain_cohort().assign(child=lambda t: t.key) + model = a.Ados2Association(level="domain").fit(cohort) + again = cohort.iloc[[0]].assign(key="later") + scored = model.score(pd.concat([cohort, again], ignore_index=True)) + first, later = ( + scored[scored.key == key].set_index(["biomarker", "zone"]).probability + for key in ("k0", "later") + ) + pd.testing.assert_series_equal(first, later) + alone = model.score(again).set_index(["biomarker", "zone"]).probability + assert (later != alone).any() + + +def test_the_saved_model_lists_no_keys(fitted, tmp_path): + cohort, model = fitted + model.save(tmp_path) + text = (tmp_path / "association.json").read_text() + assert not any(f'"{key}"' in text for key in cohort.key) + keys = json.loads(text)["fitted"]["keys"] + assert len(keys) == len(cohort) + assert all(len(key) == 16 for key in keys) + loaded = a.Ados2Association.load(tmp_path) + pd.testing.assert_frame_equal(loaded.score(cohort), model.score(cohort)) + + +@pytest.mark.parametrize("missing", ["settings", "pairs"]) +def test_an_old_saved_model_is_refused(fitted, tmp_path, missing): + _, model = fitted + old = {k: v for k, v in model.fitted.items() if k != missing} + (tmp_path / "association.json").write_text(json.dumps({"level": "domain", "fitted": old})) + with pytest.raises(ValueError, match="retrain"): + a.Ados2Association.load(tmp_path) + with pytest.raises(ValueError, match="retrain"): + a.Model(old).predict(None, pd.DataFrame()) + + +def test_clipping_leaves_the_scored_z(monkeypatch): + monkeypatch.setattr(a, "CLIP_Z", 3) + cohort = _domain_cohort() + cohort.loc[0, "z_gradient"] = 9.0 + model = a.Ados2Association(level="domain").fit(cohort) + scored = model.score(cohort) + assert scored.loc[(scored.key == "k0") & (scored.biomarker == "gradient"), "z"].item() == 9.0 + + +def _item_cohort(n=60, seed=5): + rng = np.random.default_rng(seed) + spikes = (rng.random(n) < 0.5).astype(float) + cohort = pd.DataFrame( + { + "key": [f"k{i}" for i in range(n)], + "age_months": rng.uniform(16, 36, n).round(1), + "ados_module": ["toddler", "module_1", "module_2"] * (n // 3), + "css": rng.integers(4, 11, n).astype(float), + "spikes_any_any": spikes, + "spikes_any_left": spikes, + "spikes_any_right": spikes, + "spikes_any_central": spikes, + } + ) + for item in (1, 4, 5, 7, 18, 21): + cohort[ADOS2_ITEMS[item - 1]] = rng.choice([0, 1, 2], n, p=[0.5, 0.25, 0.25]) + return cohort + + +def _spike_rows(model): + found = model.associations() + return found[found.biomarker == "spikes"].set_index("zone") + + +def test_composites_and_the_exploratory_pair(): + cohort = _item_cohort() + model = a.Ados2Association().fit(cohort) + found = _spike_rows(model) + assert list(found.index) == ["any", "left", "right", "central"] + assert found.n.to_dict() == {"any": 60, "left": 40, "right": 60, "central": 60} + assert found.event.to_dict() == { + "any": ">=8", + "left": "alguno >=2", + "right": "alguno >=2", + "central": ">=2", + } + assert list(found.loc[["left", "right", "central"]].model) == ["firth"] * 3 + assert list(found.loc[["left", "right", "central"]].sens_model) == ["ordinal"] * 3 + assert found.outcome["left"] == [1, 18] + assert found.kind["central"] == "exploratory" + assert np.isfinite(found.odds_ratio["central"]) + assert np.isnan(found.q["central"]) + tested = found.loc[["any", "left", "right"]] + np.testing.assert_allclose(tested.q.to_numpy(float), a.bh(tested.p).round(5)) + scored = model.score(cohort) + left = scored[scored.outcome_code == "ados2_items_01_18"] + assert set(cohort.ados_module[cohort.key.isin(left.key)]) == {"toddler", "module_1"} + assert set(scored.z[scored.biomarker == "spikes"]) == {0.0, 1.0} + + +def test_a_composite_event_is_any_of_its_items_altered(): + cohort = _item_cohort() + scores = pd.concat([a.item_scores(cohort, n) for n in (4, 5, 7)], axis=1) + pair = next(p for p in a.pairs("item") if p["zone"] == "right") + settings = a.Ados2Association().fit(cohort).fitted["settings"] + event, count = a._outcome(cohort, pair, settings) + np.testing.assert_allclose(event, (scores == 2).any(axis=1)) + np.testing.assert_allclose(count, (scores == 2).sum(axis=1)) + + +def test_a_composite_with_a_small_group_counts_the_altered_items(): + cohort = _item_cohort() + rng = np.random.default_rng(11) + cohort["facial_expressions"] = 2 + cohort["unusual_eye_contact"] = rng.choice([0, 2], len(cohort)) + cohort["shared_enjoyment"] = rng.choice([0, 2], len(cohort)) + model = a.Ados2Association().fit(cohort) + found = _spike_rows(model).loc["right"] + assert (found.model, found.sens_model, found.event) == ("ordinal", "firth", "alguno >=2") + assert found.reason == ( + "datos insuficientes: 60 con evento y 0 sin evento (minimo 5); " + "se usa el numero de reactivos alterados" + ) + scored = model.score(cohort) + right = scored[scored.zone == "right"] + assert (right.probability == 1).all() + assert (right.reference_probability == 1).all() diff --git a/tests/test_tea_job.py b/tests/test_tea_job.py index 1a0f9d8..5993704 100644 --- a/tests/test_tea_job.py +++ b/tests/test_tea_job.py @@ -1,3 +1,4 @@ +import json from datetime import date from types import SimpleNamespace @@ -6,6 +7,7 @@ import pandas as pd import pytest from pydantic import ValidationError +from core.tea import ADOS2_ITEMS from models.definitions import ScopeConfig, after_ingest from models.tea import jobs from models.tea.eeg import curves @@ -45,6 +47,38 @@ def test_the_domain_routine_scores_the_curves_then_relates_the_association(): assert JOBS.routine() == [*MODELS, ASSOCIATION] +def test_the_association_cohort_takes_spikes_as_yes_or_no(monkeypatch): + def study(child, day, features): + return { + **dict.fromkeys(ADOS2_ITEMS), + "person_id": child, + "study_date": day, + "edf": f"{child}-{day}", + "age_months": 24.0, + "module": "toddler", + "evaluation_date": None, + "birth_date": None, + "language_level": None, + "features": json.dumps(features), + } + + spikes = {"eeg-spikes": {"minutes": 10.0, "electrode_F8": 0.2, "electrode_C3": 0.0}} + studies = [study("one", "2025-01-01", spikes), study("two", "2025-01-01", {})] + scores = [ + {"edf": "one-2025-01-01", "metric": metric, "part": "zones", "site": "central", "z": 1.5} + for metric in ("paroxysmal_spikes", "spindles") + ] + monkeypatch.setattr(eeg, "association_cohort_rows", lambda: (studies, scores)) + fit, scored = jobs.cohort() + assert list(fit.child) == ["one"] + assert list(scored.child) == ["one", "two"] + assert [c for c in scored.columns if c.startswith("z_")] == ["z_spindles_central"] + found = fit.iloc[0] + assert (found.spikes_any_any, found.spikes_any_right, found.spikes_any_central) == (1, 1, 0) + assert pd.isna(found.spikes_any_left) + assert scored.iloc[1].filter(like="spikes_any_").isna().all() + + def test_after_ingest_requests_a_run_only_with_pending_eegs(): skip = after_ingest("r1", lambda: False) assert isinstance(skip, dg.SkipReason)