From 53e6f77c9e91be79885cfcbdd84c6825df29323b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Sat, 28 Nov 2026 21:28:36 -0600 Subject: [PATCH] =?UTF-8?q?Every=20model=20trains=20on=20the=20site:=20EEG?= =?UTF-8?q?=20age=20curves=20on=20the=20children=20with=20TEA=20ruled=20ou?= =?UTF-8?q?t,=20recurrence=20on=20the=20site's=20patients=20(St.=20Gallen?= =?UTF-8?q?=20subtype),=20and=20the=20EEG=E2=80=93ADOS-2=20association?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/cama/recurrence/__init__.py | 37 ++- models/cama/recurrence/calculator.py | 3 +- models/cama/recurrence/modeling.py | 2 +- models/cama/recurrence/reports.py | 3 +- models/cama/recurrence/site.py | 106 ++++++++ models/cama/specs.py | 55 ++-- models/jobs.py | 5 + models/tea/association.py | 389 +++++++++++++++++++++++++++ models/tea/jobs.py | 174 +++++++++--- tests/test_recurrence.py | 7 +- 10 files changed, 700 insertions(+), 81 deletions(-) create mode 100644 models/cama/recurrence/site.py create mode 100644 models/tea/association.py diff --git a/models/cama/recurrence/__init__.py b/models/cama/recurrence/__init__.py index df4db1f..48cfa7c 100644 --- a/models/cama/recurrence/__init__.py +++ b/models/cama/recurrence/__init__.py @@ -60,26 +60,41 @@ class Recurrence: def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: - """Both cohorts' models, validation, calculator and risk factors, from their datasets' - rows. + """Both reference cohorts' models, validation, calculator and risk factors, from their + datasets' rows; the saved model is METABRIC's. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors' stability criterion, are then missing).""" found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES} + return fit(found, SAVED, "metabric+scanb", bootstrap) + + +def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: + """The same, on the site's own cohort (models.cama.recurrence.site).""" + from models.cama.recurrence import site + + return fit({"site": site.prepare(rows)}, "site", "site", bootstrap) + + +def fit(found: dict, saved: str, label: str, + bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: # fmt: skip + """The models of each prepared cohort, their validation, calculator and risk factors; + the `saved` cohort's is the model kept.""" + sources = list(found) n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {} try: fits = modeling.fit(found, n_bootstrap) - drawn = {s: calculator.calculator(fits[s]) for s in SOURCES} + drawn = {s: calculator.calculator(fits[s]) for s in sources} finally: joblib.externals.loky.get_reusable_executor().shutdown(wait=True) - table = pd.concat([factors.risk_factors(fits[s]) for s in SOURCES], ignore_index=True) - summary = [row for s in SOURCES for row in factors.scenario_summary(fits[s], table)] - auc = [row for s in SOURCES for row in reports.auc_rows(fits[s])] - points = [row for s in SOURCES for row in drawn[s][1]] - saved = fits[SAVED] - model = Recurrence(SAVED, HORIZONS, saved.cohort.covariates, modeling.tables(saved)) + table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True) + summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)] + auc = [row for s in sources for row in reports.auc_rows(fits[s])] + points = [row for s in sources for row in drawn[s][1]] + kept = fits[saved] + model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept)) technical = { "model": "recurrence", - "cohort": "metabric+scanb", + "cohort": label, "method": "stepwise logistic regression + Bayesian network (BDeu), averaged", "rutinas": reports.routines(found, n_bootstrap), "recurrencia_desarrollo": reports.development(auc, table, points, summary), @@ -87,7 +102,7 @@ def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurr interpretability = { "model": "recurrence", "kind": "scenarios", - "recurrencia": reports.figures([r for s in SOURCES for r in drawn[s][0]]), + "recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]), } reports_ = {"technical_validation": technical, "interpretability": interpretability} return model, reports.metrics(auc), reports_ diff --git a/models/cama/recurrence/calculator.py b/models/cama/recurrence/calculator.py index 506d93a..c8fcc8d 100644 --- a/models/cama/recurrence/calculator.py +++ b/models/cama/recurrence/calculator.py @@ -21,7 +21,7 @@ RESAMPLES = 200 MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences CAP_MONTHS = 72 # the Weibull curves' extent GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months -LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"} +LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"} # Each scenario: covariate -> the categories it takes (AND across covariates). SCENARIOS = { @@ -59,6 +59,7 @@ SCENARIOS = { "Grado 3": {"Grado_histologico": ["3"]}, }, } # fmt: skip +SCENARIOS["site"] = SCENARIOS["scanb"] # the site's cohort is described as SCAN-B's def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: diff --git a/models/cama/recurrence/modeling.py b/models/cama/recurrence/modeling.py index c668c44..438a2b8 100644 --- a/models/cama/recurrence/modeling.py +++ b/models/cama/recurrence/modeling.py @@ -31,7 +31,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15 MAX_STEPS = 200 COX_PENALIZER = 0.05 COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side -N_BOOTSTRAP = {"metabric": 100, "scanb": 40} +N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40} # ---------------------------------------------------------------- logistic regression diff --git a/models/cama/recurrence/reports.py b/models/cama/recurrence/reports.py index 8d38f40..9f30851 100644 --- a/models/cama/recurrence/reports.py +++ b/models/cama/recurrence/reports.py @@ -15,7 +15,6 @@ from models.cama.recurrence.modeling import ( ESS, HORIZONS, MAX_PARENTS, - N_BOOTSTRAP, CohortFit, ) @@ -137,7 +136,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: "salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por " "bootstrap", "replicas": { - **{s: n_bootstrap.get(s, 0) for s in N_BOOTSTRAP}, + **{s: n_bootstrap.get(s, 0) for s in cohorts}, "calculadora": RESAMPLES, }, "eventos_minimos_por_escenario": MIN_EVENTS, diff --git a/models/cama/recurrence/site.py b/models/cama/recurrence/site.py new file mode 100644 index 0000000..a648c60 --- /dev/null +++ b/models/cama/recurrence/site.py @@ -0,0 +1,106 @@ +"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa +timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy +report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned +from), so the same fits, calculator and risk factors run on it. + +- Time and event: months from the index to her first recurrence (any site) after it, else to + her death, else to the cut-off (the site records its recurrences: a patient without one is + taken as free of it up to then); `muerte_sin_recaida` when she died without one. +- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the + first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN): + age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or + more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate: + Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+, + Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them.""" + +import numpy as np +import pandas as pd + +from models.cama.recurrence import cohorts +from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear + +RESULT_DAYS = 30 +TREATMENT_DAYS = 365 +KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B +STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II", + "III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip +RECEPTOR = {"positive": "Positive", "negative": "Negative"} +SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"} +TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy", + "Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip +FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] +TREATMENT = ["Cirugia", *TREATMENTS] + + +def subtype(er, pr, her2, ki67) -> str: + """The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it.""" + hormone = "positive" in (er, pr) + if her2 == "positive": + return "Luminal B HER2+" if hormone else "Non-luminal HER2+" + if her2 != "negative": + return UNKNOWN + if not hormone: + return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN + if ki67 is None or ki67 != ki67: + return UNKNOWN + return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-" + + +def frame(events: pd.DataFrame, as_of) -> pd.DataFrame: + """One row per member: her time, event and covariates, as `cohorts.prepare` gives a + reference cohort's.""" + events = events.assign(date=pd.to_datetime(events["date"]), + index_date=pd.to_datetime(events["index_date"])) # fmt: skip + members = events.groupby("person_id")["index_date"].first() + days = (events["date"] - events["index_date"]).dt.days + cut = pd.Timestamp(as_of) + after = events[(days > 0) & (events["date"] <= cut)] + first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min() + death = events[(events["type"] == "death") & (events["date"] <= cut)] + death = death.groupby("person_id")["date"].min().reindex(members.index) + end = first_recurrence.reindex(members.index).fillna(death).fillna(cut) + out = pd.DataFrame(index=members.index) + out["paciente"] = members.index + out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH + out["evento"] = first_recurrence.reindex(members.index).notna().astype(int) + out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int) + + near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"]) + code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731 + number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731 + birth = events[events["type"] == "birth"].groupby("person_id")["date"].min() + age = (members - birth.reindex(members.index)).dt.days / 365.25 + out["Edad"] = _band(age, *cohorts.AGE) + out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE) + out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index), + *cohorts.NODES) # fmt: skip + out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES)) + receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")} + ki67 = number("ki67_pct").reindex(members.index) + out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR)) + out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR)) + out["HER2"] = _text(receptors["her2"].map(RECEPTOR)) + high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%") + out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index)) + out["Subtipo_clinico"] = [subtype(*a) for a in zip( + receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip + out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index)) + out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP)) + course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)] + given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index) + given = given.apply(lambda g: g if isinstance(g, set) else set()) + out["Cirugia"] = given.apply( + lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None") + ) + for name, kind in TREATMENTS.items(): + out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No") + return out.reset_index(drop=True) + + +def prepare(rows: pd.DataFrame) -> Cohort: + """The site's cohort as a reference cohort is prepared: the nearly redundant covariates + dropped (cohorts.collinear).""" + covariates = [c for c in rows.columns if c not in FIXED] + dropped = collinear(rows, [c for c in covariates if c not in TREATMENT]) + kept = [c for c in covariates if c not in dropped] + return Cohort("site", rows[FIXED + kept], kept, [c for c in TREATMENT if c in kept], dropped) diff --git a/models/cama/specs.py b/models/cama/specs.py index 27d097f..9af412b 100644 --- a/models/cama/specs.py +++ b/models/cama/specs.py @@ -7,17 +7,17 @@ known at it. A patient who dies before her treatment counts as untreated (immortal-time bias), which the technical report states. Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`. -- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on two public reference - cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the - `cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a - quarter of an hour), so it trains only when asked for by name.""" +- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients + (`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math + (proved on METABRIC and SCAN-B by models/tests/test_recurrence.py); slow (its bootstraps + take minutes), so it trains only when asked for by name.""" from dataclasses import dataclass, field +from datetime import date import pandas as pd -from models.survival import DAYS_PER_YEAR, Spec, age_group, band -from persistance import nodes +from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band # The index report's results (timeline types), read from a week before to RESULT_DAYS after. RESULTS = ("histologic_type", "grade", "er", "pr", "her2") @@ -89,33 +89,40 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: @dataclass(frozen=True) -class ReferenceRecurrence: - """The recurrence model over the reference cohorts the `pipeline` loaded: one source node - per cohort, named as the cohort.""" +class SiteRecurrence: + """The recurrence model on the site's own patients (models.cama.recurrence.site): the + cohort's timelines in, its fits, calculator and risk factors out, with its own reports; + each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in.""" name: str - pipeline: str = "cama_reference" - cohort: None = None # trains on no gold cohort, and scores no patient + cohort: str = "cama_cohort_recurrence" slow: bool = True + reports: bool = True # it writes its own reports (models.jobs) method: str = field(default="stepwise logistic regression + Bayesian network", init=False) def train(self, events, as_of=None) -> tuple: from models.cama import recurrence + from models.cama.recurrence import site - model, metrics, reports = recurrence.train(self.datasets()) - return model, metrics, reports - - def datasets(self) -> dict[str, pd.DataFrame]: - """Each reference cohort's rows, as the pipeline loaded them.""" - from models.cama import recurrence - - found = {s: pd.DataFrame(nodes.rows(self.pipeline, s)) for s in recurrence.SOURCES} - if any(r.empty for r in found.values()): - raise LookupError(f"load the reference cohorts first (pipeline {self.pipeline})") - return found + return recurrence.train_site(site.frame(events, as_of or date.today())) def predict(self, model, events) -> pd.DataFrame: - return model.predict(events) + from models.cama.recurrence import calculator, site + + members = site.frame(events, date.today()) + found = model.predict(members) + index = events.groupby("person_id")["index_date"].first() + masks = calculator.masks(members, calculator.SCENARIOS["site"]) + named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None + for i in range(len(members))] # fmt: skip + rows = [] + for i, person in enumerate(members["paciente"]): + for h in model.horizons: + rows.append({"person_id": person, + "index_date": pd.Timestamp(index[person]).date(), + "horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i], + "ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip + return pd.DataFrame(rows, columns=OUTPUT) MODELS = { @@ -153,5 +160,5 @@ MODELS = { "efecto protector del tratamiento aparece mayor de lo que es.", ), ), - "recurrence": ReferenceRecurrence("recurrence"), + "recurrence": SiteRecurrence("recurrence"), } diff --git a/models/jobs.py b/models/jobs.py index 2995acd..aecad87 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -53,6 +53,11 @@ class Jobs: spec, as_of = self.models[name], as_of or date.today() if spec.cohort is None: # trained on reference data: it writes its own reports fitted, metrics, found = spec.train(None, as_of) + elif getattr(spec, "reports", False): # trained on its cohort, with its own reports + events = gold.timelines(self.events, spec.cohort, as_of) + if events.empty: + raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") + fitted, metrics, found = spec.train(events, as_of) else: events = gold.timelines(self.events, spec.cohort, as_of) if events.empty: diff --git a/models/tea/association.py b/models/tea/association.py new file mode 100644 index 0000000..ba74a0a --- /dev/null +++ b/models/tea/association.py @@ -0,0 +1,389 @@ +"""The EEG–ADOS-2 association (core.tea.association says what it relates): per biomarker, +zone and outcome, how a child's deviation from the age curve (z) goes with an altered +ADOS-2 item or a high CSS, adjusted for age and module. + +- An item: Firth's penalised logistic regression of "altered" on z (the principal model; its + odds ratio, a 95 % profile-likelihood interval and a likelihood-ratio p), with a + cumulative-logit model of the item's level as sensitivity; the CSS the other way round. +- q: Benjamini–Hochberg within each biomarker. +- A child's probability: the principal model at her z (Firth's with the FLIC intercept, so + its probabilities average to the observed rate), and the reference child's (z = 0, the + cohort's mean age, the commonest module). +The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py).""" + +import warnings +from dataclasses import dataclass, field + +import numpy as np +import pandas as pd +from scipy import optimize, stats +from scipy.special import expit +from statsmodels.stats.multitest import multipletests + +from core.tea import association as spec + +CHI2_95 = float(stats.chi2.ppf(0.95, 1)) +MIN_ROWS = 8 +TOO_FEW = "too few data or no variation" + + +def item_scores(frame: pd.DataFrame, number: int) -> pd.Series: + """Item `number`'s algorithm score for each child whose module administers it.""" + name, modules = spec.ITEMS[number] + if name not in frame or "module" not in frame: + return pd.Series(np.nan, index=frame.index) + v = pd.to_numeric(frame[name], errors="coerce") + v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2) + return v.where(frame["module"].isin(modules)) + + +def has_items(frame: pd.DataFrame) -> bool: + scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1) + return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN + + +@dataclass +class Design: + """The columns of one model: intercept, the predictor, the numeric adjustments centred on + the cohort's mean and each categorical one against its commonest level.""" + + predictor: str + numeric: dict[str, float] = field(default_factory=dict) + categorical: dict[str, list[str]] = field(default_factory=dict) + reference: dict[str, str] = field(default_factory=dict) + + @classmethod + def of(cls, t: pd.DataFrame, predictor: str) -> "Design": + d = cls(predictor) + for a in (a for a in spec.ADJUST if a in t): + v = t[a] + if pd.api.types.is_numeric_dtype(v): + if v.astype(float).std() > 0: + d.numeric[a] = float(v.astype(float).mean()) + continue + commonest = v.value_counts().index[0] + levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)] + if levels: + d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest) + return d + + @property + def names(self) -> list[str]: + return [ + "intercept", + self.predictor, + *self.numeric, + *(f"{a}={x}" for a, levels in self.categorical.items() for x in levels), + ] + + def matrix(self, t: pd.DataFrame) -> np.ndarray: + cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)] + cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()] + known = np.ones(len(t), bool) + for a, levels in self.categorical.items(): + v = t[a].astype(str) + cols += [(v == x).to_numpy(float) for x in levels] + known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy() + X = np.column_stack(cols) + X[~known] = np.nan + return X + + def state(self) -> dict: + return { + "predictor": self.predictor, + "numeric": self.numeric, + "categorical": self.categorical, + "reference": self.reference, + } + + @classmethod + def from_state(cls, s: dict) -> "Design": + return cls( + s["predictor"], + dict(s["numeric"]), + {k: list(v) for k, v in s["categorical"].items()}, + dict(s["reference"]), + ) + + +# Firth: the log-likelihood penalised by half the log-determinant of the information. +def _penalised(b, X, y) -> float: + eta = X @ b + w = expit(eta) * (1 - expit(eta)) + sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None])) + return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2) + + +def _gradient(b, X, y): + """The penalised score and the information at `b`.""" + p = expit(X @ b) + w = p * (1 - p) + info = X.T @ (X * w[:, None]) + leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w + return X.T @ (y - p + leverage * (0.5 - p)), info + + +def _firth_fit(X, y, max_iter=200, tol=1e-10): + """Newton–Raphson on the penalised likelihood, halving a step that lowers it.""" + b = np.zeros(X.shape[1]) + best = _penalised(b, X, y) + for _ in range(max_iter): + score, info = _gradient(b, X, y) + step, t = np.linalg.solve(info, score), 1.0 + while t > 1e-8: + trial = _penalised(b + t * step, X, y) + if trial >= best - 1e-12: + break + t /= 2 + b, best = b + t * step, trial + if np.max(np.abs(t * step)) < tol: + break + return b, best + + +def _firth_profile(value, j, X, y, start) -> float: + """The penalised likelihood maximised with coefficient `j` held at `value`.""" + free = [k for k in range(X.shape[1]) if k != j] + + def negative(bf): + b = np.empty(X.shape[1]) + b[free], b[j] = bf, value + v = _penalised(b, X, y) + if not np.isfinite(v): + return 1e10, np.zeros(len(free)) + return -v, -_gradient(b, X, y)[0][free] + + return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun) + + +def _interval(profile, centre, maximum, scale) -> tuple[float, float]: + """Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on + each side of `centre`, searched in steps of `scale` (infinite if never).""" + drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731 + limits = [] + for sign in (-1, 1): + previous, limit = centre, sign * np.inf + for k in range(1, 80): + v = centre + sign * scale * k + if drop(v) > 0: + limit = optimize.brentq(drop, min(previous, v), max(previous, v)) + break + previous = v + limits.append(limit) + return limits[0], limits[1] + + +def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict: + return { + "model": model, + "n": n, + "coef": round(float(coef), 4), + "odds_ratio": round(float(np.exp(coef)), 4), + "ci_low": round(float(np.exp(low)), 4), + "ci_high": round(float(np.exp(high)), 4), + "p": round(p, 5), + "adjusted_for": ", ".join(design.names[2:]), + "reason": "", + **extra, + "state": {"design": design.state(), **state}, + } + + +def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict: + d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna() + y = d[outcome].to_numpy(float) + out = {"model": "firth", "n": len(d), "events": int(y.sum())} + if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0: + return {**out, "reason": TOO_FEW} + design = Design.of(d, predictor) + X = design.matrix(d) + b, top = _firth_fit(X, y) + se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1])) + profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731 + low, high = _interval(profile, b[1], top, max(se, 0.05)) + p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1)) + # FLIC: the intercept refitted so the probabilities add up to the events. + eta = X[:, 1:] @ b[1:] + intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50) + state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)} + return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum())) + + +# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing. +def _ordinal_nll(par, X, y, K) -> float: + theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) + eta = X @ par[K - 1 :] + n = len(y) + cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)] + return -float( + np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None))) + ) + + +def _ordinal_fit(X, y, K, fixed=None): + start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])] + if fixed is None: + r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS") + return r.x, float(r.fun) + j, value = fixed + free = [k for k in range(len(start)) if k != K - 1 + j] + + def nll(q): + par = np.empty(len(start)) + par[free], par[K - 1 + j] = q, value + return _ordinal_nll(par, X, y, K) + + return None, float(optimize.minimize(nll, start[free], method="BFGS").fun) + + +def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict: + d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna() + levels = np.sort(d[outcome].unique()) + out = {"model": "ordinal", "n": len(d), "levels": len(levels)} + if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0: + return {**out, "reason": TOO_FEW} + design = Design.of(d, predictor) + X = design.matrix(d)[:, 1:] + K = len(levels) + y = np.searchsorted(levels, d[outcome].to_numpy()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + par, nll = _ordinal_fit(X, y, K) + beta = par[K - 1 :] + if abs(beta[0]) > 20: + return {**out, "reason": "does not converge (separation)"} + profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731 + low, high_ = _interval(profile, beta[0], -nll, 0.1) + p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1)) + theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) + k = int(np.searchsorted(levels, high)) + inside = 0 < k < K + state = { + "beta": [float(v) for v in beta], + "threshold": float(theta[k - 1]) if inside else None, + "always": None if inside else float(k == 0), + } + return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K) + + +def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]: + """Each child's probability of the outcome under `fit`, and the reference child's.""" + s = fit["state"] + X = Design.from_state(s["design"]).matrix(t) + if fit["model"] == "firth": + return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float( + expit(s["intercept"]) + ) + if s["threshold"] is None: + return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"] + return ( + 1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])), + float(1 - expit(s["threshold"])), + ) + + +def _guarded(fit, *args) -> dict: + try: + return fit(*args) + except (np.linalg.LinAlgError, ValueError) as error: + model = "firth" if fit is firth else "ordinal" + return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"} + + +def fit(cohort: pd.DataFrame, level: str = "auto") -> dict: + """Every pair's principal and sensitivity models and its q: what the association is.""" + if level == "auto": + level = "item" if has_items(cohort) else "domain" + rows = [] + for pair in spec.pairs(level): + if pair["predictor"] not in cohort: + continue + d = cohort.copy() + d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan) + if pair["kind"] == "item": + d["_level"] = item_scores(cohort, pair["outcome"]) + d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna()) + principal = _guarded(firth, d, "_yes", pair["predictor"]) + sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED) + else: + d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce") + d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna()) + principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH) + sensitivity = _guarded(firth, d, "_yes", pair["predictor"]) + rows.append({**pair, "principal": principal, "sensitivity": sensitivity}) + p = np.array([r["principal"].get("p", np.nan) for r in rows], float) + biomarkers = np.array([r["biomarker"] for r in rows]) + q = np.full(len(rows), np.nan) + for b in dict.fromkeys(biomarkers): + mine = (biomarkers == b) & np.isfinite(p) + if mine.any(): + q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5) + for r, v in zip(rows, q, strict=True): + r["q"] = None if np.isnan(v) else float(v) + return {"level": level, "n": len(cohort), "rows": rows} + + +def outcome_code(row: dict) -> str: + return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS + + +def associations(fitted: dict) -> list[dict]: + """One row per pair: what the governance report and the record show.""" + out = [] + for r in fitted["rows"]: + f, s = r["principal"], r["sensitivity"] + ratio, other = f.get("odds_ratio"), s.get("odds_ratio") + out.append( + { + "biomarker": r["biomarker"], + "zone": r["zone"], + "kind": r["kind"], + "outcome": r["outcome"], + "outcome_code": outcome_code(r), + "event": f">={spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH}", + "model": f["model"], + "n": f["n"], + "odds_ratio": ratio, + "ci_low": f.get("ci_low"), + "ci_high": f.get("ci_high"), + "p": f.get("p"), + "q": r["q"], + "sens_model": s["model"], + "sens_odds_ratio": other, + "same_direction": None + if ratio is None or other is None + else bool(np.sign(ratio - 1) == np.sign(other - 1)), + "reason": f.get("reason", ""), + } + ) + return out + + +def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]: + """Each child's probability under every estimated pair, and the reference child's.""" + out = [] + for r in fitted["rows"]: + f = r["principal"] + if f.get("odds_ratio") is None or r["predictor"] not in cohort: + continue + t = cohort + if r["kind"] == "item": + t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])] + t = t[t[r["predictor"]].notna()] + if not len(t): + continue + found, reference = probability(f, t) + for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True): + if np.isfinite(p): + out.append( + { + "key": key, + "biomarker": r["biomarker"], + "zone": r["zone"], + "outcome_code": outcome_code(r), + "z": float(z), + "probability": round(float(p), 4), + "reference_probability": round(reference, 4), + } + ) + return out diff --git a/models/tea/jobs.py b/models/tea/jobs.py index 558d52c..83cb965 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -1,26 +1,27 @@ """TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves -(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and -its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age. - -Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its -features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set -or ages table that changes is measured again.""" +(models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the +children whose diagnosis ruled TEA out, persistance.eeg.ruled_out) and scoring every +analysed EEG against the child's age. The math is the old platform's, proved on its HK1K +cohort by models/tests/test_eeg.py.""" import hashlib -import json -import os from dataclasses import dataclass from datetime import date -from pathlib import Path import mlflow.pyfunc import pandas as pd +from core.tea import ados2 +from core.tea import association as relation from models import cluster +from models.jobs import EmptyCohort +from models.tea import association from models.tea.eeg import analysis, curves, reference from persistance import eeg, registry, silver -MODELS = curves.SCENARIOS +CURVES = curves.SCENARIOS +ASSOCIATION = "eeg-ados2" # trained on the champion curves' z: after they are promoted +MODELS = [*CURVES, ASSOCIATION] GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: _risk) @@ -51,24 +52,6 @@ def analyze() -> int: return len(found) -def _reference() -> tuple[str, list[dict]]: - """The reference cohort's hash and each study's verdict and features, cached.""" - folder = Path(os.environ["TEA_REFERENCE_DIR"]) - ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv")) - studies = reference.listing(folder, ages) - digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest() - cache = os.environ.get("TEA_REFERENCE_CACHE") - path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None - if path and path.exists(): - return digest, json.loads(path.read_text()) - measured = reference.measure(studies) - measured = [{**m, "key": str(m["key"])} for m in measured] - if path: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(measured)) - return digest, measured - - @dataclass(frozen=True) class Jobs: """The domain's model jobs (models.definitions): every curve is routine.""" @@ -85,27 +68,43 @@ def registered(name: str) -> str: def train(name: str, as_of: date | None = None) -> int: - """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.""" - digest, measured = _reference() + if name == ASSOCIATION: + return _train_association(as_of) + return _train_curve(name, as_of) + + +def _train_curve(name: str, as_of: date | None = None) -> int: + """A new version of one age curve, trained on the site's reference group as known on + `as_of` (today by default), with its two reports: the group it learned from, and its + centile curves.""" + day = as_of or date.today() + measured = eeg.ruled_out(day) + if not measured: + raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}") + digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest() table = reference.tables(measured)[name] baseline = curves.train(table, name) - valid = [m for m in measured if m["valid"] and m["error"] is None] + ages = [m["age_months"] for m in measured] technical = { "model": name, "method": "age curves (weighted centiles on log age)", - "cohort": reference.NAME, "cohort_sha256": digest, "studies": len(measured), - "valid_studies": len(valid), - "ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)], - "features": sorted(baseline), + "cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day), + "studies": len(measured), "valid_studies": len(measured), + "ages_months": [min(ages), max(ages)], "features": sorted(baseline), } # fmt: skip interpretability = {"model": name, "kind": "age_curves", "curves": baseline} - metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))} - params = {"cohort": reference.NAME, "cohort_sha256": digest} + metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))} + params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)} reports = {"technical_validation": technical, "interpretability": interpretability} return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) def score(name: str) -> int | None: + if name == ASSOCIATION: + return _score_association() + return _score_curve(name) + + +def _score_curve(name: str) -> int | None: """The champion curve's scores of every analysed EEG: the metric's value, and each electrode and zone it measures; None without a champion.""" found = registry.champion(registered(name)) @@ -113,7 +112,7 @@ def score(name: str) -> int | None: return None version, model = found baseline = model.unwrap_python_model().baseline - scenario, label = MODELS[name], f"{registered(name)}/{version}" + scenario, label = CURVES[name], f"{registered(name)}/{version}" rows = [] for one in eeg.analysed(): metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None) @@ -135,3 +134,100 @@ def score(name: str) -> int | None: "part": part, "site": site or None, **s}) # fmt: skip eeg.save_scores(name, rows) return version + + +class Association(mlflow.pyfunc.PythonModel): + """The fitted association as MLflow serves it: a cohort in, each child's probabilities.""" + + def __init__(self, fitted: dict): + self.fitted = fitted + + def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: + return pd.DataFrame(association.score(self.fitted, model_input)) + + +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.""" + day = str(as_of) if as_of else None + rows = [] + for r in eeg.association_inputs(relation.BIOMARKERS): + a = r["ados2"] + evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None + if day and (r["study_date"] > day or (evaluated and evaluated > day)): + continue + css = None + if evaluated and r["birth_date"]: + row = {**a, "evaluation_date": date.fromisoformat(evaluated)} + css, _ = ados2.score(row, date.fromisoformat(r["birth_date"])) + 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 + scored = pd.DataFrame(rows) + if scored.empty: + return scored, scored + predictors = [c for c in scored.columns if c.startswith("z_")] + 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"]) + + +def _train_association(as_of: date | None = None) -> int: + """A new version of the association, fitted on the site's children, with its reports: + the cohort and pairs it estimated, and the pairs themselves.""" + fit, _ = association_cohort(as_of) + if fit.empty: + raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG") + fitted = association.fit(fit) + 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", + "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), + "estimated": len(estimated), "clear": sum(1 for p in estimated if (p["q"] or 1) < 0.05), + } # fmt: skip + interpretability = {"model": ASSOCIATION, "kind": "associations", "level": fitted["level"], + "children": int(fitted["n"]), "rows": pairs} # fmt: skip + metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))} + params = {"level": fitted["level"], "as_of": str(as_of or date.today())} + reports = {"technical_validation": technical, "interpretability": interpretability} + return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports) + + +def _score_association() -> int | None: + """The champion association's probabilities for every scored EEG; None without one.""" + found = registry.champion(registered(ASSOCIATION)) + if found is None: + return None + version, model = found + fitted = model.unwrap_python_model().fitted + label = f"{registered(ASSOCIATION)}/{version}" + _, scored = association_cohort() + kept = ("biomarker", "zone", "kind", "outcome_code", "event", "n", "odds_ratio", "ci_low", + "ci_high", "p", "q", "sens_odds_ratio", "same_direction", "reason") # fmt: skip + pairs = [{**{k: p[k] for k in kept}, "model": label, + "key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}", + "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)) + scores = [] + for one in association.score(fitted, scored) if not scored.empty else []: + seen = observed.get(one["outcome_code"], {}).get(one["key"]) + pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}" + shown = None if seen is None or seen != seen else float(seen) + scores.append({**one, "edf": one["key"], "model": label, "key": f"{one['key']}|{pair}", + "observed": shown}) # fmt: skip + eeg.save_association(label, pairs, scores) + return version diff --git a/tests/test_recurrence.py b/tests/test_recurrence.py index 0543134..8b3b939 100644 --- a/tests/test_recurrence.py +++ b/tests/test_recurrence.py @@ -68,10 +68,11 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]: drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW))) platform.save("pipelines", "cama_reference", drawn) platform.ingest("cama_reference") - # What the training job reads (models.cama.specs), from that platform. + # Each cohort's rows as the pipeline loaded them (one source node per cohort). out = folder / "datasets.pkl" - platform.run("python", "-c", "import pandas as pd; from models.cama.specs import MODELS; " - f"pd.to_pickle(MODELS['recurrence'].datasets(), {str(out)!r})") # fmt: skip + platform.run("python", "-c", "import pandas as pd; from persistance import nodes; " + "from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows(" + f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip return pd.read_pickle(out)