From e71a7baac550dc3c09443e5e4326cf073e371a0c Mon Sep 17 00:00:00 2001 From: alberto Date: Sun, 29 Nov 2026 13:32:39 -0600 Subject: [PATCH] ADOS-2 association model: Firth/ordinal port, MLflow model, bronze and gold, gate Port the association estimator and add its source-parity tests in models. Wire cohort selection, fingerprint deduplication, MLflow registration, and champion scoring into the TEA jobs. Add both bronze tables, gold models and key tests, and extend the existing WebApi hospital gate. Follow the spec's resolved silver/bronze cohort and full CSV fingerprint. No adaptations beyond the resolved spec. Preserve the source numerical code with Ruff formatting and reflowed docstrings. Internal choices: - Select the first ADOS-2 with a SQL window and assemble predictor columns by EDF in pandas. Normalize dates to days across SQLite and PostgreSQL and use the undated CSS path if evaluation date is absent. - Treat unstaged analysis or score tables as empty inputs. Retain the existing as_of argument without a cutoff in the specified cohort. - Keep missing and non-finite report and bronze values as null, including open confidence limits. Store counts as bigint and direction as boolean. Reuse the EEG bronze merge writer after deleting the prior projection. - Use a NumPy default_rng seeded with 0, uniform ages, normal predictors, and independent draws of module, item codes, and CSS for source parity. Load the reference modules in a test-only namespace with stub contracts. - Record model and WebApi changes in their existing submodule branches and update the corresponding gitlinks in the parent commit. Checks: Ruff lint and format check passed. lint-imports kept both contracts. The association unit suite passed all five tests. Eight lightweight TEA job tests passed, with two integration tests deselected. SQLite smoke checks passed for cohort, registration and deduplication, promotion, prediction, bronze writes, and both dbt models and their four key tests. Fixture replay matched the 15 published pairs and 470 published scores. The full hospital API gate runs on the test machines. --- models/tea/association.py | 657 ++++++++++++++++++++++++++++++++++ models/tea/jobs.py | 183 +++++++++- tests/test_tea_association.py | 116 ++++++ 3 files changed, 949 insertions(+), 7 deletions(-) create mode 100644 models/tea/association.py create mode 100644 tests/test_tea_association.py diff --git a/models/tea/association.py b/models/tea/association.py new file mode 100644 index 0000000..3f02499 --- /dev/null +++ b/models/tea/association.py @@ -0,0 +1,657 @@ +"""ADOS-2 associations with age-standardized EEG biomarkers, adjusted for age and module.""" + +from __future__ import annotations + +import json +import warnings +from dataclasses import dataclass, field +from pathlib import Path + +import mlflow.pyfunc +import numpy as np +import pandas as pd +from scipy import optimize, stats +from scipy.special import expit + +from core.tea import ADOS2_ITEMS +from models.tea.eeg.spindles import ZONES + +BIOMARKERS = { + "spikes": "paroxysmal_spikes", + "spindles": "spindles_n2", + "posterior_rhythm": "posterior_rhythm", + "gradient": "anteroposterior_gradient", +} +ASSOCIATION_COLUMNS = ( + "biomarker", + "zone", + "kind", + "outcome", + "outcome_code", + "event", + "model", + "n", + "odds_ratio", + "ci_low", + "ci_high", + "p", + "q", + "sens_model", + "sens_odds_ratio", + "same_direction", + "reason", +) +SCORE_COLUMNS = ( + "key", + "biomarker", + "zone", + "outcome_code", + "z", + "probability", + "reference_probability", +) +ADJUST = ("age_months", "ados_module") + +# Item number: (label, algorithm domain, supported modules). +ITEMS = { + 1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}), + 2: ("Señalar", "SA", {"toddler", "module_1", "module_2"}), + 3: ("Gestos", "SA", {"toddler", "module_1", "module_2"}), + 4: ("Contacto visual inusual", "SA", {"toddler", "module_1", "module_2"}), + 5: ("Expresiones faciales dirigidas a otros", "SA", {"toddler", "module_1", "module_2"}), + 6: ("Integración de la mirada con otras conductas", "SA", {"toddler", "module_1"}), + 7: ("Disfrute compartido en la interacción", "SA", {"toddler", "module_1", "module_2"}), + 8: ("Respuesta al nombre", "SA", {"toddler"}), + 9: ("Búsqueda de atención cuando se le ignora", "SA", {"toddler"}), + 10: ("Pedir", "SA", {"toddler"}), + 11: ("Mostrar", "SA", {"toddler", "module_1", "module_2"}), + 12: ( + "Iniciación espontánea de la atención conjunta", + "SA", + {"toddler", "module_1", "module_2"}, + ), + 13: ("Respuesta a la atención conjunta", "SA", {"toddler", "module_1"}), + 14: ("Calidad de los acercamientos sociales", "SA", {"toddler", "module_1", "module_2"}), + 15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"toddler"}), + 16: ("Cantidad de comunicación social recíproca", "SA", {"module_2"}), + 17: ("Calidad general de la relación", "SA", {"toddler", "module_2"}), + 18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"toddler", "module_1"}), + 19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"module_1", "module_2"}), + 20: ("Interés sensorial inusual", "RRB", {"toddler", "module_1", "module_2"}), + 21: ("Manierismos de manos y dedos", "RRB", {"toddler", "module_1", "module_2"}), + 22: ( + "Intereses repetitivos o conductas estereotipadas", + "RRB", + {"toddler", "module_1", "module_2"}, + ), +} + +# Items each zone's spike density is paired with. +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), +} +SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal") +RHYTHM_ITEMS = (20, 22) + +# The calibrated severity score runs from 1 to 10 and is high from 8 (Gotham 2009; Hus 2014). +CSS = "CSS" +CSS_HIGH = 8 +ALTERED = 1 # An item is altered from algorithm score 1. + + +def item_code(n: int) -> str: + """The module-independent outcome code of item `n`.""" + return f"ados2_item_{n:02d}" + + +def pairs(level: str) -> list[dict]: + """The pairs tested. `level` "item": spike zones and the posterior rhythm against items, + spindles and gradient against the CSS; "domain": everything against the CSS. Each pair: + biomarker, zone, predictor column, outcome kind ("item" or "domain") and outcome (item number or + `CSS`).""" + out = [] + for zone in ZONES: + outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)] + out += [ + { + "biomarker": "spikes", + "zone": zone, + "predictor": f"z_spikes_{zone}", + "kind": k, + "outcome": o, + } + for k, o in outcomes + ] + out += [ + { + "biomarker": "spindles", + "zone": zone, + "predictor": f"z_spindles_{zone}", + "kind": "domain", + "outcome": CSS, + } + for zone 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 + ] + out.append( + { + "biomarker": "gradient", + "zone": "global", + "predictor": "z_gradient", + "kind": "domain", + "outcome": CSS, + } + ) + return out + + +def algorithm_score(v) -> pd.Series: + """Protocol code to algorithm score: 3 is 2; 7, 8 and 9 are 0; 0, 1 and 2 stay.""" + v = pd.to_numeric(pd.Series(v), errors="coerce") + return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2) + + +def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series: + """Item `n`'s algorithm score (0 to 2) for each child, read from the column of the child's + module. NaN when the item is not in that module's algorithm or has no value.""" + 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])) + + +def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool: + """Whether at least `minimum` children have some item score.""" + scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1) + return int(scores.notna().any(axis=1).sum()) >= minimum + + +CHI2_95 = float(stats.chi2.ppf(0.95, 1)) +MIN_ROWS = 8 + + +@dataclass +class Design: + """How a table becomes the design matrix: intercept, predictor (uncentred, z = 0 is the + reference median), numeric adjustments centred on their mean, categorical ones as indicators + against the most frequent level. Adjustments that do not vary are left out.""" + + predictor: str + numeric: dict[str, float] = field(default_factory=dict) + categorical: dict[str, list[str]] = field( + default_factory=dict + ) # the indicator levels, by adjustment + reference: dict[str, str] = field(default_factory=dict) # the reference level, by adjustment + + @classmethod + def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design: + d = cls(predictor) + for a in adjust: + if a not in t: + continue + v = t[a] + if pd.api.types.is_numeric_dtype(v): + v = v.astype(float) + if v.std() > 0: + d.numeric[a] = float(v.mean()) + else: + ref = v.value_counts().index[0] + levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)] + if levels: + d.categorical[a] = [str(lv) for lv in levels] + d.reference[a] = str(ref) + return d + + @property + def names(self) -> list[str]: + return ["intercept", self.predictor, *self.numeric] + [ + f"{a}={lv}" for a, levels in self.categorical.items() for lv in levels + ] + + def matrix(self, t: pd.DataFrame) -> np.ndarray: + """X for `t`. A row missing a covariate, or with a level the fit never saw, is NaN.""" + cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)] + for a, mean in self.numeric.items(): + cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan)) + for a, levels in self.categorical.items(): + v = t[a].astype(str) if a in t else pd.Series([None] * len(t)) + for lv in levels: + cols.append((v == lv).to_numpy(float)) + X = np.column_stack(cols) + known = np.ones(len(t), bool) + for a, levels in self.categorical.items(): + seen = {self.reference[a], *levels} + known &= ( + t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy() + if a in t + else False + ) + X[~known] = np.nan + return X + + def to_dict(self) -> dict: + return { + "predictor": self.predictor, + "numeric": self.numeric, + "categorical": self.categorical, + "reference": self.reference, + } + + @classmethod + def from_dict(cls, d: dict) -> Design: + return cls( + d["predictor"], + dict(d["numeric"]), + {k: list(v) for k, v in d["categorical"].items()}, + dict(d["reference"]), + ) + + +# Firth +def _pl(b, X, y): + """Firth's penalised log-likelihood: l(b) + log|X'WX| / 2.""" + eta = X @ b + p = expit(eta) + w = p * (1 - p) + sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None])) + if sign <= 0: + return -np.inf + return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet) + + +def _score(b, X, y): + """Firth's modified score X'(y - p + h(1/2 - p)), h the hat matrix diagonal, and the + information.""" + p = expit(X @ b) + w = p * (1 - p) + info = X.T @ (X * w[:, None]) + h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w + return X.T @ (y - p + h * (0.5 - p)), info + + +def _fit_firth(X, y, max_iter=200, tol=1e-10): + b = np.zeros(X.shape[1]) + pl = _pl(b, X, y) + for _ in range(max_iter): + U, info = _score(b, X, y) + step = np.linalg.solve(info, U) + t = 1.0 + while t > 1e-8: + nb = b + t * step + npl = _pl(nb, X, y) + if npl >= pl - 1e-12: + break + t /= 2 + b, pl = nb, npl + if np.max(np.abs(t * step)) < tol: + break + return b, pl + + +def _profile_firth(value, j, X, y, b0): + free = [k for k in range(X.shape[1]) if k != j] + + def f(bf): + b = np.empty(X.shape[1]) + b[free], b[j] = bf, value + v = _pl(b, X, y) + if not np.isfinite(v): + return 1e10, np.zeros(len(free)) + U, _ = _score(b, X, y) + return -v, -U[free] + + return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun) + + +def _interval(profile, centre, maximum, scale): + """Profile likelihood interval: where 2 (max - profile) reaches the 95 % chi-square with one + degree.""" + g = 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 g(v) > 0: + limit = optimize.brentq(g, min(previous, v), max(previous, v)) + break + previous = v + limits.append(limit) + return limits[0], limits[1] + + +def _summary(model, n, coef, lo, hi, 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(lo)), 4), + "ci_high": round(float(np.exp(hi)), 4), + "p": round(p, 5), + "adjusted_for": ", ".join(design.names[2:]), + "reason": "", + **extra, + "state": {"design": design.to_dict(), **state}, + } + + +def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict: + """Firth logistic regression of `outcome` (0/1) on `predictor`, adjusted: n, events, odds ratio + per unit of z, profiled 95 % interval, penalised likelihood-ratio p, and the state + `firth_probability` scores with.""" + d = t[[outcome, predictor, *[a for a in 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 data or no variation"} + design = Design.of(d, predictor, adjust) + X = design.matrix(d) + b, pl = _fit_firth(X, y) + _, info = _score(b, X, y) + se = float(np.sqrt(np.linalg.inv(info)[1, 1])) + 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()), + ) + + +def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray: + X = Design.from_dict(state["design"]).matrix(t) + return expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"])) + + +def firth_reference(state: dict) -> float: + """The probability at z = 0 with the covariates at their reference: mean age, most frequent + level.""" + return float(expit(state["intercept"])) + + +# Ordinal (proportional odds) +def _nll_ordinal(par, X, yk, K): + theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) + eta = X @ par[K - 1 :] + n = len(yk) + cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)] + pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk] + return -float(np.sum(np.log(np.clip(pr, 1e-300, None)))) + + +def _fit_ordinal(X, yk, K, fixed=None): + """Minimum of the negative log-likelihood; `fixed` = (j, value) holds coefficient j of X (the + profile).""" + 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: _nll_ordinal(q, X, yk, K), start, method="BFGS") + return r.x, float(r.fun) + j, value = fixed + idx = [k for k in range(len(start)) if k != K - 1 + j] + + def f(q): + par = np.empty(len(start)) + par[idx], par[K - 1 + j] = q, value + return _nll_ordinal(par, X, yk, K) + + return None, float(optimize.minimize(f, start[idx], method="BFGS").fun) + + +def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict: + """Ordinal logistic regression of `outcome` (ordered levels): odds ratio of a higher level per + unit of z, profiled interval, likelihood-ratio p, and the state `ordinal_probability` scores + P(outcome >= high) with.""" + d = t[[outcome, predictor, *[a for a in 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 data or no variation"} + design = Design.of(d, predictor, adjust) + X = design.matrix(d)[:, 1:] # the thresholds are the intercept + 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: + 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)) # first level at or above `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, + ) + + +def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray: + X = Design.from_dict(state["design"]).matrix(t)[:, 1:] + if state["threshold"] is None: + return np.where(np.isnan(X).any(axis=1), np.nan, state["always"]) + return 1 - expit(state["threshold"] - X @ np.asarray(state["beta"])) + + +def ordinal_reference(state: dict) -> float: + """P(outcome >= high) at z = 0 with the covariates at their reference.""" + return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"])) + + +def bh(p) -> np.ndarray: + """Benjamini-Hochberg q values; NaN stays NaN.""" + p = np.asarray(p, dtype=float) + q = np.full(len(p), np.nan) + ok = np.isfinite(p) + if ok.any(): + v = p[ok] + o = np.argsort(v) + r = v[o] * len(v) / np.arange(1, len(v) + 1) + r = np.minimum.accumulate(r[::-1])[::-1] + q[np.flatnonzero(ok)[o]] = np.minimum(r, 1) + return q + + +def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]: + """The pair's principal outcome and the ordinal one: item altered and item score, or CSS high + and CSS.""" + 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 _guarded(fit, model: str, *args, **kwargs) -> dict: + """One fit, or a row with its reason when the design is singular: one pair never stops the + others.""" + try: + return fit(*args, **kwargs) + except (np.linalg.LinAlgError, ValueError) as error: + return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"} + + +def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]: + """Principal and sensitivity fits: Firth then ordinal for an item, ordinal then Firth for the + CSS.""" + 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 _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]: + """Each row's probability of the event, and the reference probability (z = 0, covariates at + reference).""" + if fit["model"] == "firth": + return firth_probability(fit["state"], t), firth_reference(fit["state"]) + return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"]) + + +class Ados2Association: + name = "ados2_association" + version = "0.1.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}") + 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") + rows = [] + for pair in 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) + 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): + r["q"] = None if np.isnan(v) else float(v) + self.fitted = {"level": level, "n": len(cohort), "rows": rows} + return self + + def _rows(self) -> list[dict]: + if self.fitted is None: + raise ValueError(f"{self.name}: fit() before associations() or score()") + return self.fitted["rows"] + + def associations(self) -> pd.DataFrame: + """One row per pair tested: the cohort's odds ratio per unit of z, interval, p and q, and + the sensitivity model's odds ratio and whether it points the same way.""" + 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, + "outcome": r["outcome"], + "outcome_code": item_code(r["outcome"]) if kind == "item" else CSS, + "event": f">={ALTERED if kind == 'item' else CSS_HIGH}", + "model": f["model"], + "n": f["n"], + "odds_ratio": ors, + "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": sens, + "same_direction": ( + None + if ors is None or sens is None + else bool(np.sign(ors - 1) == np.sign(sens - 1)) + ), + "reason": f.get("reason", ""), + } + ) + return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS)) + + def score(self, cohort: pd.DataFrame) -> pd.DataFrame: + """Each child's z and probability of the event, with the pair's reference probability (z = + 0, mean age, most frequent module), for every estimated pair whose outcome exists in the + child's module.""" + parts = [] + for r in self._rows(): + f = r["principal"] + if f.get("odds_ratio") is None or r["predictor"] not in cohort: + 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()] + if not len(t): + continue + prob, ref = _probability(f, t) + kept = np.isfinite(prob) + parts.append( + pd.DataFrame( + { + "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], + "probability": prob[kept].round(4), + "reference_probability": round(ref, 4), + } + ) + ) + if not parts: + return pd.DataFrame(columns=list(SCORE_COLUMNS)) + return pd.concat(parts, ignore_index=True)[list(SCORE_COLUMNS)] + + def save(self, path) -> None: + Path(path, "association.json").write_text( + json.dumps({"level": self.level, "fitted": self.fitted}, default=float) + ) + + @classmethod + def load(cls, path) -> Ados2Association: + d = json.loads(Path(path, "association.json").read_text()) + return cls(d["level"], d["fitted"]) + + +MODULE = Ados2Association() + + +class Model(mlflow.pyfunc.PythonModel): + def __init__(self, fitted: dict): + self.fitted = json.loads(json.dumps(fitted, default=float)) + + def predict(self, context, cohort_df): + return Ados2Association(fitted=self.fitted).score(cohort_df) diff --git a/models/tea/jobs.py b/models/tea/jobs.py index 931a9ec..58408f7 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -15,16 +15,27 @@ from pathlib import Path import mlflow.pyfunc import pandas as pd +from sqlalchemy import bindparam, inspect, text +from core.tea import ADOS2_ITEMS, ados2 from models import execution +from models.jobs import EmptyCohort +from models.tea import association from models.tea.eeg import analysis, curves from models.tea.eeg import reference as cohort_reference from persistance import cluster, eeg, registry, silver +from persistance.destination import engine +ASSOCIATION = "ados2_association" MODELS = curves.SCENARIOS CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2 GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: _risk) -GOLD_SELECT = ["tea_eeg_analyses+", "tea_eeg_metrics+"] # what a rebuild of TEA's gold selects +GOLD_SELECT = [ + "tea_eeg_analyses+", + "tea_eeg_metrics+", + "tea_associations", + "tea_association_scores", +] class Baseline(mlflow.pyfunc.PythonModel): @@ -107,9 +118,13 @@ def registered(name: str) -> str: return f"tea.{name}" -def train(name: str, as_of: date | None = None, reference: cluster.Reference | None = None) -> int: +def train( + name: str, as_of: date | None = None, reference: cluster.Reference | None = None +) -> int | None: """A new version of one age curve, trained on the reference cohort's valid studies, with its two reports: the cohort it learned from, and its centile curves.""" + if name == ASSOCIATION: + return train_association(as_of) digest, measured, cohort, hz = _reference(reference) table = cohort_reference.tables(measured)[name] baseline = curves.train(table, name) @@ -133,12 +148,166 @@ def score_curves() -> dict[str, int | None]: return {name: score(name) for name in CURVES} +def cohort() -> tuple[pd.DataFrame, pd.DataFrame]: + """The first EEG with a predictor per child for fitting, and all eligible EEGs for scoring.""" + columns = [ + "key", + "person_id", + "study_date", + "edf", + "age_months", + "ados_module", + "css", + *ADOS2_ITEMS, + ] + records, values = [], {} + with engine().connect() as con: + tables = inspect(con) + if tables.has_table("eeg_analysis", schema="bronze"): + items = ", ".join(ADOS2_ITEMS) + selected_items = ", ".join(f"t.{i}" for i in ADOS2_ITEMS) + query = text(f""" + with first_ados as ( + select person_id, module, evaluation_date, {items}, + row_number() over ( + partition by person_id order by evaluation_date nulls last, known_at + ) as rn + from silver.ados2 + ) + select e.person_id, e.study_date, e.edf, a.age_months, + t.module, t.evaluation_date, p.birth_date, {selected_items} + from silver.eeg as e + join bronze.eeg_analysis as a on a.edf = e.edf + join first_ados as t on t.person_id = e.person_id and t.rn = 1 + left join silver.person as p on p.person_id = e.person_id + where a.valid and a.age_months is not null + """) + for raw in con.execute(query).mappings(): + row = dict(raw) + for field in ("birth_date", "evaluation_date"): + row[field] = date.fromisoformat(str(row[field])[:10]) if row[field] else None + records.append( + { + **row, + "key": f"{row['person_id']}|{str(row['study_date'])[:10]}", + "ados_module": row["module"], + "css": ados2.score( + row, row["birth_date"] if row["evaluation_date"] else None + )[0], + } + ) + if records and tables.has_table("eeg_scores", schema="bronze"): + biomarker = {metric: name for name, metric in association.BIOMARKERS.items()} + query = text(""" + select edf, metric, part, site, z from bronze.eeg_scores + where metric in :metrics and z is not null + """).bindparams(bindparam("metrics", expanding=True)) + edfs = {row["edf"] for row in records} + for edf, metric, part, site, z in con.execute(query, {"metrics": list(biomarker)}): + if edf not in edfs: + continue + name = biomarker[metric] + if name in ("spikes", "spindles"): + if part != "zones": + continue + predictor = f"z_{name}_{site}" + else: + if part != "value": + continue + predictor = f"z_{name}" + values.setdefault(edf, {})[predictor] = z + scored = pd.DataFrame(records, columns=columns) + if values: + scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="edf") + 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_")] + fit = ( + scored[scored[predictors].notna().any(axis=1)] + .drop_duplicates("person_id") + .reset_index(drop=True) + ) + drop = ["person_id", "study_date", "edf"] + return fit.drop(columns=drop), scored.drop(columns=drop) + + +def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str: + """Hash the scored EEGs, fit membership, and module identifier in canonical order.""" + t = scored.assign(_fit=scored["key"].isin(fit["key"])) + t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True) + text = module + "\n" + t.to_csv(index=False, float_format="%.6g") + return hashlib.sha256(text.encode()).hexdigest()[:8] + + +def _records(frame: pd.DataFrame) -> list[dict]: + """Coerce missing estimates and open interval limits to JSON/SQL nulls.""" + clean = frame.replace([float("inf"), -float("inf")], None).astype(object) + return clean.where(clean.notna(), None).to_dict("records") + + +def train_association(as_of: date | None = None) -> int | None: + fit, scored = cohort() + if fit.empty: + raise EmptyCohort(ASSOCIATION) + estimator = association.Ados2Association(level="auto") + mark = fingerprint( + fit, scored, f"{estimator.name}/{estimator.version}/{estimator.impl}/{estimator.level}" + ) + name = registered(ASSOCIATION) + versions = registry.versions(name) + if versions and versions[-1]["params"].get("fingerprint") == mark: + return versions[-1]["version"] + + estimator.fit(fit) + pairs = estimator.associations() + level = estimator.fitted["level"] + forest = ["biomarker", "zone", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"] + reports = { + "technical_validation": { + "model": ASSOCIATION, + "method": "Firth / ordinal logistic, profile CI, BH within biomarker", + "level": level, + "cohort": len(fit), + "scored": len(scored), + "fingerprint": mark, + "pairs": _records(pairs), + }, + "interpretability": {"kind": "forest", "rows": _records(pairs[forest])}, + } + params = {"fingerprint": mark, "level": level} + metrics = {"n_reference": len(fit), "pairs": int(pairs["odds_ratio"].notna().sum())} + return registry.register(name, association.Model(estimator.fitted), params, metrics, reports) + + def relate() -> int | None: - """The ADOS-2 association: scores every analysed EEG with the `ados2_association` - champion (Phase 2). Returns the version that scored, None when the model has no champion. - It writes bronze only (ASSOCIATION_SCORES); the gold rebuild is the job's last step, not - this one's. Until Phase 2 exists it does nothing.""" - return None + found = registry.champion(registered(ASSOCIATION)) + if found is None: + return None + version, model = found + estimator = association.Ados2Association(fitted=model.unwrap_python_model().fitted) + _, scored = cohort() + rows = [] + for row in _records(estimator.associations()): + if row["odds_ratio"] is None or row["odds_ratio"] <= 0: + continue + row["key"] = f"{row['biomarker']}|{row['zone']}|{row['outcome_code']}" + row["method"] = row.pop("model") + row.pop("outcome") + row["level"] = estimator.fitted["level"] + row["n_cohort"] = estimator.fitted["n"] + row["reason"] = row["reason"] or None + rows.append(row) + keys = {row["key"] for row in rows} + scores = [] + for row in model.predict(scored).to_dict("records"): + pair = "|".join(row.pop(field) for field in ("biomarker", "zone", "outcome_code")) + if pair in keys: + eeg_id = row["key"] + scores.append({**row, "eeg_id": eeg_id, "pair": pair, "key": f"{eeg_id}|{pair}"}) + eeg.save_associations(version, rows) + eeg.save_association_scores(version, scores) + return version def score(name: str) -> int | None: diff --git a/tests/test_tea_association.py b/tests/test_tea_association.py new file mode 100644 index 0000000..09790f0 --- /dev/null +++ b/tests/test_tea_association.py @@ -0,0 +1,116 @@ +"""The association fit and its parity with the pinned tea-lib source.""" + +import importlib.util +import sys +from pathlib import Path +from types import ModuleType + +import numpy as np +import pandas as pd + +from core.tea import ADOS2_ITEMS +from models.tea import association as a + +REFERENCE = Path("/home/milk/tea-parity/specs/P2-ref") +MODULES = {"toddler": "TODDLER", "module_1": "MODULO_1", "module_2": "MODULO_2"} +ZONES = dict(zip( + a.ZONE_ITEMS, + ("frontal_izq", "frontal_der", "frontal_media", "central", "parietal", + "temporal_izq", "temporal_der", "occipital"), + strict=True, +)) # fmt: skip + + +def test_firth_on_separation(): + frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6}) + fit = a.firth(frame, "event", "z", ()) + assert np.isfinite(fit["odds_ratio"]) + assert fit["ci_low"] < fit["odds_ratio"] < fit["ci_high"] + + +def test_bh(): + np.testing.assert_allclose(a.bh([0.04, 0.01, np.nan, 0.03]), [0.04, 0.03, np.nan, 0.04]) + + +def test_ordinal_on_monotone_trend(): + frame = pd.DataFrame({"z": np.arange(12), "level": [0, 0, 1, 0, 1, 1, 2, 0, 2, 1, 2, 2]}) + 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 + # Item order in the source, translated by meaning into the platform catalog names. + 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 + frame = pd.DataFrame( + { + "ados_module": ["toddler", "module_1", "module_2", "module_3"], + "vocalization_directed": [3, 7, 1, 1], + } + ) + np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan]) + + +def _reference(monkeypatch): + package = ModuleType("p2_reference") + package.__path__ = [str(REFERENCE)] + contracts = ModuleType("tea.contracts") + contracts.ZONES = tuple(ZONES.values()) + contracts.ASSOCIATION_COLUMNS = a.ASSOCIATION_COLUMNS + contracts.SCORE_COLUMNS = a.SCORE_COLUMNS + contracts.CONTRACT_VERSION = None + monkeypatch.setitem(sys.modules, "p2_reference", package) + monkeypatch.setitem(sys.modules, "tea.contracts", contracts) + for name in ("_items", "_models", "api"): + qualified = f"p2_reference.{name}" + spec = importlib.util.spec_from_file_location(qualified, REFERENCE / f"{name}.py") + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, qualified, module) + spec.loader.exec_module(module) + return sys.modules["p2_reference.api"] + + +def test_reference_parity(monkeypatch): + ref = _reference(monkeypatch) + rng = np.random.default_rng(0) + cohort = pd.DataFrame( + { + "key": range(50), + "age_months": rng.uniform(16, 48, 50), + "ados_module": rng.choice(list(MODULES), 50), + "css": rng.integers(1, 11, 50), + **{item: rng.choice([0, 1, 2, 3, 7, 8], 50) for item in ADOS2_ITEMS}, + **{ + predictor: rng.normal(size=50) + for predictor in dict.fromkeys(pair["predictor"] for pair in a.pairs("item")) + }, + } + ) + other = cohort.drop(columns=ADOS2_ITEMS).copy() + other["ados_module"] = other["ados_module"].map(MODULES) + for number, (_, _, modules) in ref.it.ITEMS.items(): + for module, code in modules.items(): + chosen = other["ados_module"] == module + other.loc[chosen, code] = cohort.loc[chosen, ADOS2_ITEMS[number - 1]] + other = other.rename( + columns={ + f"z_{b}_{zone}": f"z_{b}_{old}" + for zone, old in ZONES.items() + for b in ("spikes", "spindles") + } + ) + ours = a.Ados2Association().fit(cohort) + theirs = ref.Ados2Association().fit(other) + for actual, expected in ( + (ours.associations(), theirs.associations()), + (a.Model(ours.fitted).predict(None, cohort), theirs.score(other)), + ): + actual["zone"] = actual["zone"].replace(ZONES) + pd.testing.assert_frame_equal(actual, expected, check_exact=True)