diff --git a/models/cama/recurrence/__init__.py b/models/cama/recurrence/__init__.py new file mode 100644 index 0000000..52904d1 --- /dev/null +++ b/models/cama/recurrence/__init__.py @@ -0,0 +1,95 @@ +"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months, +learned from two external reference cohorts, METABRIC and SCAN-B, read from their published +files. Per cohort and horizon, a stepwise logistic regression and a Bayesian network (BDeu +parents of the outcome) are fitted and validated (cohorts, modeling); a calculator gives the +recurrence-free probability of clinical scenarios with bootstrap intervals and survival curves +(calculator, curves); risk factors are rated by four criteria (factors); reports gives the +tables and figures. The saved model is METABRIC's, refitted on each whole horizon cohort.""" + +from dataclasses import dataclass + +import joblib +import numpy as np +import pandas as pd + +from models.cama.recurrence import calculator, cohorts, factors, modeling, reports + +SOURCES = ("metabric", "scanb") +HORIZONS = modeling.HORIZONS # months +SAVED = "metabric" + + +def cohort(source: str, raw: pd.DataFrame) -> pd.DataFrame: + """The source's cohort table: fixed columns, then its covariates as categories.""" + return cohorts.prepare(source, raw).frame + + +def read(source: str, path) -> pd.DataFrame: + """The raw file as its publisher distributes it, as `cohort()` expects it.""" + return cohorts.read(source, path) + + +@dataclass +class Recurrence: + """Per horizon: the LR (intercept and coefficients of its terms) and the HBN (CPT over + its parents, keyed by their categories); the recurrence probability is their mean, and an + unseen parent configuration takes the horizon's recurrence rate.""" + + cohort: str + horizons: tuple[int, ...] + covariates: list[str] + tables: dict[int, dict] + + def predict(self, X: pd.DataFrame) -> pd.DataFrame: + """The probability of recurrence by each horizon (`recurrence_{H}m`) for each row + of `X`, whose covariates are categories as in `cohort()` (missing: UNKNOWN).""" + found = X[self.covariates].astype(object) + found = found.where(found.notna(), cohorts.UNKNOWN).astype(str) + dummies = pd.get_dummies(found).astype(float) + out = {} + for h in self.horizons: + t = self.tables[h] + p_lr = np.full(len(found), t["lr_prior"]) + if t["lr_terms"]: + x = dummies.reindex(columns=t["lr_terms"], fill_value=0.0).to_numpy() + logit = t["lr_constant"] + x @ np.asarray(t["lr_coefficients"]) + p_lr = 1 / (1 + np.exp(-logit)) + p_hbn = np.full(len(found), t["hbn_prior"]) + if t["hbn_parents"]: + keys = map(tuple, found[t["hbn_parents"]].to_numpy()) + p_hbn = np.array([t["hbn_cpt"].get(k, t["hbn_prior"]) for k in keys]) + out[f"recurrence_{h}m"] = (p_lr + p_hbn) / 2 + return pd.DataFrame(out, index=X.index) + + +def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: + """Both cohorts' models, validation, calculator and risk factors, from their raw files. + 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} + 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} + 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)) + technical = { + "model": "recurrence", + "cohort": "metabric+scanb", + "method": "stepwise logistic regression + Bayesian network (BDeu), averaged", + "rutinas": reports.routines(found, n_bootstrap), + "recurrencia_desarrollo": reports.development(auc, table, points, summary), + } + interpretability = { + "model": "recurrence", + "kind": "scenarios", + "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 new file mode 100644 index 0000000..fdc091b --- /dev/null +++ b/models/cama/recurrence/calculator.py @@ -0,0 +1,211 @@ +"""The recurrence calculator: for clinical scenarios of each cohort, the mean recurrence-free +probability the LR + HBN average gives its patients at each horizon, with a 95 % interval from +refits on resamples of the whole cohort, next to the scenario's observed survival (Kaplan-Meier) +and its classic and fractional Weibull curves. + +The models are refitted on the whole cohort (and on each resample) with the terms and parents +the split chose; the HBN's pseudo-count counts every level of the cohort, seen in the +(re)sample or not.""" + +from dataclasses import dataclass + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from joblib import Parallel, delayed + +from models.cama.recurrence import curves +from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit + +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"} + +# Each scenario: covariate -> the categories it takes (AND across covariates). +SCENARIOS = { + "metabric": { + "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": { + "Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], + "Tamano_tumor": ["<=20 mm"]}, + "Ganglios 4+": {"Ganglios_positivos": ["4+"]}, + "Tumor >50 mm": {"Tamano_tumor": [">50 mm"]}, + "< 45 años": {"Edad": ["<45"]}, + "≥ 75 años": {"Edad": ["75+"]}, + "Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]}, + "HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]}, + "Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]}, + "RE+ · 1-3 ganglios · cirugía conservadora": { + "Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], + "Cirugia": ["BREAST CONSERVING"]}, + "RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, + }, + "scanb": { + "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": { + "Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], + "Tamano_tumor": ["<=20 mm"]}, + "Ganglios 4+": {"Ganglios_positivos": ["4+"]}, + "Tumor >50 mm": {"Tamano_tumor": [">50 mm"]}, + "< 45 años": {"Edad": ["<45"]}, + "≥ 75 años": {"Edad": ["75+"]}, + "Basal-like": {"Subtipo_clinico": ["Basal-like"]}, + "HER2+ (luminal B HER2+ o no luminal)": { + "Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]}, + "Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]}, + "Luminal · 1-3 ganglios · lumpectomía": { + "Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], + "Cirugia": ["Lumpectomy"]}, + "Grado 3": {"Grado_histologico": ["3"]}, + }, +} # fmt: skip + + +def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: + return { + name: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in cond.items()]) + for name, cond in scenarios.items() + } + + +@dataclass +class Risk: + """The cohort coded once: dummies for the LR, integer codes for the HBN.""" + + fitted: CohortFit + + def __post_init__(self): + frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates + self.n = len(frame) + self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float) + self.codes = {v: pd.factorize(frame[v])[0] for v in covariates} + self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()} + self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy() + + def _key(self, chosen, rows) -> np.ndarray: + key = np.zeros(len(rows), dtype=np.int64) + for p in chosen: + key = key * self.levels[p] + self.codes[p][rows] + return key + + def _combined(self, rows, horizon) -> np.ndarray | None: + """Every patient's (LR + HBN) / 2, fitted on `rows`; None when the LR fails.""" + t, e = self.time[rows], self.event[rows] + recurred = (e == 1) & (t <= horizon) + known = recurred | (t > horizon) + train, y = rows[known], recurred[known].astype(int) + split = self.fitted.horizons[horizon].split + p_lr = p_hbn = np.full(self.n, y.mean()) + if split.terms: + m = logit(y, self.X.iloc[train][split.terms].reset_index(drop=True), "add") + if m is None: + return None + p_lr = m.predict(sm.add_constant(self.X[split.terms], has_constant="add")).to_numpy() + if split.parents: + q = int(np.prod([self.levels[p] for p in split.parents])) + a = ESS / (2 * q) + key = self._key(split.parents, train) + table = (pd.Series(y, index=key).groupby(level=0).sum() + a) / ( + pd.Series(1, index=key).groupby(level=0).sum() + 2 * a + ) + everyone = self._key(split.parents, np.arange(self.n)) + p_hbn = table.reindex(everyone).fillna(y.mean()).to_numpy() + return (p_lr + p_hbn) / 2 + + def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None: + """Per scenario, the mean risk at each horizon over its patients in `rows` (repeats + counted); None when a refit fails.""" + out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks} + for j, h in enumerate(HORIZONS): + combined = self._combined(rows, h) + if combined is None: + return None + for name, mask in scenario_masks.items(): + inside = mask[rows] + if inside.any(): + out[name][j] = combined[rows][inside].mean() + return out + + +def _curves(months, event, observed): + d, c, _ = curves.life_table(months, event) + k, lam = curves.fit_weibull(d, c) + fractional = curves.fit_fractional(d, c, k, lam) + grid = np.linspace(0, CAP_MONTHS, GRID_POINTS) + return { + "km": dict( + zip(("S", "low", "high"), curves.kaplan_meier(months, event, observed), strict=True) + ), + "weibull": curves.weibull(grid, k, lam), + "weibull_fractional": curves.fractional(grid, k, *fractional), + "grid": grid, + } + + +def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]: + """The figure record of each scenario with enough recurrences, and its table rows.""" + source = fitted.cohort.source + scenarios = SCENARIOS[source] if scenarios is None else scenarios + risk = Risk(fitted) + found = masks(fitted.cohort.frame, scenarios) + rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel + samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)] + months = np.floor(risk.time).astype(int) + event = risk.event == 1 + drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS} + jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()] + jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples] # the long ones first + done = Parallel(n_jobs=-1)(jobs) + fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :] + replicas = [r for r in resampled if r is not None] + records, rows = [], [] + for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True): + free = 1 - point[name] + risks = np.array([r[name] for r in replicas]) + low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0) + observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum()) + km, grid = drawn_curves["km"], drawn_curves["grid"].tolist() + records.append( + { + "cohorte": source, + "cohorte_nombre": LABELS[source], + "escenario": name, + "condiciones": scenarios[name], + "n": n, + "recaidas": events, + "horizons_months": list(HORIZONS), + "observado_hasta": observed, + "months_max": CAP_MONTHS, + "km": { + "months": list(range(observed + 1)), + **{k: v.tolist() for k, v in km.items()}, + }, + "weibull": {"t": grid, "S": drawn_curves["weibull"].tolist()}, + "weibull_fractional": {"t": grid, "S": drawn_curves["weibull_fractional"].tolist()}, + "points": { + "COMB": { + "S": free.tolist(), + "low": np.clip(low, 0, 1).tolist(), + "high": np.clip(high, 0, 1).tolist(), + } + }, + "bootstrap_replicas": len(replicas), + } + ) + for j, h in enumerate(HORIZONS): + rows.append( + { + "cohorte": source, + "subgrupo": name, + "n": n, + "recaidas": events, + "horizonte_meses": h, + "S_libre_LR_HBN": free[j], + "IC95_inf": low[j], + "IC95_sup": high[j], + "riesgo_recurrencia": 1 - free[j], + "S_libre_KM": km["S"][min(h, observed)] if h <= observed else np.nan, + "replicas_bootstrap": len(replicas), + } + ) + return records, rows diff --git a/models/cama/recurrence/cohorts.py b/models/cama/recurrence/cohorts.py new file mode 100644 index 0000000..ec9cb6b --- /dev/null +++ b/models/cama/recurrence/cohorts.py @@ -0,0 +1,166 @@ +"""Each reference cohort's raw file as one table of categories: the patients with a known +recurrence time and status, their time to recurrence (`tiempo_meses`), whether it happened +(`evento`), and their covariates as text. A missing or out-of-range value is a category of its +own (UNKNOWN); nothing is imputed or dropped for it. Of each pair of nearly redundant +covariates (Cramér's V >= V_MAX), the one with more unknowns is dropped.""" + +from dataclasses import dataclass + +import pandas as pd +from scipy.stats.contingency import association + +UNKNOWN = "Desconocido" +V_MAX = 0.80 +DAYS_PER_MONTH = 30.4375 + +# Bands, closed on the left: [a, b). +AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) +SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]) +NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"]) +GRADES = {1.0: "1", 2.0: "2", 3.0: "3"} + +FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"} +FIXED = { + "metabric": ["paciente", "tiempo_meses", "evento"], + "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], +} +TREATMENT = { + "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], + "scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], +} +# Covariates taken as they come (our name: the file's column). +PASSTHROUGH = { + "metabric": { + "Receptor_estrogeno": "ER Status", "Receptor_progesterona": "PR Status", + "HER2": "HER2 Status", "Subtipo_PAM50": "Pam50 + Claudin-low subtype", + "Tipo_histologico": "Cancer Type Detailed", "Celularidad": "Cellularity", + "Estado_menopausico": "Inferred Menopausal State", + "Cluster_integrativo": "Integrative Cluster", "Lateralidad": "Primary Tumor Laterality", + "Cirugia": "Type of Breast Surgery", "Quimioterapia": "Chemotherapy", + "Radioterapia": "Radio Therapy", "Hormonoterapia": "Hormone Therapy", + }, + "scanb": { + "Receptor_estrogeno": "ER", "Receptor_progesterona": "PR", "HER2": "HER2", + "Ki67": "Ki67", "Subtipo_clinico": "ClinicalSubtype", "Tipo_histologico": "Histology", + "Estado_menopausico": "MenopauseStatus_bin", "Lateralidad": "Laterality", + "Estadio_clinico": "tnm_ClinicalStage", "Cirugia": "SurgeryType", + "Quimioterapia": "Chemotherapy", "Radioterapia": "Radiation", + "Hormonoterapia": "Endocrine", "AntiHER2": "AntiHER2", + }, +} # fmt: skip +SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} +SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} + + +def read(source: str, path) -> pd.DataFrame: + """The raw file as its publisher distributes it (tab separated, pandas' NA tokens).""" + return pd.read_csv(path, sep="\t", low_memory=False) + + +def _text(s: pd.Series) -> pd.Series: + """As text; missing values are UNKNOWN.""" + return s.astype(object).where(s.notna(), UNKNOWN).astype(str) + + +def _band(s: pd.Series, edges: list, labels: list) -> pd.Series: + return _text(pd.cut(s, edges, labels=labels, right=False).astype(object)) + + +def _metabric(raw: pd.DataFrame) -> pd.DataFrame: + d = raw.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]) + d = d.reset_index(drop=True) + out = pd.DataFrame({"paciente": d["Patient ID"]}) + out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float) + out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int) + out["Edad"] = _band(d["Age at Diagnosis"], *AGE) + out["Tamano_tumor"] = _band(d["Tumor Size"], *SIZE) + out["Ganglios_positivos"] = _band(d["Lymph nodes examined positive"], *NODES) + out["Grado_histologico"] = _text(d["Neoplasm Histologic Grade"].map(GRADES)) + # Mutational load in tertiles of this cohort; a value on a cut falls in the lower band. + load = d["Mutation Count"] + q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() + edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6] + out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"]) + for name, column in PASSTHROUGH["metabric"].items(): + out[name] = _text(d[column]) + return out + + +def _scanb(raw: pd.DataFrame) -> pd.DataFrame: + d = raw[raw["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]) + d = d.reset_index(drop=True) + out = pd.DataFrame({"paciente": d["PatientName"]}) + out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH + out["evento"] = d["RFI_event"].astype(int) + out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int) + out["Edad"] = _band(d["Age_5year_bin"].astype(float) - 2, *AGE) # the 5-year bin's middle + out["Tamano_tumor"] = _band(d["TumorSize_mm"], *SIZE) + out["Ganglios_positivos"] = _text(d["NodeMetSpec"].map(SCANB_NODES)) + out["Grado_histologico"] = _text(d["NHG"].map(SCANB_GRADES)) + for name, column in PASSTHROUGH["scanb"].items(): + out[name] = _text(d[column]) + return out + + +def cramers_v(a: pd.Series, b: pd.Series) -> float: + table = pd.crosstab(a, b).to_numpy() + return association(table, method="cramer") if min(table.shape) > 1 else 0.0 + + +def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]: + """The covariates to drop: pairs by decreasing V (ties: by decreasing names); of each pair + with V >= v_max and neither already dropped, the one with the larger share of unknowns + (on a tie, the first of the pair).""" + pairs = sorted( + ( + (cramers_v(frame[a], frame[b]), a, b) + for i, a in enumerate(candidates) + for b in candidates[i + 1 :] + ), + reverse=True, + ) + unknown = {c: (frame[c] == UNKNOWN).mean() for c in candidates} + dropped = [] + for v, a, b in pairs: + if v < v_max: + break + if a not in dropped and b not in dropped: + dropped.append(a if unknown[a] >= unknown[b] else b) + return dropped + + +@dataclass(frozen=True) +class Cohort: + """A source's cohort table and what its covariates are.""" + + source: str + frame: pd.DataFrame # fixed columns, then the kept covariates + covariates: list[str] + treatment: list[str] + eliminated: list[str] + + @property + def intrinsic(self) -> list[str]: + return [c for c in self.covariates if c not in self.treatment] + + +def prepare(source: str, raw: pd.DataFrame) -> Cohort: + full = {"metabric": _metabric, "scanb": _scanb}[source](raw) + fixed, treatment = FIXED[source], TREATMENT[source] + covariates = [c for c in full.columns if c not in fixed] + dropped = collinear(full, [c for c in covariates if c not in treatment]) + kept = [c for c in covariates if c not in dropped] + return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped) + + +def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: + """The patients whose status at `horizon` months is known (a recurrence by then, or + followed past it), with `y` = recurred by then.""" + t, event = frame["tiempo_meses"], frame["evento"] == 1 + found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True) + found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int) + return found + + +def unknown_shares(cohort: Cohort) -> dict[str, float]: + return {c: float((cohort.frame[c] == UNKNOWN).mean()) for c in cohort.covariates} diff --git a/models/cama/recurrence/curves.py b/models/cama/recurrence/curves.py new file mode 100644 index 0000000..66380e4 --- /dev/null +++ b/models/cama/recurrence/curves.py @@ -0,0 +1,188 @@ +"""Recurrence-free survival curves of a group, from whole months of follow-up: Kaplan-Meier +with its Greenwood band (log-log scale), and a classic and a fractional (Kilbas-Saigo) +Weibull, both fitted by maximum likelihood on the monthly counts of recurrences and +censorings (a recurrence in month m falls between S(m) and S(m+1); a censoring there +survives to m + 1/2). Fits start from several points and stop on iteration counts only.""" + +import mpmath as mp +import numpy as np +from scipy.optimize import minimize +from scipy.special import gammaln + +Z = 1.96 +INVALID = 1e12 # the likelihood outside a model's parameter region + + +def life_table(months: np.ndarray, event: np.ndarray, length: int = 0): + """Per month: recurrences, censorings, and patients at risk at its start.""" + months, event = np.asarray(months, int), np.asarray(event, bool) + length = max(length, int(months.max()) + 2) + d = np.bincount(months[event], minlength=length) + c = np.bincount(months[~event], minlength=length) + at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]]) + return d, c, at_risk + + +def kaplan_meier(months, event, until: int): + """S, low, high at the start of months 0..until.""" + d, _, n = life_table(months, event, until + 1) + with np.errstate(divide="ignore", invalid="ignore"): + q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) + v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0) + S = np.concatenate([[1.0], np.cumprod(q)])[: until + 1] + se = np.sqrt(np.concatenate([[0.0], np.cumsum(v)])[: until + 1]) / np.abs(np.log(S)) + inside = (S > 0) & (S < 1) + return ( + S, + np.where(inside, S ** np.exp(Z * se), S), + np.where(inside, S ** np.exp(-Z * se), S), + ) + + +def _nll(survival, d, c) -> float: + T = len(d) + S = survival(np.arange(0, T + 1, dtype=float)) + mid = survival(np.arange(T) + 0.5) + if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))): + return INVALID + p = np.clip(S[:-1] - S[1:], 1e-300, None) + return -(np.sum(d * np.log(p)) + np.sum(c * np.log(np.clip(mid, 1e-300, None)))) + + +def weibull(t, k, lam): + return np.exp(-((np.asarray(t, float) / lam) ** k)) + + +def fit_weibull(d, c) -> tuple[float, float]: + """(k, lambda) of the classic Weibull, best of a 3 x 3 grid of Nelder-Mead starts.""" + best = None + for k0 in (0.7, 1.0, 1.5): + for l0 in (50.0, 200.0, 1000.0): + r = minimize( + lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c), + [np.log(k0), np.log(l0)], + method="Nelder-Mead", + options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000}, + ) + best = r if best is None or r.fun < best.fun else best + k, lam = np.exp(best.x) + return float(k), float(lam) + + +# ---------------------------------------------------------------- fractional Weibull + +FLOAT_LOG_MAX = 12.0 # largest term a float sum tolerates (e^12: ~5 digits of 16 lost) +MP_LOG_MAX = 300.0 # beyond this the series is out of reach (NaN) +TAIL = -40.0 # the series is summed until its terms fall below e^TAIL +MAX_TERMS = 40_000 +# The fit's likelihood evaluations. v1 stopped on a 60 s wall clock instead; 100 evaluations +# cost at most a few seconds a scenario (later ones wander where the series is costly: 300 +# took up to 7 minutes) and land within 0.05 of v1's curves. +FRACTIONAL_EVALUATIONS = 100 + + +def _horner(coefficients: list[int], x: float, bits: int) -> float: + """The polynomial at `x` in fixed point (integers scaled by 2^bits): exact Python + integers, an order of magnitude faster than mpmath's floats at the same precision.""" + X, acc = int(mp.ldexp(x, bits)), coefficients[-1] + for c in reversed(coefficients[:-1]): + acc = ((acc * X) >> bits) + c + return float(mp.ldexp(acc, -bits)) + + +def kilbas_saigo(z, rho, m, l) -> np.ndarray: # noqa: E741 + """E_{rho,m,l}(z) = sum_n c_n z^n, c_0 = 1, c_n = prod_{i widest.argmax())) + if len(past) == 0: + return np.full(len(z), np.nan) + n = int(past[0]) + 1 + with np.errstate(divide="ignore"): + log_terms = ( + log_c[None, :n] + np.arange(n)[None, :] * np.log(np.maximum(np.abs(z), 1e-300))[:, None] + ) + peak = log_terms.max(axis=1) + out = np.full(len(z), np.nan) + small = peak <= FLOAT_LOG_MAX + signs = np.where(z[:, None] < 0, (-1.0) ** np.arange(n), 1.0) + out[small] = (np.exp(log_terms[small]) * signs[small]).sum(axis=1) + rest = ~small & (peak <= MP_LOG_MAX) + if rest.any(): + digits = 30 + int(peak[rest].max() / 2.3) + bits = int(3.33 * digits) + with mp.workdps(digits): + c = [mp.mpf(1)] + for j in range(n - 1): + a = rho * (m * j + l) + c.append(c[-1] * mp.exp(mp.loggamma(a + 1) - mp.loggamma(a + rho + 1))) + fixed = [int(mp.ldexp(x, bits)) for x in c] + out[rest] = [_horner(fixed, x, bits) for x in z[rest]] + return out + + +def fractional(t, k, alpha, beta, lam) -> np.ndarray: + """The Kilbas-Saigo Weibull's survival; NaN outside its parameter region.""" + t = np.atleast_1d(np.asarray(t, float)) + s = k + alpha - 2 + if k + alpha <= 1 or s + beta <= 0: + return np.full(t.shape, np.nan) + scale = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) + S = np.ones_like(t) + pos = t > 0 + z = -scale * (t[pos] / lam) ** (k + alpha + beta - 2) + S[pos] = kilbas_saigo(z, beta, s / beta + 1, s / beta) + return np.clip(S, 0.0, 1.0) + + +def fit_fractional( + d, c, k: float, lam: float, budget: int = FRACTIONAL_EVALUATIONS +) -> tuple[float, ...]: + """(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, + from the start that reproduces the classic fit (so it is never worse) and then a grid of + others, while `budget` likelihood evaluations last.""" + floor = max(0.0, 1.0 - k) + 1e-6 + horizon = float(len(d)) + calls = [0] + + def unpack(p): + return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1])), np.exp(p[2]) + + def nll(p): + calls[0] += 1 + a, b, scale = unpack(p) + if ( + k + a <= 1 + or k + a + b <= 2 + or not 1.0 <= scale <= 1e7 + or (horizon / scale) ** (k + a + b - 2) > 300 + ): + return INVALID # degenerate: the series would be huge and unstable + return _nll(lambda t: fractional(t, k, a, b, scale), d, c) + + starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0, np.log(lam)]] + starts += [ + [np.log(a0), np.log(b0 / (1 - b0)), np.log(l0)] + for l0 in (lam, 100.0, 500.0) + for a0 in (0.3, 1.0) + for b0 in (0.5, 0.9) + ] + best = None + for p0 in starts: + left = budget - calls[0] + if left <= 0: + break + r = minimize( + nll, + p0, + method="Nelder-Mead", + options={"xatol": 1e-5, "fatol": 1e-9, "maxiter": 1200, "maxfev": left}, + ) + best = r if best is None or r.fun < best.fun else best + return tuple(float(x) for x in unpack(best.x)) diff --git a/models/cama/recurrence/factors.py b/models/cama/recurrence/factors.py new file mode 100644 index 0000000..65de580 --- /dev/null +++ b/models/cama/recurrence/factors.py @@ -0,0 +1,262 @@ +"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has. + +Each category of an intrinsic covariate (not a treatment) is rated against its covariate's +most frequent category by four criteria: (1) its adjusted odds ratio's 95 % CI excludes 1 and +its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least FREQ_MIN of +the time; (3) its covariate is a parent of the HBN; (4) its Kaplan-Meier recurrence-free +survival at the horizon differs from the reference's (95 % CI) in the odds ratio's direction. +"Robusto" needs (1) and three criteria, "sugerente" two. Treatments get their odds ratios, +adjusted for the intrinsic covariates, but no class: they are associations, not effects.""" + +import warnings + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.stats import false_discovery_control + +from models.cama.recurrence.calculator import SCENARIOS, masks +from models.cama.recurrence.cohorts import UNKNOWN, at_horizon +from models.cama.recurrence.curves import life_table +from models.cama.recurrence.modeling import CohortFit, variable_of + +ALPHA = 0.05 +FREQ_MIN = 0.80 +Z = 1.96 +ORDER = { + "riesgo robusto": 0, + "protector robusto": 1, + "riesgo sugerente": 2, + "protector sugerente": 3, + "no concluyente": 4, +} +TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" +COLUMNS = [ + "cohorte", + "horizonte_meses", + "tipo", + "variable", + "categoria", + "referencia", + "n_categoria", + "OR_recurrencia", + "IC95_inf", + "IC95_sup", + "p", + "p_ajustado_BH", + "freq_seleccion_bootstrap", + "en_manta_markov", + "S_libre_categoria", + "S_libre_referencia", + "delta_S", + "delta_IC95_inf", + "delta_IC95_sup", + "c1_or", + "c2_estabilidad", + "c3_manta_markov", + "c4_supervivencia", + "criterios_cumplidos", + "clasificacion", +] +# Scenario presence: the share of the scenario's patients in the category. +DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10 +DESCRIBING = ("definitoria", "mayoritaria") + + +def km_at(months, event, horizon) -> tuple[float, float]: + """Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE.""" + d, _, n = life_table(months, event) + q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) + v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0) + last = min(horizon, len(d) - 1) + 1 + S = float(np.prod(q[:last])) + return S, S * float(np.sqrt(np.sum(v[:last]))) + + +def _odds_ratios(data: pd.DataFrame, y, variables, reference) -> pd.DataFrame: + """Logistic GLM on every category but each covariate's reference (constant and + duplicated dummies dropped): odds ratios with Wald 95 % CI and p.""" + X = pd.get_dummies(data[variables]).astype(float) + X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables]) + X = X.loc[:, X.nunique() > 1] + X = X.loc[:, ~X.T.duplicated()] + m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit() + ci = np.exp(m.conf_int().loc[X.columns]) + return pd.DataFrame( + { + "termino": X.columns, + "OR_recurrencia": np.exp(m.params[X.columns].to_numpy()), + "IC95_inf": ci[0].to_numpy(), + "IC95_sup": ci[1].to_numpy(), + "p": m.pvalues[X.columns].to_numpy(), + } + ) + + +def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame: + cohort = fitted.cohort + frame = at_horizon(cohort.frame, horizon) + data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy() + reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates} + t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates] + months = np.floor(np.minimum(t, horizon + 1)).astype(int) + event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy() + + def complete(table, variables): + """Each term's covariate, category, BH p and survival difference to its reference.""" + table = table.reset_index(drop=True) + table["variable"] = [variable_of(x, variables) for x in table["termino"]] + table["categoria"] = [ + x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True) + ] + table["referencia"] = table["variable"].map(reference) + table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else [] + rows = [] + for v, cat, ref in zip( + table["variable"], table["categoria"], table["referencia"], strict=True + ): + a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == ref).to_numpy() + (sa, ea), (sb, eb) = ( + km_at(months[a], event[a], horizon), + km_at(months[b], event[b], horizon), + ) + delta, se = sa - sb, np.sqrt(ea**2 + eb**2) + rows.append( + { + "n_categoria": int(a.sum()), + "S_libre_categoria": sa, + "S_libre_referencia": sb, + "delta_S": delta, + "delta_IC95_inf": delta - Z * se, + "delta_IC95_sup": delta + Z * se, + } + ) + return pd.concat([table, pd.DataFrame(rows)], axis=1) + + intrinsic, treatment = cohort.intrinsic, cohort.treatment + tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic) + risk = tab["OR_recurrencia"] > 1 + tab["direccion"] = np.where(risk, "riesgo", "protector") + tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA) + excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0) + tab["c4_supervivencia"] = excludes_zero & (np.sign(tab["delta_S"]) == np.where(risk, -1, 1)) + hz = fitted.horizons[horizon] + tab["freq_seleccion_bootstrap"] = tab["variable"].map( + lambda v: np.nan if selection is None else selection.get(v, 0.0) + ) + tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN + tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents) + criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"] + tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1) + tab["clasificacion"] = [ + "no aplica (categoria desconocida)" + if cat == UNKNOWN + else f"{d} robusto" + if c1 and k >= 3 + else f"{d} sugerente" + if k >= 2 + else "no concluyente" + for cat, d, c1, k in zip( + tab["categoria"], + tab["direccion"], + tab["c1_or"], + tab["criterios_cumplidos"], + strict=True, + ) + ] + tab["tipo"] = "factor de riesgo" + if treatment: + both = intrinsic + treatment + tr = _odds_ratios(data, y, both, reference) + of = tr["termino"].map(lambda x: variable_of(x, both)) + tr = complete( + tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment + ) + tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS + tab = pd.concat([tab, tr], ignore_index=True) + tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon + return tab + + +def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame: + """Every horizon's table: by horizon, factors before treatments, by class, by odds ratio + (decreasing); rounded to 4 places. `selection` (per horizon, the share of bootstrap LRs + each covariate entered) defaults to the fit's own bootstrap.""" + if selection is None: + covariates = fitted.cohort.covariates + selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()} + with warnings.catch_warnings(), np.errstate(over="ignore"): + warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios + found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons] + tab = pd.concat(found, ignore_index=True) + tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) + tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5) + keys = ["horizonte_meses", "_kind", "_order", "OR_recurrencia"] + tab = tab.sort_values(keys, ascending=[True, True, True, False]) + return tab[COLUMNS].round(4) + + +def _presence(share: float) -> str: + if share >= DEFINING: + return "definitoria" + return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria" + + +def _listing(part: pd.DataFrame) -> str: + """`variable=category (strength, share)`, `;`-separated; a treatment's strength is + `asociacion`.""" + strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion", + part["clasificacion"].str.split().str[-1]) # fmt: skip + return "; ".join( + f"{v}={c} ({s}, {p:.0%})" + for v, c, s, p in zip( + part["variable"], part["categoria"], strength, part["share"], strict=True + ) + ) + + +def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: + """Per scenario and horizon, the classified factors and treatments nearly all of its + patients have (definitorios) or most have (mayoritarios).""" + frame, source = fitted.cohort.frame, fitted.cohort.source + scenarios = SCENARIOS[source] + found = factors[ + (factors["cohorte"] == source) + & factors["clasificacion"].str.contains("robusto|sugerente|tratamiento") + ] + kind = np.where( + found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0] + ) + found = found.assign(tipo_efecto=kind) + rows = [] + for name, mask in masks(frame, scenarios).items(): + if not mask.any() or found.empty: + continue + share = [ + float((frame.loc[mask, v] == c).mean()) + for v, c in zip(found["variable"], found["categoria"], strict=True) + ] + detail = found.assign(share=share, presence=[_presence(s) for s in share]) + definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items()) + for h in fitted.horizons: + d = detail[detail["horizonte_meses"] == h] + row = { + "cohorte": source, + "escenario": name, + "definicion": definition, + "n_escenario": int(mask.sum()), + "horizonte_meses": h, + } + for k in ("riesgo", "protector", "tratamiento"): + for level, label in ( + ("definitoria", "definitorios"), + ("mayoritaria", "mayoritarios"), + ): + row[f"{k}_{label}"] = _listing( + d[(d["tipo_efecto"] == k) & (d["presence"] == level)] + ) + included = (d["tipo_efecto"] == "riesgo") & d["presence"].isin(DESCRIBING) + row["n_factores_riesgo_incluidos"] = int(included.sum()) + row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0 + rows.append(row) + return rows diff --git a/models/cama/recurrence/modeling.py b/models/cama/recurrence/modeling.py new file mode 100644 index 0000000..c668c44 --- /dev/null +++ b/models/cama/recurrence/modeling.py @@ -0,0 +1,299 @@ +"""Per horizon, two models of recurrence by then: a logistic regression (LR) on the dummies a +stepwise selection keeps, and a Bayesian network (HBN) whose outcome's parents a greedy BDeu +search picks, predicting by its conditional probability table. Each is validated on a +stratified 70/30 split of the horizon's cohort (AUC) and on bootstrap resamples of it (each +replicate its own 70/30 split); a penalized Cox model's C-index rates the whole follow-up. + +Resamples are drawn in order from one seeded generator and fitted in parallel, so every +replicate is the same however many workers run them.""" + +import warnings +from dataclasses import dataclass, field + +import numpy as np +import pandas as pd +import statsmodels.api as sm +from joblib import Parallel, delayed +from lifelines import CoxPHFitter +from lifelines.utils import concordance_index +from pgmpy.structure_score import BDeu +from sklearn.metrics import roc_auc_score +from sklearn.model_selection import train_test_split + +from models.cama.recurrence.cohorts import Cohort, at_horizon + +HORIZONS = (12, 36, 60) # months +SEED = 42 +TEST_SIZE = 0.3 +ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count +MAX_PARENTS = 6 +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} + + +# ---------------------------------------------------------------- logistic regression + + +def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: + """Dummies (each covariate's alphabetically first level is the reference), the + non-constant ones; a term is `{covariate}_{level}`.""" + X = pd.get_dummies(frame[covariates], drop_first=True).astype(float) + return X.loc[:, X.nunique() > 1] + + +def logit(y, X: pd.DataFrame, has_constant: str = "skip"): + """Maximum-likelihood logistic regression with an intercept, or None when it fails.""" + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + X = sm.add_constant(X, has_constant=has_constant) + return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300) + except Exception: + return None + + +def stepwise(X: pd.DataFrame, y) -> list[str]: + """Forward (the smallest Wald p < ALPHA_IN enters) then backward (the largest p > + ALPHA_OUT leaves) until nothing changes; the terms in the order they entered.""" + included = [] + for _ in range(MAX_STEPS): + changed, best, best_p = False, None, ALPHA_IN + for c in X.columns: + if c in included: + continue + m = logit(y, X[included + [c]]) + if m is not None and m.pvalues[c] < best_p: + best, best_p = c, m.pvalues[c] + if best is not None: + included.append(best) + changed = True + if included and (m := logit(y, X[included])) is not None: + p = m.pvalues.drop("const") + if p.max() > ALPHA_OUT: + included.remove(p.idxmax()) + changed = True + if not changed: + break + return included + + +def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]): + """The terms selected on `train` (univariate prefilter, then stepwise) and the test + rows' predicted probabilities (the training rate when no term is selected).""" + X = encode(pd.concat([train, test]), covariates) + X_train = X.loc[train.index] + X_train = X_train.loc[:, X_train.nunique() > 1] + y = train["y"] + candidates = [ + c + for c in X_train.columns + if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER + ] + terms = stepwise(X_train[candidates], y) if candidates else [] + if not terms: + return [], np.full(len(test), y.mean()) + m = logit(y, X_train[terms]) + X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add") + return terms, m.predict(X_test).to_numpy() + + +# ---------------------------------------------------------------- Bayesian network + + +def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: + table = frame[covariates].astype(str) + table["outcome"] = frame["y"].astype(int).astype(str) + return table + + +def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]: + """Greedy: the covariate whose addition most raises the outcome's BDeu score, while + any does (up to MAX_PARENTS); the parents in the order chosen.""" + score = BDeu(table, equivalent_sample_size=ESS) + chosen, current = [], score.local_score("outcome", ()) + while len(chosen) < MAX_PARENTS: + best, gain = None, 0.0 + for c in [c for c in covariates if c not in chosen]: + g = score.local_score("outcome", (*chosen, c)) - current + if g > gain: + best, gain = c, g + if best is None: + break + chosen.append(best) + current += gain + return chosen + + +def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]: + """P(recurrence | parents) for each configuration seen, smoothed by ESS / (2 q) per cell; + `q`, the number of configurations, defaults to the levels seen in `table`.""" + q = q or int(np.prod([table[p].nunique() for p in chosen])) + a = ESS / (2 * q) + counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size") + return { + (k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a)) + for k, r in counts.iterrows() + } + + +def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray: + """The test rows' probabilities by the CPT of `train`; unseen configurations (or no + parents) get the training rate.""" + rate = (train["outcome"] == "1").mean() + if not chosen: + return np.full(len(test), rate) + table = cpt(train, chosen) + return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())]) + + +# ---------------------------------------------------------------- one split, one cohort + + +@dataclass(frozen=True) +class Split: + """The two models' selection and AUC on one 70/30 split.""" + + terms: list[str] + parents: list[str] + auc_lr: float + auc_hbn: float + + +def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split: + train, test = train_test_split( + frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"] + ) + terms, p_lr = lr(train, test, covariates) + bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates) + chosen = parents(bn_train, covariates) + p_hbn = hbn(bn_train, bn_test, chosen) + return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn)) + + +def _replicate(frame, covariates, rows, b) -> Split | None: + """Bootstrap replicate `b`: the split (seed SEED + b) of the resample `rows`; None when + any fit fails (the replicate is then not counted).""" + try: + return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b) + except Exception: + return None + + +def c_index(cohort: Cohort) -> float: + """Harrell's C of a ridge-penalized Cox model on the whole follow-up, by a 70/30 split + stratified by event; dummies with fewer than COX_MIN_COUNT patients on a side are left out.""" + time_event = ["tiempo_meses", "evento"] + X = pd.get_dummies( + cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True + ).astype(float) + X = X.loc[:, X.nunique() > 1] + train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"]) + n = len(train) + keep = [ + c + for c in X.columns + if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT + ] + cox = CoxPHFitter(penalizer=COX_PENALIZER) + cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5}) + risk = cox.predict_partial_hazard(test[keep]) + return float(concordance_index(test["tiempo_meses"], -risk, test["evento"])) + + +def variable_of(term: str, covariates: list[str]) -> str: + """The covariate a dummy belongs to (the longest name it starts with).""" + found = [c for c in covariates if term.startswith(c + "_")] + return max(found, key=len) if found else term + + +@dataclass +class Horizon: + """A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each + covariate entered the LR and the HBN).""" + + n: int + events: int + split: Split + replicates: list[Split] = field(default_factory=list) + + @property + def aucs(self) -> np.ndarray: + return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2) + + def selection(self, covariates: list[str]) -> dict[str, float] | None: + """Share of the replicates whose final LR has a term of each covariate.""" + if not self.replicates: + return None + counts = {} + for r in self.replicates: + for v in {variable_of(t, covariates) for t in r.terms}: + counts[v] = counts.get(v, 0) + 1 + return {v: k / len(self.replicates) for v, k in counts.items()} + + +@dataclass +class CohortFit: + cohort: Cohort + c_index: float + horizons: dict[int, Horizon] + + +def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]: + """Every cohort's split fits, bootstrap replicates and C-index, in one pool of workers. + Each horizon's resamples come from a fresh generator seeded SEED.""" + frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS} + tasks = [] + for (s, h), frame in frames.items(): + rng = np.random.default_rng(SEED) + rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))] + tasks += [ + ((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b)) + for b, r in enumerate(rows) + ] + tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates))) + tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()] + done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks)) + results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True)) + out = {} + for s, cohort in cohorts.items(): + horizons = {} + for h in HORIZONS: + frame = frames[(s, h)] + reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))] + horizons[h] = Horizon( + len(frame), + int(frame["y"].sum()), + results[(s, h, "split")], + [r for r in reps if r is not None], + ) + out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons) + return out + + +def tables(fitted: CohortFit) -> dict[int, dict]: + """What the saved model keeps per horizon: the split's LR terms refitted on the whole + horizon cohort, and the split's HBN parents with their CPT on it.""" + found = {} + for h, hz in fitted.horizons.items(): + frame = at_horizon(fitted.cohort.frame, h) + covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents + prior = float(frame["y"].mean()) + entry = { + "lr_prior": prior, + "lr_terms": terms, + "lr_constant": 0.0, + "lr_coefficients": [], + "hbn_parents": chosen, + "hbn_prior": prior, + "hbn_cpt": {}, + } + if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None: + entry["lr_constant"] = float(m.params["const"]) + entry["lr_coefficients"] = [float(m.params[t]) for t in terms] + if chosen: + entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen) + found[h] = entry + return found diff --git a/models/cama/recurrence/reports.py b/models/cama/recurrence/reports.py new file mode 100644 index 0000000..8d38f40 --- /dev/null +++ b/models/cama/recurrence/reports.py @@ -0,0 +1,163 @@ +"""What the governance page draws, as JSON: the development tables (AUC, risk factors, +calculator points, scenario summaries) and the scenarios' figures, as v1 published them in +`analisis/recurrencia_desarrollo.json` and `analisis/recurrencia.json`, and the five routine +records (`rutinas/`).""" + +import numpy as np +import pandas as pd + +from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES +from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares +from models.cama.recurrence.modeling import ( + ALPHA_IN, + ALPHA_OUT, + COX_PENALIZER, + ESS, + HORIZONS, + MAX_PARENTS, + N_BOOTSTRAP, + CohortFit, +) + +VERSION = 1 +AUC_COLUMNS = [ + "cohorte", + "horizonte_meses", + "modelo", + "n_modelo", + "recurrencias", + "AUC_validacion_interna", + "AUC_bootstrap_medio", + "AUC_bootstrap_IC95_inf", + "AUC_bootstrap_IC95_sup", + "replicas_bootstrap", +] + + +def table(rows, columns=None) -> dict: + """Columns and records; NaN and infinities are null.""" + frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object) + return { + "columnas": [str(c) for c in frame.columns], + "filas": frame.where(frame.notna(), None).to_dict("records"), + } + + +def auc_rows(fitted: CohortFit) -> list[dict]: + """Per horizon and model, the AUC on the internal split and over the bootstrap + replicates (mean, 2.5 and 97.5 percentiles); then the Cox model's C-index.""" + source, rows = fitted.cohort.source, [] + for h, hz in fitted.horizons.items(): + for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))): + aucs = hz.aucs[:, j] + boot = ( + [np.nanmean(aucs), *np.nanpercentile(aucs, [2.5, 97.5])] + if len(aucs) + else [None] * 3 + ) + rows.append( + { + "cohorte": source, + "horizonte_meses": h, + "modelo": name, + "n_modelo": hz.n, + "recurrencias": hz.events, + "AUC_validacion_interna": internal, + **dict(zip(AUC_COLUMNS[6:9], boot, strict=True)), + "replicas_bootstrap": len(aucs) if len(aucs) else None, + } + ) + frame = fitted.cohort.frame + rows.append( + { + "cohorte": source, + "horizonte_meses": "completo", + "modelo": "Cox penalizado (C-index)", + "n_modelo": len(frame), + "recurrencias": int(frame["evento"].sum()), + "AUC_validacion_interna": fitted.c_index, + } + ) + return [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in rows] + + +def metrics(auc: list[dict]) -> dict[str, float]: + """v1's metric names: `{cohort}.auc_{LR|HBN}_{H}m` (internal split), with `_bootstrap` + (the replicates' mean), and `{cohort}.c_index_cox`.""" + found = {} + for r in auc: + if r["horizonte_meses"] == "completo": + found[f"{r['cohorte']}.c_index_cox"] = float(r["AUC_validacion_interna"]) + continue + tag = f"{r['cohorte']}.auc_{r['modelo']}_{r['horizonte_meses']}m" + found[tag] = float(r["AUC_validacion_interna"]) + if r.get("AUC_bootstrap_medio") is not None: + found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"]) + return found + + +def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: + """The five routine records a promotion reads.""" + return { + "MUESTREO": { + "cohortes": { + s: { + "pacientes": len(c.frame), + "recaidas": int(c.frame["evento"].sum()), + "covariables": len(c.covariates), + "eliminadas_por_colinealidad": c.eliminated, + } + for s, c in cohorts.items() + }, + "criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", + "origen": "METABRIC y SCAN-B (externas)", + }, + "DATOS_FALTANTES": { + "criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); " + "no se imputa ni se descarta", + "desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()}, + }, + "METODO_ANALITICO": { + "modelos": "regresión logística con selección stepwise y red bayesiana con padres " + "del desenlace por BDeu, uno por horizonte", + "horizontes_meses": list(HORIZONS), + "alfa_entrada": ALPHA_IN, + "alfa_salida": ALPHA_OUT, + "ess_bdeu": ESS, + "maximo_de_padres": MAX_PARENTS, + "cox_penalizado": COX_PENALIZER, + "combinacion": "promedio de la LR y la HBN", + }, + "BALANCE_CLASES": { + "aplica": False, + "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres " + "de ella después; no se rebalancea", + }, + "CONFIANZA_SALIDA": { + "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}, + "calculadora": RESAMPLES, + }, + "eventos_minimos_por_escenario": MIN_EVENTS, + }, + } + + +def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict: + """`recurrencia_desarrollo`: the tables behind the figures.""" + return { + "version": VERSION, + "tablas": { + "auc": table(auc, AUC_COLUMNS), + "factores_riesgo": table(factors), + "calculadora": table(pd.DataFrame(points).round(4)), + "escenarios_resumen": table(summary), + }, + } + + +def figures(records: list[dict]) -> dict: + """`recurrencia`: each scenario's curves and calculator points.""" + return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records} diff --git a/models/cama/specs.py b/models/cama/specs.py index 7edae0c..98843b6 100644 --- a/models/cama/specs.py +++ b/models/cama/specs.py @@ -1,7 +1,16 @@ -"""The CaMa models. Survival: mortality at 6, 12 and 18 months from the first invasive biopsy -report, by interval survival (models.survival) over the age at the index and that report's -results. Training and scoring read the timelines (gold `cama_events`) of the members of -`gold.cama_cohort_survival`.""" +"""The CaMa models. + +- Survival: mortality at 6, 12 and 18 months from the first invasive biopsy report, by + interval survival (models.survival) over the age at the index and that report's results. + 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) read from a configured folder + (CAMA_REFERENCE_DIR), not on the hospital's patients; slow (its bootstraps take over an + hour), so it trains only when asked for by name.""" + +import os +from dataclasses import dataclass, field +from pathlib import Path import pandas as pd @@ -28,6 +37,32 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: return found +# The reference cohorts' files, as their publishers distribute them. +REFERENCE_FILES = {"metabric": "brca_metabric_clinical_data.tsv", + "scanb": "scanb_clinical_metadata.txt"} # fmt: skip + + +@dataclass(frozen=True) +class ReferenceRecurrence: + """The recurrence model over the reference cohorts of `CAMA_REFERENCE_DIR`.""" + + name: str + cohort: None = None # trains on no gold cohort, and scores no patient + slow: bool = True + method: str = field(default="stepwise logistic regression + Bayesian network", init=False) + + def train(self, events, as_of=None) -> tuple: + from models.cama import recurrence + + folder = Path(os.environ.get("CAMA_REFERENCE_DIR", "reference/cama")) + raws = {s: recurrence.read(s, folder / f) for s, f in REFERENCE_FILES.items()} + model, metrics, reports = recurrence.train(raws) + return model, metrics, reports + + def predict(self, model, events) -> pd.DataFrame: + return model.predict(events) + + MODELS = { "survival": Spec( name="survival", @@ -38,4 +73,5 @@ MODELS = { borders=(0, 6, 12, 18), cap_months=24, ), + "recurrence": ReferenceRecurrence("recurrence"), } diff --git a/models/definitions.py b/models/definitions.py index ca9b6aa..224afca 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -40,7 +40,7 @@ def _jobs(domain: str): class Training(dg.Config): domain: str - models: list[str] = [] # default: every model of the domain + models: list[str] = [] # default: every model of the domain but the slow ones as_of: str | None = None # the date the data are taken up to (default: today) @@ -50,7 +50,7 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict: jobs = _jobs(config.domain) as_of = date.fromisoformat(config.as_of) if config.as_of else None found = {} - for name in config.models or list(jobs.MODELS): + for name in config.models or jobs.JOBS.routine(): found[name] = jobs.train(name, as_of) context.log.info(f"{config.domain}.{name}: version {found[name]}") return found @@ -70,10 +70,10 @@ class Scoring(dg.Config): def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict: """Each model's champion scores its cohort; then gold's risk tables are rebuilt.""" jobs = _jobs(config.domain) - found = {name: jobs.score(name) for name in config.models or list(jobs.MODELS)} + found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()} for name, version in found.items(): context.log.info(f"{name}: " + (f"version {version}" if version else "no champion")) - silver.build([f"{config.domain}_risk+"]) + silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"]) return found @@ -82,4 +82,21 @@ def score(): score_models() -defs = dg.Definitions(jobs=[ingest, train, score]) +class Analysis(dg.Config): + domain: str + + +@dg.op +def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int: + """The domain's studies a model reads whole (TEA: each EEG not analysed yet).""" + found = _jobs(config.domain).analyze() + context.log.info(f"{config.domain}: {found} analysed") + return found + + +@dg.job(tags=WRITES) +def analyze(): + analyze_studies() + + +defs = dg.Definitions(jobs=[ingest, train, score, analyze]) diff --git a/models/graph.py b/models/graph.py index db0cbd2..712ed90 100644 --- a/models/graph.py +++ b/models/graph.py @@ -46,6 +46,8 @@ from core.pipeline import ( from persistance import config_log, nodes, silver MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer +# Files kept whole (catalog `file` fields), once each, keyed by their content hash. +FILES = {"key": {"data_type": "text"}, "content": {"data_type": "binary"}} READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` "text": {"data_type": "text", "nullable": True}, "ocr": {"data_type": "bool"}, @@ -387,10 +389,14 @@ def run_target(p: str, node: Target, kinds: dict[str, str]): linked = {r[RECORD]: r for r in nodes.rows(p, link)} person = {k: r["person_id"] for k, r in linked.items()} model, study = catalog.model(node.entity), catalog.studies()[node.entity] - observations, held_rows = [], [] + observations, held_rows, files = [], [], {} + kept = [n for n, f in study.fields.items() if f.type == "file"] for i in (i for i in node.inputs if i != link): for row in nodes.rows(p, i): values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None} + for name in (n for n in kept if n in values): # kept once, named by its hash + files[key := hashlib.sha256(values[name]).hexdigest()] = values[name] + values[name] = key held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values) if row[RECORD] not in person: held.append("no identity linked to this record") @@ -408,6 +414,7 @@ def run_target(p: str, node: Target, kinds: dict[str, str]): if (value := getattr(clean, name)) is not None: observations.append({**base, "instance": instance, "field": name, catalog.value_column(field): value}) # fmt: skip + nodes.remember("files", [{"key": k, "content": c} for k, c in files.items()], FILES) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) diff --git a/models/jobs.py b/models/jobs.py index 8f46fe7..b3a1272 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -36,6 +36,10 @@ class Jobs: def events(self) -> str: return f"{self.domain}_events" + def routine(self) -> list[str]: + """The models a train or score run takes when none is named: all but the slow ones.""" + return [n for n, s in self.models.items() if not getattr(s, "slow", False)] + def registered(self, name: str) -> str: return f"{self.domain}.{name}" @@ -43,11 +47,15 @@ class Jobs: """A new registered version of the model, trained on its cohort's timelines up to `as_of` (default: today), with its metrics and its two generated reports.""" spec, as_of = self.models[name], as_of or date.today() - fitted, metrics, data = spec.train(gold.timelines(self.events, spec.cohort, as_of), as_of) - found = { - "technical_validation": self.technical_validation(spec, metrics, data), - "interpretability": self.interpretability(spec, fitted, data), - } + if spec.cohort is None: # trained on reference data: it writes its own reports + fitted, metrics, found = spec.train(None, as_of) + else: + events = gold.timelines(self.events, spec.cohort, as_of) + fitted, metrics, data = spec.train(events, as_of) + found = { + "technical_validation": self.technical_validation(spec, metrics, data), + "interpretability": self.interpretability(spec, fitted, data), + } # Bootstraps ran on joblib's worker pool: release it now, or the job's process waits # for its idle workers to time out (5 minutes) before it can end. get_reusable_executor().shutdown(wait=True) @@ -58,6 +66,8 @@ class Jobs: def score(self, name: str) -> int | None: """The champion's risks for today's members of the model's cohort, saved as its risk batch; None when the model has no champion yet.""" + if self.models[name].cohort is None: # scores no patient + return None found = registry.champion(self.registered(name)) if found is None: return None diff --git a/models/tea/__init__.py b/models/tea/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/tea/eeg/__init__.py b/models/tea/eeg/__init__.py new file mode 100644 index 0000000..5c5c831 --- /dev/null +++ b/models/tea/eeg/__init__.py @@ -0,0 +1,2 @@ +"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`, +`curves.py`).""" diff --git a/models/tea/eeg/analysis.py b/models/tea/eeg/analysis.py new file mode 100644 index 0000000..9fe6e18 --- /dev/null +++ b/models/tea/eeg/analysis.py @@ -0,0 +1,132 @@ +"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics. + + analysis = analyze(edf_bytes, birth_date) + +Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared +(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are +measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`). + +The age is the EDF header's (recording start minus birth date) when it has both dates, else the +recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with +`error` set, keeping the verdict and checks when validation finished before it. Missing values +are None. +""" + +import math +import re +from dataclasses import dataclass, field +from datetime import date + +from models.tea.eeg import biomarkers, checks, preprocess, read, sleep + +DAYS_PER_MONTH = 30.4375 +MAINS_HZ = 60.0 + + +@dataclass(frozen=True) +class Metric: + code: str + value: float | None + electrodes: dict[str, float] = field(default_factory=dict) # None where not measured + zones: dict[str, float] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Analysis: + valid: bool | None + level: str + age_months: float | None + clean_fraction: float | None + bad_channels: int | None + channels: int | None + duration_min: float | None + line_noise_db: float | None + sleep: bool | None + checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal + metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes, + # anteroposterior_gradient + features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing + error: str | None + + +def _number(v) -> float | None: + return float(v) if v is not None and math.isfinite(v) else None + + +def _error(exc: Exception) -> str: + message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "", str(exc))[:300] + return f"{type(exc).__name__}: {message}" + + +def analyze( + edf: bytes, + birth_date: date | None = None, + *, + age_months: float | None = None, + mains_hz: float = MAINS_HZ, +) -> Analysis: + """`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency + of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`).""" + out = dict( + valid=None, + level=checks.NOT_ANALYZABLE, + age_months=age_months, + clean_fraction=None, + bad_channels=None, + channels=None, + duration_min=None, + line_noise_db=None, + sleep=None, + checks=[], + metrics=[], + features={}, + error=None, + ) + try: + try: + rec = read.read(edf) + except read.FileNotValid as exc: + verdict = checks.file_not_valid(str(exc)) + return Analysis( + **out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks) + ) + if age_months is None: + header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH) + given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH) + out["age_months"] = age = header if header is not None else given + else: + age = age_months + verdict = checks.validate(rec, mains_hz) + out.update( + valid=verdict.valid, + level=verdict.level, + clean_fraction=verdict.clean_pct / 100, + bad_channels=len(verdict.bad), + channels=len(rec.names) or None, + duration_min=round(rec.duration_s / 60, 2), + line_noise_db=_number(verdict.line_db), + checks=verdict.checks, + ) + if not verdict.valid: + return Analysis(**out) + prep = preprocess.prepare(rec, verdict.bad) + notes = sleep.note_intervals(prep.annotations, prep.duration_s) + states = sleep.states(prep, notes, age) + staged = sleep.stages(prep, states) + metrics, features = biomarkers.measure(prep, states, staged, notes) + out.update( + sleep=bool((states == "sleep").any()), + metrics=[ + Metric( + code, + _number(value), + {k: _number(v) for k, v in electrodes.items()}, + {k: _number(v) for k, v in zones.items()}, + ) + for code, (value, electrodes, zones) in metrics.items() + ], + features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()}, + ) + return Analysis(**out) + except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch + return Analysis(**out | dict(error=_error(exc))) diff --git a/models/tea/eeg/biomarkers.py b/models/tea/eeg/biomarkers.py new file mode 100644 index 0000000..329f0bb --- /dev/null +++ b/models/tea/eeg/biomarkers.py @@ -0,0 +1,113 @@ +"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features +each age baseline scores (by scenario, `curves.SCENARIOS`). + +Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior +electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more. + +Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-4 Hz) power of +each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the +electrode's front-back position (6 electrodes at least). + +Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode. +Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes. +""" + +import numpy as np +from scipy.fft import rfft, rfftfreq +from scipy.signal.windows import hann +from scipy.stats import theilslopes + +from models.tea.eeg import signals, spikes, spindles +from models.tea.eeg.preprocess import WINDOW_S, Prepared +from models.tea.eeg.sleep import POSTERIOR + +MIN_WINDOWS = 15 +FRONT_BACK = { + "Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59, + "T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53, + "Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95, +} # fmt: skip +CODES = ( + "posterior_rhythm", + "spindles_n2", + "spindles_n3", + "paroxysmal_spikes", + "anteroposterior_gradient", +) + + +def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None: + """The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15.""" + starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state] + if len(starts) < MIN_WINDOWS or not names: + return None + x, n = prep.data(names), int(round(WINDOW_S * prep.fs)) + found = [] + for a in (int(round(float(s) * prep.fs)) for s in starts): + if a + n <= len(x) and np.isfinite(x[a : a + n]).all(): + found.append(x[a : a + n].T) + return found or None + + +def posterior_rhythm(prep: Prepared, states) -> float: + names = prep.columns(POSTERIOR) + segments = _segments(prep, names, states, "wake") + if segments is None: + return np.nan + f, power = signals.periodograms(np.stack(segments), prep.fs) + peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))] + found = [hz for hz, _, ok in peaks if ok] + return float(np.median(found)) if len(found) >= 2 else np.nan + + +def delta_gradient(prep: Prepared, states) -> float: + names = [c for c in prep.names if c in FRONT_BACK] + segments = _segments(prep, names, states, "sleep") + if segments is None: + return np.nan + stack = np.stack(segments) + n = stack.shape[-1] + f = rfftfreq(n, 1 / prep.fs) + power = np.abs(rfft((stack - stack.mean(axis=-1, keepdims=True)) * hann(n, sym=True))) ** 2 + delta = np.median(power[..., (f >= 0.5) & (f < 4)].sum(axis=-1), axis=0) + log_power = np.log10(np.maximum(delta, 1e-30)) + y = np.array([FRONT_BACK[c] for c in names]) + finite = np.isfinite(log_power) + return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan + + +def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]: + """(metrics: code -> (value, electrodes, zones), features by scenario).""" + metrics, features = {}, {} + rhythm = posterior_rhythm(prep, states) + metrics["posterior_rhythm"] = (rhythm, {}, {}) + features["eeg-posterior-rhythm"] = {"value": rhythm} + for stage in ("N2", "N3"): + found = spindles.detect(prep, staged, stage) + value, zones = spindles.density(found) + electrodes = spindles.enhancement(prep, found, states) + metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones) + features[f"eeg-spindles-{stage.lower()}"] = { + "value": value, + **{f"zone_{z}": v for z, v in zones.items()}, + } + features[f"eeg-spindle-topography-{stage.lower()}"] = { + f"electrode_{e}": v for e, v in electrodes.items() + } + found = spikes.detect(prep, states, intervals) + if found is None: + nan = dict.fromkeys + found = spikes.Spikes( + np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0 + ) + metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones) + features["eeg-spikes"] = { + "value": found.rate, + **{f"electrode_{e}": v for e, v in found.electrodes.items()}, + **{f"zone_{z}": v for z, v in found.zones.items()}, + "minutes": found.minutes, + } + gradient = delta_gradient(prep, states) + metrics["anteroposterior_gradient"] = (gradient, {}, {}) + features["eeg-gradient"] = {"value": gradient} + return {code: metrics[code] for code in CODES}, features diff --git a/models/tea/eeg/checks.py b/models/tea/eeg/checks.py new file mode 100644 index 0000000..4236cb5 --- /dev/null +++ b/models/tea/eeg/checks.py @@ -0,0 +1,349 @@ +"""Whether an EEG can be analysed: channel rules, 4 s window QC, triage level and gates. + +Channel rules flag a channel bad (each reason is one check): dead (< 10 finite samples or SD +< 0.5 µV, which skips the rest), frozen, saturated, infinite values, gaps of its own; after the +mains notch and a 0.5-45 Hz band-pass, an amplitude over 4 x the scalp median, intermittent +contact (10 s blocks far below the montage) or bursts (far above it); on 1-40 Hz, a bridge with +a contiguous electrode or an ear that does not follow its neighbours; EOG/ECG out of range. + +Window QC splits the kept scalp channels (notch, 0.5-45 Hz) into back-to-back 4 s windows: a +gap, or a window over 800 µV peak to peak, with muscle (30-45 / 4-13 Hz power, fixed lines out, +over 0.6) or common mode over 0.8, is not clean. Triage sets the level from coverage, bad scalp +electrodes and clean minutes; the gates make the EEG not valid when the level is +`not_analyzable`, fewer than 60 % of windows are clean or fewer than 12 scalp electrodes are +usable. +""" + +from dataclasses import dataclass, field + +import numpy as np + +from models.tea.eeg import signals +from models.tea.eeg.read import Recording + +NEIGHBOURS = { + "Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"), + "F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"), + "Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"), + "C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"), + "T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"), + "P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"), + "O2": ("T6", "P4", "O1"), +} # fmt: skip +EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")} +MIN_CLEAN_PCT = 60.0 +MIN_COVERAGE = 0.90 +MAX_BAD_SCALP = 2 +MIN_SCALP = 12 +MAX_LINE_DB = 45.0 +NOT_ANALYZABLE = "not_analyzable" + + +@dataclass(frozen=True) +class Validation: + valid: bool + level: str + bad: dict[str, list[str]] # channel -> reasons, every kind of channel + clean_pct: float + line_db: float + checks: list[dict] = field(default_factory=list) + + @property + def ears_usable(self) -> bool: + return all(ear not in self.bad for ear in ("A1", "A2")) + + +def check( + code, + *, + electrode=None, + value=None, + text=None, + unit=None, + low=None, + high=None, + decisive=False, + abnormal=False, +) -> dict: + return dict( + code=code, + electrode=electrode, + value=value, + text=text, + unit=unit, + low=low, + high=high, + decisive=decisive, + abnormal=abnormal, + ) + + +def file_not_valid(reason: str) -> Validation: + rows = [check("file", text=reason, decisive=True, abnormal=True)] + return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows) + + +def _filtered(x, fs, mains_hz, lo, hi): + return signals.bandpass(signals.notch(x, fs, mains_hz), fs, lo, hi) + + +def _temporal(v: np.ndarray) -> list[tuple[str, str]]: + """Rules on a channel's raw samples: (code, reason).""" + finite = v[np.isfinite(v)] + if len(finite) < 10 or np.std(finite) < 0.5: + return [("dead-channel", "dead channel")] + out = [] + if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5: + out.append(("frozen", "frozen")) + if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001: + out.append(("saturated", "saturated")) + if np.isinf(v).any(): + out.append(("inf-values", "Inf values")) + return out + + +def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: + """Per channel, the fraction of 10 s blocks silent against the montage and bursting above it + (NaN with fewer than 6 blocks).""" + size = int(10 * fs) + blocks = len(y) // size + low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan) + if blocks < 6: + return low, high + sd = np.full((blocks, y.shape[1]), np.nan) + for b in range(blocks): + block = y[b * size : (b + 1) * size] + if np.isfinite(block).all(): + sd[b] = block.std(axis=0) + with np.errstate(all="ignore"): + relative = sd / np.maximum(np.nanmedian(sd, axis=1, keepdims=True), 1e-12) + for i in range(y.shape[1]): + v = relative[:, i] + v = v[np.isfinite(v) & (v > 0)] + if len(v) >= 6: + low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35)) + high[i] = np.mean(v > 4.0) + return low, high + + +def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]: + """Scalp channels correlating over 0.99 with a contiguous electrode and with no far one.""" + finite = np.isfinite(y).all(axis=1) + if finite.sum() < 200 or len(scalp) < 2: + return {} + r = np.abs(np.corrcoef(y[finite][:, scalp].T)) + index = {names[i]: k for k, i in enumerate(scalp)} + out = {} + for name, k in index.items(): + near = [index[n] for n in NEIGHBOURS.get(name, ()) if n in index] + far = [j for j in index.values() if j != k and j not in near] + if not near: + continue + best = max(near, key=lambda j: r[k, j]) + if r[k, best] > 0.99 and not (far and max(r[k, j] for j in far) > 0.99): + out[name] = next(n for n, j in index.items() if j == best) + return out + + +def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]: + """Per ear: its best |r| with its neighbours, and the neighbours' median |r| between them.""" + out = {} + for ear, around in EAR_NEIGHBOURS.items(): + present = [n for n in around if n in names] + if ear not in names or len(present) < 2: + continue + cols = [names.index(ear)] + [names.index(n) for n in present] + rows = np.isfinite(y[:, cols]).all(axis=1) + if rows.sum() < fs * 30: + continue + r = np.abs(np.corrcoef(y[rows][:, cols].T)) + between = [r[a, b] for a in range(1, len(cols)) for b in range(a + 1, len(cols))] + out[ear] = (float(np.nanmax(r[0, 1:])), float(np.nanmedian(between))) + return out + + +def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]: + """Channel -> [(code, reason)] of every channel some rule flags.""" + x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds() + reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)} + dead = { + name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")] + } + notched = signals.notch(x, fs, mains_hz) + y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9)) + y40 = signals.bandpass(notched, fs, 1.0, 40.0) + scalp = [i for i, name in enumerate(names) if kinds[name] == "eeg"] + rms = np.nanstd(y45, axis=0) + median = float(np.nanmedian(rms[scalp])) if scalp else np.nan + ratio = rms / median if np.isfinite(median) and median > 0 else np.full(len(names), np.nan) + low, burst = _contact(y45, fs) + bridges = _bridges(y40, names, scalp) + ears = _ears(y40, fs, names) + missing = 1 - np.isfinite(x).mean(axis=0) + for i, name in enumerate(names): + found, k = reasons[name], kinds[name] + if missing[i] > missing.min() + 0.02: + excess = 100 * (missing[i] - missing.min()) + found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)")) + if name in dead: + continue + if k == "eeg" and name in bridges: + found.append(("bridge", f"bridge with {bridges[name]}")) + if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0: + found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median")) + if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]: + c, e = ears[name] + found.append( + ( + "does-not-correlate", + f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})", + ) + ) + if np.isfinite(low[i]) and low[i] > 0.10: + found.append( + ( + "intermittent-contact", + f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)", + ) + ) + if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05: + found.append( + ( + "intermittent-bursts", + f"intermittent contact by bursts " + f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)", + ) + ) + if k in ("eog", "ecg"): + v = x[:, i][np.isfinite(x[:, i])] + if np.sqrt(np.mean(v**2)) > 20000: + found.append( + ( + "aux-amplitude", + f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, " + f"out of range even for {k.upper()}", + ) + ) + return {name: found for name, found in reasons.items() if found} + + +def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]: + """Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the + verdict `gap`, `suspect` or `clean`.""" + n = int(4 * fs) + lines = signals.fixed_lines(y, fs, f_max=44.0) + starts = list(range(0, len(y) - n + 1, n)) + segments = [y[a : a + n] for a in starts] + whole = [bool(np.isfinite(s).all()) for s in segments] + emg = {} + if any(whole): + stack = np.stack([s.T for s, ok in zip(segments, whole, strict=True) if ok]) + f, power = signals.periodograms(stack, fs) + power = np.moveaxis(power, -1, 0) + high = signals.band_power(f, power, 30.0, 45.0, lines) + low = signals.band_power(f, power, 4.0, 13.0, lines) + ratio = np.median(high / np.maximum(low, 1e-12), axis=1) + emg = dict(zip([a for a, ok in zip(starts, whole, strict=True) if ok], ratio, strict=True)) + out = [] + for a, s, ok in zip(starts, segments, whole, strict=True): + if not ok: + out.append((a / fs, (a + n) / fs, "gap")) + continue + p2p = float(np.max(s.max(axis=0) - s.min(axis=0))) + variance = float(np.mean(s.var(axis=0))) + common = float(s.mean(axis=1).var() / variance) if variance > 0 else np.nan + muscle = float(emg[a]) + suspect = p2p > 800 or (np.isfinite(muscle) and muscle > 0.6) or common > 0.8 + out.append((a / fs, (a + n) / fs, "suspect" if suspect else "clean")) + return out + + +def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float): + """(level, bad scalp electrodes by the triage rule).""" + x, fs, kinds = rec.x, rec.fs, rec.kinds() + columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")] + y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0) + rms, flat = {}, {} + for k, i in enumerate(columns): + v = y[:, k][np.isfinite(y[:, k])] + rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan + flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-9)) if len(v) > 1 else 1.0 + scalp = rec.of("eeg") + median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan + triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5] + minutes = rec.duration_s * clean_pct / 100 / 60 + base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP + if not (base and clean_pct >= 30 and minutes >= 3): + level = NOT_ANALYZABLE + elif not (clean_pct >= 50 and minutes >= 3): + level = "partial" + elif {"A1", "A2"} & {n for n in bad if kinds[n] == "ear"}: + level = "no_ear_reference" + else: + level = "complete" + return level, triaged + + +def validate(rec: Recording, mains_hz: float) -> Validation: + flagged = bad_channels(rec, mains_hz) + scalp = rec.of("eeg") + usable = [n for n in scalp if n not in flagged] + qc = usable if len(usable) >= 2 else scalp + y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0) + windows = window_qc(y, rec.fs) + clean_pct = 100.0 * sum(v == "clean" for *_, v in windows) / max(len(windows), 1) + coverage = float(np.isfinite(rec.x).all(axis=1).mean()) + columns = [rec.names.index(n) for n in scalp] if scalp else slice(None) + db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz) + line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan + level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage) + + rows = [ + check(code, electrode=name, text=reason, abnormal=True) + for name, found in flagged.items() + for code, reason in found + ] + rows += [ + check( + "clean-windows", + value=clean_pct, + unit="%", + low=MIN_CLEAN_PCT, + abnormal=clean_pct < MIN_CLEAN_PCT, + decisive=True, + ), + check( + "internal-coverage", + value=coverage, + unit="fraction", + low=MIN_COVERAGE, + abnormal=coverage < MIN_COVERAGE, + decisive=True, + ), + check( + "bad-scalp-triage", + value=float(len(triaged)), + unit="electrodes", + high=float(MAX_BAD_SCALP), + abnormal=len(triaged) > MAX_BAD_SCALP, + decisive=True, + ), + check( + "usable-scalp", + value=float(len(usable)), + unit="electrodes", + low=float(MIN_SCALP), + abnormal=len(usable) < MIN_SCALP, + decisive=True, + ), + check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True), + ] + if np.isfinite(line): + rows.append( + check( + "line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB + ) + ) + valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP + bad = {name: [reason for _, reason in found] for name, found in flagged.items()} + return Validation(valid, level, bad, clean_pct, line, rows) diff --git a/models/tea/eeg/curves.py b/models/tea/eeg/curves.py new file mode 100644 index 0000000..e4c2672 --- /dev/null +++ b/models/tea/eeg/curves.py @@ -0,0 +1,191 @@ +"""Age baselines: each metric's value (and per electrode and zone) against children of the same +age in a reference cohort. + +Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference +study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets +its own baseline, plain JSON-able data (`train`), scored by `score`: + +* Centile curves: on 120 ages log-spaced from 1 to 216 months, the p5, p25, median, p75 and p95 + of the reference weighted by a Gaussian on log age (width 0.2), where the effective number of + studies is at least 30 and the age lies within the reference's. A value scores z = (value - + median) / ((median - p5 or p95 - median) / 1.645), outside -1 / +1 below p5 / above p95; the + centiles are interpolated on log age; ages outside the curve get none. +* Count rate (spikes, which most reference children never have): the reference's rate per + minute (16 to 37 months) and its dispersion between children (negative binomial by moments, + Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from + the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5, + median and p95 are the rates at those quantiles of the count in those minutes. +""" + +import math +from dataclasses import dataclass + +import numpy as np +import pandas as pd +from scipy import stats + +QUANTILES = {"p5": 0.05, "p25": 0.25, "median": 0.5, "p75": 0.75, "p95": 0.95} +CURVE_AGES = np.exp(np.linspace(np.log(1.0), np.log(216.0), 120)) +LOG_WIDTH = 0.2 +MIN_EFFECTIVE = 30 +COUNT_AGES = (16.0, 37.0) +Z_MAX = 8.0 +EXPOSURE = "minutes" + + +@dataclass(frozen=True) +class Scenario: + metric: str # the metric code it scores + parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones" + stage: str | None = None + counts: bool = False # a count against the `minutes` feature, not centile curves + + +SCENARIOS = { + "eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)), + "eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"), + "eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"), + "eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"), + "eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"), + "eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True), + "eeg-gradient": Scenario("anteroposterior_gradient", ("value",)), +} +PREFIX = {"electrodes": "electrode_", "zones": "zone_"} + + +def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float: + """Interpolated between the midpoints of each weight's cumulative share.""" + order = np.argsort(x) + x, w = x[order], w[order] + return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x)) + + +def _curve(values: np.ndarray, ages: np.ndarray) -> dict: + ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0) + v, log_age = values[ok], np.log(ages[ok]) + curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}} + for a in CURVE_AGES: + w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2) + n_effective = w.sum() ** 2 / (w**2).sum() if w.sum() > 0 else 0.0 + inside = len(log_age) and log_age.min() <= np.log(a) <= log_age.max() + curve["age_months"].append(round(float(a), 3)) + curve["n_effective"].append(round(float(n_effective), 1)) + for name, q in QUANTILES.items(): + enough = n_effective >= MIN_EFFECTIVE and inside + curve[name].append(round(_weighted_quantile(v, w, q), 4) if enough else None) + return { + "kind": "curves", + "log_width": LOG_WIDTH, + "min_effective": MIN_EFFECTIVE, + "curve": curve, + } + + +def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict: + n = np.round(values * exposure) + keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0) + keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1]) + n, x = n[keep], exposure[keep] + rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan") + mu = rate * x + excess = float(((n - mu) ** 2 - n).sum()) + k = float((mu**2).sum() / excess) if excess > 0 else None # None: Poisson + return { + "kind": "count_rate", + "ages": list(COUNT_AGES), + "rate": rate, + "k": k, + "reference": int(keep.sum()), + "events": int(n.sum()), + } + + +def train(features: pd.DataFrame, scenario: str) -> dict: + """Feature -> baseline, for every feature of the scenario's table (`age_months` and the + count's `minutes` excepted).""" + counts = SCENARIOS[scenario].counts + ages = features["age_months"].to_numpy(float) + out = {} + for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"): + values = pd.to_numeric(features[name]).to_numpy(float) + if counts: + out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float)) + else: + out[name] = _curve(values, ages) + return out + + +def _number(v) -> float | None: + return float(v) if v is not None and math.isfinite(v) else None + + +def _score_curve(baseline: dict, value: float, age: float) -> dict: + curve = pd.DataFrame(baseline["curve"]).astype(float).dropna() + out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) + if not len(curve) or not age > 0: + return out + log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0]) + if not log_ages.min() <= at <= log_ages.max(): + return out + q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES} + side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"] + z = (value - q["median"]) / (side / 1.645) if side > 0 else None + outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0 + return { + "z": _number(z), + "outside": outside, + "p5": q["p5"], + "median": q["median"], + "p95": q["p95"], + } + + +def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict: + out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) + rate, k = baseline["rate"], baseline["k"] + lo, hi = baseline["ages"] + if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi): + return out + n, mu = float(np.round(value * exposure)), rate * exposure + law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu)) + tail, at = law.sf(n - 1), law.pmf(n) + z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX)) + p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95)) + return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95} + + +def score( + baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None +) -> dict: + """z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the + age or the baseline's coverage is missing.""" + value, age_months = _number(value), _number(age_months) + if value is None or age_months is None: + return dict.fromkeys(("z", "outside", "p5", "median", "p95")) + if baseline["kind"] == "count_rate": + return _score_count(baseline, value, age_months, _number(exposure)) + return _score_curve(baseline, value, age_months) + + +def deviations(models: dict[str, dict], analysis) -> dict[str, dict]: + """Metric code -> {"value": score, "electrodes": {e: score}, "zones": {z: score}} from the + trained scenarios in `models` (scenario -> `train`'s output); a scenario without a model + leaves its parts out.""" + out = {m.code: {} for m in analysis.metrics} + metrics = {m.code: m for m in analysis.metrics} + for name, scenario in SCENARIOS.items(): + model, metric = models.get(name), metrics.get(scenario.metric) + if model is None or metric is None: + continue + exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None + for part in scenario.parts: + if part == "value": + out[metric.code]["value"] = score( + model["value"], metric.value, analysis.age_months, exposure + ) + else: + out[metric.code][part] = { + key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure) + for key, v in getattr(metric, part).items() + } + return out diff --git a/models/tea/eeg/data/hk1k_state.json b/models/tea/eeg/data/hk1k_state.json new file mode 100644 index 0000000..3eca189 --- /dev/null +++ b/models/tea/eeg/data/hk1k_state.json @@ -0,0 +1,11 @@ +{ + "source": "HK1K reference of the sleep-depth index (223 studies, 16-36 months): each window feature standardised by its median and dispersion, the posterior rhythm's median a line on log10 age; signs and weights of the weighted mean; cut-offs wake < -1.2327 <= drowsy < -0.3032 <= sleep", + "features": { + "delta_beta": {"median": 1.6117037688126001, "dispersion": 0.3097998485854789, "sign": 1, "weight": 1.0}, + "posterior_rhythm": {"slope": 4.934510806157707, "intercept": 0.999676072265559, "median": 7.765061458878031, "dispersion": 1.021788597296859, "sign": -1, "weight": 1.0}, + "sigma": {"median": 0.019957376774209706, "dispersion": 0.012167857665235331, "sign": 1, "weight": 0.7}, + "muscle": {"median": 0.0742822337558628, "dispersion": 0.056777351044491706, "sign": -1, "weight": 0.7}, + "alpha": {"median": 0.03498707283228359, "dispersion": 0.016352123389996105, "sign": -1, "weight": 0.6} + }, + "cuts": [-1.2326590642152986, -0.3031551001049524] +} diff --git a/models/tea/eeg/preprocess.py b/models/tea/eeg/preprocess.py new file mode 100644 index 0000000..b3d6a7d --- /dev/null +++ b/models/tea/eeg/preprocess.py @@ -0,0 +1,66 @@ +"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average +reference, and the 4 s / 2 s window grid with the stretches QC judged not clean. + +The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp +channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given: +the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so. +The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp +channels at 0.5-45 Hz. +""" + +import warnings +from dataclasses import dataclass + +import numpy as np + +from models.tea.eeg import signals +from models.tea.eeg.checks import window_qc +from models.tea.eeg.read import Recording + +NOTCH_HZ = 60.0 +NOTCH_MIN_DB = 6.0 +WINDOW_S = 4.0 +STEP_S = 2.0 + + +@dataclass(frozen=True) +class Prepared: + x: np.ndarray # (samples, scalp channels) µV, average reference + names: tuple[str, ...] # the kept scalp channels + fs: float + starts: np.ndarray # window grid starts, s + unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean + annotations: tuple[tuple[float, float, str], ...] + + @property + def duration_s(self) -> float: + return len(self.x) / self.fs + + def columns(self, wanted) -> list[str]: + """The kept channels among `wanted`, in `wanted`'s order.""" + return [name for name in wanted if name in self.names] + + def data(self, names) -> np.ndarray: + return self.x[:, [self.names.index(name) for name in names]] + + +def prepare(rec: Recording, bad) -> Prepared: + scalp = [name for name in rec.of("eeg") if name not in bad] + x = rec.x[:, [rec.names.index(name) for name in scalp]] + if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB: + x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5) + gaps = ~np.isfinite(x).all(axis=1) + y = signals.bandpass(x, rec.fs, 0.5, 100.0) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row + referenced = y - np.nanmean(y, axis=1, keepdims=True) + # Kept as the reference analysis read it from MNE: through volts and back, column-major in + # memory (the layout decides the order of float sums along time). + referenced = np.asfortranarray(referenced * 1e-6 * 1e6) + qc = signals.bandpass(x, rec.fs, 0.5, 45.0) + qc[gaps] = np.nan + unclean = tuple( + (float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean" + ) + starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S) + return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations) diff --git a/models/tea/eeg/read.py b/models/tea/eeg/read.py new file mode 100644 index 0000000..d805725 --- /dev/null +++ b/models/tea/eeg/read.py @@ -0,0 +1,135 @@ +"""An EDF's bytes as signals: the recognised channels in µV, their kind, the notes and dates. + +`edfio` reads the header first: a file under 256 bytes, an unreadable header, no signals or no +recognised channel is not valid (`FileNotValid`). Channels sampled at another rate than the +majority, and later duplicates of a name, are dropped rather than resampled. MNE then reads the +kept channels' data (`reject_by_annotation="NaN"`: `BAD*` notes are gaps) and the notes. + +Labels are normalised to 10-20 names (`EEG Fp1-REF` -> `Fp1`, T7/T8/P7/P8 -> T3/T4/T5/T6) or +to EKG/LOC/ROC; anything else is not a channel the analysis reads. +""" + +import io +import re +from dataclasses import dataclass +from datetime import date, datetime + +import edfio +import mne +import numpy as np + +STANDARD = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz" +CANONICAL = {name.upper(): name for name in STANDARD.split()} +RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"} +AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC")) +EARS = {"A1", "A2"} +EOG = {"LOC", "ROC"} +# What a header's start date holds when the writer didn't know it. +UNKNOWN_START = date(1985, 1, 1) + + +class FileNotValid(ValueError): + """The bytes are not an EDF the analysis can read.""" + + +def normalize(label: str) -> str | None: + """The channel's 10-20 name (or EKG/LOC/ROC), None if not a recognised channel.""" + text = str(label).strip() + if not text or "ANNOT" in text.upper(): + return None + stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0] + key = re.sub(r"[^A-Z0-9]", "", stem.strip().upper()) + if key in CANONICAL: + name = CANONICAL[key] + return RENAMED.get(name, name) + return next((name for part, name in AUXILIARY if part in text.upper()), None) + + +def kind(name: str) -> str: + """`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name.""" + if name in EARS: + return "ear" + if name in EOG: + return "eog" + return "ecg" if name == "EKG" else "eeg" + + +@dataclass(frozen=True) +class Recording: + x: np.ndarray # (samples, channels) µV, NaN in gaps + fs: float + names: tuple[str, ...] + annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text) + start: date | None + birthday: date | None + + @property + def duration_s(self) -> float: + return len(self.x) / self.fs + + def kinds(self) -> dict[str, str]: + return {name: kind(name) for name in self.names} + + def of(self, *kinds: str) -> list[str]: + """The channels of these kinds, in file order.""" + return [name for name in self.names if kind(name) in kinds] + + +def _kept(edf: bytes) -> list[tuple[str, str]]: + """(label, name) of the channels to read: recognised, at the majority rate, first of each.""" + if len(edf) < 256: + raise FileNotValid("file too short to be an EDF (header < 256 bytes)") + try: + signals = edfio.read_edf(edf, lazy_load_data=True).signals + except Exception as exc: # noqa: BLE001 -- any parse failure means the same + raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None + if not signals: + raise FileNotValid("the EDF declares zero signals") + named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals] + named = [(label, name, rate) for label, name, rate in named if name is not None] + if not named: + raise FileNotValid("no recognised channel") + rates = [rate for _, _, rate in named] + fs = max(set(rates), key=rates.count) + kept, seen = [], set() + for label, name, rate in named: + if abs(rate - fs) <= 1e-6 and name not in seen: + seen.add(name) + kept.append((label, name)) + return kept + + +def read(edf: bytes) -> Recording: + kept = _kept(edf) + options = dict(include=[label for label, _ in kept], preload=True, verbose="error") + try: + raw = mne.io.read_raw_edf(io.BytesIO(edf), **options) + except Exception as exc: # notes in a Windows code page + if "latin1" not in str(exc): + raise + raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options) + raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name}) + names = [name for name in raw.ch_names if name in {n for _, n in kept}] + x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6 + start = raw.info.get("meas_date") + born = (raw.info.get("subject_info") or {}).get("birthday") + notes = tuple( + (float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations + ) + return Recording( + x=x, + fs=float(raw.info["sfreq"]), + names=tuple(names), + annotations=notes, + start=start.date() if isinstance(start, datetime) else start, + birthday=date(*born) if isinstance(born, tuple) else born, + ) + + +def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None: + """Months from birth to the recording, to one decimal; None when a date is missing or is the + unknown-start placeholder, the birth is after the start or the age is over 18 years.""" + if start is None or birthday is None or start == UNKNOWN_START or birthday > start: + return None + months = round((start - birthday).days / days_per_month, 1) + return months if months <= 216 else None diff --git a/models/tea/eeg/reference.py b/models/tea/eeg/reference.py new file mode 100644 index 0000000..67d92b6 --- /dev/null +++ b/models/tea/eeg/reference.py @@ -0,0 +1,62 @@ +"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public), +children of 16 to 36 months, recorded on 50 Hz mains. + +`listing` pairs each EDF under a folder with its age from the cohort's table (first column the +file name, second the age in years; months = years x 12 to one decimal); keys are positions in +path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's +mains, with the table's age) in worker processes; `tables` gives each scenario's training table +from the valid studies. +""" + +import multiprocessing +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import pandas as pd + +from models.tea.eeg.analysis import analyze +from models.tea.eeg.curves import SCENARIOS + +NAME = "hk1k" +MAINS_HZ = 50.0 +AGES = (16.0, 36.0) + + +def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]: + """(key, path, age in months) of each EDF with an age within `ages`.""" + table = pd.read_csv(ages_table) + years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True)) + found = [] + for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"): + age = round(float(years[path.name] * 12), 1) if path.name in years else None + if age is not None and age == age and ages[0] <= age <= ages[1]: + found.append((path, age)) + return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] + + +def _one(study: tuple[str, Path, float]) -> dict: + key, path, age = study + a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=MAINS_HZ) + return { + "key": key, + "age_months": age, + "valid": a.valid, + "error": a.error, + "features": a.features, + } + + +def measure(studies, workers: int = 4) -> list[dict]: + """Each study's verdict and features, in listing order.""" + context = multiprocessing.get_context("spawn") + with ProcessPoolExecutor(workers, mp_context=context) as pool: + return list(pool.map(_one, studies)) + + +def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: + """Scenario -> its training table: the valid studies' features and `age_months`.""" + usable = [s for s in measured if s["valid"] and s["error"] is None] + return { + name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable]) + for name in SCENARIOS + } diff --git a/models/tea/eeg/signals.py b/models/tea/eeg/signals.py new file mode 100644 index 0000000..8bb614e --- /dev/null +++ b/models/tea/eeg/signals.py @@ -0,0 +1,162 @@ +"""Signal primitives every step shares. + +Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A +filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum +stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge +padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains +notch, the fixed-line search and the dominant peak are small rules of their own: no library +computes the same thing (MNE's notch filters change the signal by microvolts). +""" + +import numpy as np +from mne.time_frequency import psd_array_welch +from scipy import signal +from scipy.ndimage import median_filter + + +def runs(valid: np.ndarray) -> list[tuple[int, int]]: + """`(start, stop)` of each run of True.""" + edges = np.diff(np.concatenate([[False], np.asarray(valid, bool), [False]]).astype(int)) + return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True)) + + +def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray: + """`fn` on each gap-free run of rows at least `minimum` long; NaN elsewhere.""" + x = np.asarray(x, float) + out = np.full_like(x, np.nan) + for a, b in runs(np.isfinite(x).all(axis=1)): + if b - a >= minimum: + out[a:b] = fn(x[a:b]) + return out + + +def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray: + """Zero-phase Butterworth band-pass of each gap-free run.""" + sos = signal.butter(order, [lo / (fs / 2), hi / (fs / 2)], btype="band", output="sos") + minimum = max(3 * (2 * len(sos) + 1), int(fs)) + return by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum) + + +def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray: + """Mains removal by spectrum interpolation: around `f0` and each harmonic below 98 % of + Nyquist, the FFT magnitudes within `width` Hz are replaced by a line from the mean magnitude + of the `2 width` Hz on the left to that on the right, keeping the phase.""" + centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98] + + def interpolate(run): + f = np.fft.rfftfreq(len(run), 1 / fs) + spectrum = np.fft.rfft(run, axis=0) + for c in centres: + inside = (f >= c - width) & (f <= c + width) + left = (f >= c - 3 * width) & (f < c - width) + right = (f > c + width) & (f <= c + 3 * width) + if not (inside.any() and left.any() and right.any()): + continue + k = np.linspace(0, 1, int(inside.sum()))[:, None] + target = ( + np.abs(spectrum[left]).mean(axis=0)[None, :] * (1 - k) + + np.abs(spectrum[right]).mean(axis=0)[None, :] * k + ) + current = spectrum[inside] + magnitude = np.abs(current) + phase = np.where(magnitude > 0, current / np.maximum(magnitude, 1e-30), 1.0) + spectrum[inside] = target * phase + return np.fft.irfft(spectrum, n=len(run), axis=0) + + return by_runs(x, interpolate, max(int(2 * fs), 256)) + + +def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray: + """Per channel, dB of the mains peak (`f0` ± 0.6 Hz) over its neighbourhood (2-6 Hz away), + from one Hann-tapered FFT of the rows finite in every channel.""" + finite = np.isfinite(x).all(axis=1) + if not finite.any(): + return np.full(x.shape[1], np.nan) + run = x[finite] - x[finite].mean(axis=0) + f = np.fft.rfftfreq(len(run), 1 / fs) + power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2 + peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0) + around = ((f >= f0 - 6) & (f <= f0 - 2)) | ((f >= f0 + 2) & (f <= f0 + 6)) + near = power[around].mean(axis=0) + with np.errstate(divide="ignore", invalid="ignore"): + return 10 * np.log10(np.where(near > 0, peak / near, np.nan)) + + +def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: + """One Hann periodogram (density, mean removed) of each segment along the last axis: + `(..., n)` -> `(frequencies, (..., n // 2 + 1))`.""" + n = segments.shape[-1] + power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + return f, power + + +def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]: + """Frequencies of narrow fixed lines of a recording (artefacts, not EEG): the power of 8 s + Hann segments, averaged and its median taken over channels, in dB above a 4 Hz running + median; local maxima in [1, f_max] Hz at least 6 dB up and at most 0.5 Hz wide at -3 dB, + the most prominent kept where two lie within 0.5 Hz.""" + n = int(round(8 * fs)) + f = np.fft.rfftfreq(n, 1 / fs) + taper = np.hanning(n)[:, None] + total, count = None, 0 + for a in range(0, len(x) - n + 1, n): + segment = x[a : a + n] + if np.isfinite(segment).all(): + power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2 + total = power if total is None else total + power + count += 1 + if not count: + return [] + db = 10 * np.log10(np.maximum(np.median(total / count, axis=1), 1e-30)) + df = float(f[1] - f[0]) + half = max(1, int(round(2 / df))) + prominence = db - median_filter(db, size=2 * half + 1, mode="nearest") + f_max = min(f_max, fs / 2 - 2) + found = [] + for i in range(1, len(f) - 1): + p = prominence[i] + if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or p < prominence[i + 1]: + continue + a = b = i + while a > 0 and prominence[a - 1] >= p - 3: + a -= 1 + while b < len(f) - 1 and prominence[b + 1] >= p - 3: + b += 1 + if (b - a + 1) * df <= 0.5: + found.append((round(float(f[i]), 3), round(float(p), 1))) + kept = [] + for hz, db_up in sorted(found, key=lambda line: -line[1]): + if all(abs(hz - other) > 0.5 for other, _ in kept): + kept.append((hz, db_up)) + return [hz for hz, _ in kept] + + +def band_power(f, power, lo, hi, lines=(), include_hi=False): + """Power summed over [lo, hi) Hz (`include_hi`: [lo, hi]) along the first axis of `power`, + without the bins within 1 Hz of a fixed line, rescaled to the band's full width.""" + band = (f >= lo) & ((f <= hi) if include_hi else (f < hi)) + clean = band.copy() + for line in lines: + clean &= np.abs(f - line) > 1.0 + if not clean.any(): + return np.full(power.shape[1:], np.nan) if power.ndim > 1 else np.nan + return power[clean].sum(axis=0) * (band.sum() / clean.sum()) + + +def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]: + """The largest 3-14 Hz peak over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz: + (Hz, prominence in dB, found). Found when at least 1.5 dB up and not at the band's edge.""" + usable = (f >= 1.5) & (f <= 45) & (power > 0) + background = usable & ~((f >= 4) & (f <= 16)) + if background.sum() < 5: + return np.nan, np.nan, False + line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1) + residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable]))) + fu = f[usable] + band = (fu >= 3) & (fu <= 14) + if not band.any(): + return np.nan, np.nan, False + i = int(np.argmax(residual[band])) + prominence = float(residual[band][i]) + found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1 + return (float(fu[band][i]) if found else np.nan), prominence, bool(found) diff --git a/models/tea/eeg/sleep.py b/models/tea/eeg/sleep.py new file mode 100644 index 0000000..424cf8d --- /dev/null +++ b/models/tea/eeg/sleep.py @@ -0,0 +1,223 @@ +"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3). + +Notes: a note's state is the first whose words its text contains (lower case, accents removed, +ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s; +pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement, +disconnection, photic stimulation and hyperventilation are masked. + +State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five +features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma, +muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is standardised by +the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age), +and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no +posterior electrode leaves that feature out of the mean. + +Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2 +s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least +20 % of the 30 s centred on it, else N2. +""" + +import json +import unicodedata +from pathlib import Path + +import numpy as np + +from models.tea.eeg import signals +from models.tea.eeg.preprocess import WINDOW_S, Prepared + +REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text()) +NOTE_WORDS = { + "photic": ("fotic", "photic", "flash", "estimulacion luminosa"), + "hyperventilation": ("hv", "hipervent", "hypervent"), + "eyes_open": ("ojos abiertos", "eyes open", "oa"), + "eyes_closed": ("ojos cerrados", "eyes closed", "oc"), + "sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii", + "n1", "n2", "n3"), + "awake": ("despierta", "despierto", "arousal", "vigilia"), + "crying": ("llanto", "llora", "cry"), + "movement": ("movimiento", "movement", "artefacto de movimiento"), + "feeding": ("come", "alimenta", "biberon", "lactancia"), +} # fmt: skip +EXCLUDED = ("crying", "movement", "disconnection") +MASKED = (*EXCLUDED, "photic", "hyperventilation") +STATES = np.array(["wake", "drowsy", "sleep"], dtype=object) +BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16), + "beta": (16, 30), "high": (20, 40)} # fmt: skip +POSTERIOR = ("O1", "O2", "P3", "P4") +CENTRAL = ("C3", "C4", "Cz") +FRONTAL = ("F3", "F4", "Fz") + + +def note_state(text: str) -> str | None: + kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1") + plain = "".join( + c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn" + ) + plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip() + return next( + (state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None + ) + + +def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]: + """(onset s, duration s, state) covering the record: the notes' states and `unmarked`.""" + notes = sorted(annotations, key=lambda note: note[0]) + found = [] + for i, (t0, length, text) in enumerate(notes): + state = note_state(text) + if state is None: + continue + if length > 0: + t1 = t0 + length + else: + following = next((n[0] for n in notes[i + 1 :] if note_state(n[2])), None) + t1 = min(t0 + 60.0, following if following else t0 + 60.0) + if t1 - t0 >= 1: + found.append((t0, t1, state)) + found.sort(key=lambda piece: piece[0]) + full, cursor = [], 0.0 + for t0, t1, state in found: + if t0 - cursor >= 1: + full.append((cursor, t0, "unmarked")) + full.append((t0, t1, state)) + cursor = max(cursor, t1) + if duration_s - cursor >= 1: + full.append((cursor, duration_s, "unmarked")) + pieces = [(round(t0, 2), round(t1, 2), state) for t0, t1, state in full] + return [(t0, t1 - t0, state) for t0, t1, state in pieces] + + +def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]: + """The state covering most of [t0, t1) and whether it covers less than 80 % of it.""" + overlap = {} + for onset, length, state in intervals: + lo, hi = max(t0, onset), min(t1, onset + length) + if hi > lo: + overlap[state] = overlap.get(state, 0) + (hi - lo) + if not overlap: + return "unlabelled", False + dominant = max(overlap, key=overlap.get) + return dominant, overlap[dominant] < 0.8 * (t1 - t0) + + +def mask(prep: Prepared, intervals) -> np.ndarray: + """Samples of the QC spans and of the masked notes.""" + out = np.zeros(len(prep.x), bool) + spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)] + for onset, length in spans: + out[int(onset * prep.fs) : int((onset + length) * prep.fs)] = True + return out + + +def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]: + """Start samples of the usable windows and their features.""" + fs, x, names = prep.fs, prep.x, list(prep.names) + n, step = int(WINDOW_S * fs), int(2 * fs) + starts = [ + a + for a in range(0, len(x) - n + 1, step) + if np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any() + ] + if not starts: + return [], {} + f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs) + band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()} + total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12) + central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names)))) + posterior = [names.index(c) for c in POSTERIOR if c in names] + delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1) + features = { + "delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)), + "sigma": np.median((band["sigma"] / total)[:, central], axis=1), + "muscle": np.median( + band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1 + ), + "alpha": np.median(band["alpha"] / total, axis=1), + } + if posterior: + peaks = [ + signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts)) + ] + features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks]) + return starts, features + + +def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray: + """The weighted mean of the standardised features, clipped to ±6.""" + z, weights = [], [] + for name, ref in REFERENCE["features"].items(): + if name not in features: + continue + if "slope" in ref and age_months and age_months > 0: + median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"] + else: + median = ref["median"] + z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9)) + weights.append(ref["weight"]) + w = np.array(weights, float) + return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6) + + +def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray: + """`wake`, `drowsy`, `sleep` or `` (not scored) per grid window.""" + starts, features = _features(prep, mask(prep, intervals)) + out = np.full(len(prep.starts), "", dtype=object) + if not starts: + return out + labels = STATES[np.digitize(depth(features, age_months), REFERENCE["cuts"])] + by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True)) + out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts] + return out + + +def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]: + """(onset s, duration s) of the slow waves of one channel.""" + y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0] + sign = np.sign(y) + sign[sign == 0] = 1 + crossings = np.flatnonzero(np.diff(sign) != 0) + 1 + waves = [] + for j, c0 in enumerate(crossings): + if not y[c0] < 0: + continue + if j + 2 >= len(crossings): + break + c1, c2 = crossings[j + 1], crossings[j + 2] + negative, total = (c1 - c0) / fs, (c2 - c0) / fs + if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0): + continue + p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1]))) + if 75.0 <= p2p <= 300.0: + waves.append((round(c0 / fs, 3), round(total, 3))) + return waves + + +def _merged(waves: list[tuple[float, float]]) -> np.ndarray: + if not waves: + return np.empty((0, 2)) + a = np.array([onset for onset, _ in waves]) + b = a + np.array([length for _, length in waves]) + order = np.argsort(a) + out = [[a[order[0]], b[order[0]]]] + for i in order[1:]: + if a[i] <= out[-1][1]: + out[-1][1] = max(out[-1][1], b[i]) + else: + out.append([a[i], b[i]]) + return np.array(out) + + +def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray: + """`N3` or `N2` per sleep window (`` elsewhere).""" + waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)] + covered = _merged(waves) + out = np.full(len(prep.starts), "", dtype=object) + for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)): + if label != "sleep": + continue + t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0 + overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None) + coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0 + out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2" + return out diff --git a/models/tea/eeg/spikes.py b/models/tea/eeg/spikes.py new file mode 100644 index 0000000..57383a7 --- /dev/null +++ b/models/tea/eeg/spikes.py @@ -0,0 +1,232 @@ +"""Paroxysmal spikes in sleep: candidates per channel, merged into discharges, counted against +the clean minutes of sleep. + +Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an +excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz +power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is +one. Each kept window adds its 2 s to the state of its midpoint. + +Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD, +20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both +flanks at least 6 x the MAD of the channel's slope; inside a kept window. Its field is the +number of 10-20 neighbours with a same-sign candidate within 25 ms. + +Discharge: candidates closer than 180 ms are one; the largest (in MADs) gives its channel, state +and width. A useful discharge has field and is not a vertex wave (asleep, max on Cz/Fz/Pz, a +slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on +Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair). + +Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode +(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals. +""" + +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +from models.tea.eeg import signals +from models.tea.eeg.checks import NEIGHBOURS +from models.tea.eeg.preprocess import WINDOW_S, Prepared +from models.tea.eeg.sleep import EXCLUDED, window_note +from models.tea.eeg.spindles import ZONES + +ELECTRODES = tuple(NEIGHBOURS) +GATE_S = 2.0 +VERTEX = ("Cz", "Fz", "Pz") +POSTS = ("O1", "O2") +OCULAR = ("Fp1", "Fp2", "F7", "F8") +POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"} +LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4")) +ASLEEP = ("N2", "N3", "sleep") + + +@dataclass(frozen=True) +class Spikes: + rate: float # useful discharges per minute of clean sleep + electrodes: dict[str, float] + zones: dict[str, float] + minutes: float # clean sleep minutes, the rate's exposure + + +def _mad(v: np.ndarray) -> float: + v = v[np.isfinite(v)] + if not len(v): + return np.nan + return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan + + +def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]: + """(start, end) s of the 2 s windows the detector reads.""" + n = int(GATE_S * fs) + top = min(45, fs / 2 * 0.9) + lines = signals.fixed_lines(x, fs, f_max=top) + f = np.fft.rfftfreq(n, 1 / fs) + taper = np.hanning(n)[:, None] + kept = [] + for a in range(0, len(x) - n + 1, n): + t0, t1 = a / fs, a / fs + GATE_S + state, mixed = window_note(t0, t1, intervals) + segment = x[a : a + n] + if not np.isfinite(segment).all() or state in EXCLUDED or mixed: + continue + power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2 + power = power.mean(axis=1) + high = signals.band_power(f, power, 20, top, lines, include_hi=True) + low = signals.band_power(f, power, 4, 13, lines, include_hi=True) + muscle = float(high / max(low, 1e-12)) + frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9)) + if not (muscle > 1.5 or frozen > 0.5): + kept.append((round(t0, 2), round(t1, 2))) + return kept + + +def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]: + """(slower flank's slope µV/s, width ms) of the transient peaking at `i`, at half height.""" + n = len(y) + if i <= 0 or i >= n - 1: + return np.nan, np.nan + w = int(500 * fs / 1000) + base = float(np.median(y[max(0, i - w) : min(n, i + w)])) + peak = float(y[i]) - base + if peak == 0.0: + return np.nan, np.nan + sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000) + a, low = i, max(0, i - reach) + while a > low and sign * (y[a] - base) >= half: + a -= 1 + b, high = i, min(n - 1, i + reach) + while b < high and sign * (y[b] - base) >= half: + b += 1 + if b <= a: + return np.nan, np.nan + rise, fall = half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs) + return float(min(rise, fall)), float((b - a) / fs * 1000.0) + + +def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]: + y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel() + if np.isfinite(y).sum() < fs * 2: + return [] + slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y) + if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad): + return [] + v = np.abs(y) + peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else [] + after = int(100 * fs / 1000), int(500 * fs / 1000) + out = [] + for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad): + slope, width = _flanks(y, int(i), fs) + if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0): + continue + if slope < 6.0 * slope_mad: + continue + a, b = int(i) + after[0], min(int(i) + after[1], len(y)) + post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0 + out.append( + dict( + channel=channel, + t=float(i) / fs, + sign=int(np.sign(y[i])), + width=width, + size=float(abs(y[i]) / amplitude_mad), + post=post, + ) + ) + return out + + +def _field(c: pd.DataFrame) -> np.ndarray: + """Per candidate, its 10-20 neighbours with a same-sign candidate within 25 ms.""" + times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])} + out = np.zeros(len(c), int) + for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)): + for other in NEIGHBOURS.get(ch, ()): + near = times.get((other, s)) + if near is None: + continue + j = np.searchsorted(near, t) + close = near[max(j - 1, 0) : j + 1] + out[k] += bool(np.any(np.abs(close - t) <= 0.025)) + return out + + +def _merge(c: pd.DataFrame) -> pd.DataFrame: + """One row per discharge: candidates closer than 180 ms.""" + c = c.iloc[np.argsort(c.t.to_numpy(), kind="quicksort")].reset_index(drop=True) + groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1) + rows = [] + for g in groups: + part = c.iloc[g] + top = c.loc[part["size"].idxmax()] + asleep = top.state in ASLEEP + signs = dict(zip(part.channel, part.sign, strict=True)) + frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR) + opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT) + vertex = asleep and top.channel in VERTEX and float(part.post.max()) > 3.0 + posts = asleep and top.channel in POSTS and top.sign > 0 and top.width > 80.0 + rows.append( + dict( + channel=top.channel, + state=top.state, + field=int(part.field.max()), + useful=not (vertex or posts or frontal_only or opposite), + ) + ) + return pd.DataFrame(rows, columns=["channel", "state", "field", "useful"]) + + +def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None: + """None with fewer than 4 10-20 channels.""" + channels = [c for c in prep.names if c in ELECTRODES] + if len(channels) < 4: + return None + fs = prep.fs + x = np.array(prep.data(channels), dtype=np.float64) + labelled = [ + (s, s + WINDOW_S, label) + for s, label in zip(prep.starts, states, strict=True) + if label in ("wake", "drowsy", "sleep") + ] + + def state_at(t: np.ndarray) -> np.ndarray: + """The state of the first labelled window holding each time.""" + out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool) + for t0, t1, label in labelled: + hit = open_ & (t0 <= t) & (t < t1) + out[hit], open_ = label, open_ & ~hit + return out + + gate = _gate(x, fs, intervals) + minutes = {} + middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate])) + for (t0, t1), state in zip(gate, middles, strict=True): + minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0 + sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",))) + counts = dict.fromkeys(channels, 0) + candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)] + if candidates and gate: + c = pd.DataFrame(candidates) + t = c.t.to_numpy(float) + inside = np.zeros(len(t), bool) + for t0, t1 in gate: + inside |= (t >= t0) & (t < t1) + c = c[inside] + if len(c): + c = c.assign(field=_field(c), state=state_at(c.t.to_numpy())) + found = _merge(c) + found = found[found.useful & (found.field > 0) & (found.state == "sleep")] + for channel, n in found.channel.value_counts().items(): + counts[channel] = int(n) + rounded = round(sleep_minutes, 2) + rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan + electrodes = { + e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan + for e in ELECTRODES + } + zones = {} + for zone, members in ZONES.items(): + present = [e for e in members if e in counts] + total = sum(counts[e] for e in present) + zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan + return Spikes(rate, electrodes, zones, round(sleep_minutes, 4)) diff --git a/models/tea/eeg/spindles.py b/models/tea/eeg/spindles.py new file mode 100644 index 0000000..e36b763 --- /dev/null +++ b/models/tea/eeg/spindles.py @@ -0,0 +1,181 @@ +"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the +sigma envelope per electrode. + +Detection runs on the frontal, central and parietal electrodes over the windows of the stage +(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets +per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median), +from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer +ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose +instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose +envelope peaks 3 x over the median. + +Density: spindles per minute and searched channel (NaN when none were found); per zone, the +zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are +one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within +the episode ± 0.25 s, over the median envelope in sleep. +""" + +from dataclasses import dataclass + +import numpy as np +from scipy.signal import hilbert, welch + +from models.tea.eeg import signals +from models.tea.eeg.preprocess import WINDOW_S, Prepared + +CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz") +SIGMA = (11.0, 16.0) +ZONES = { + "frontal_left": ("Fp1", "F3", "F7"), + "frontal_right": ("Fp2", "F4", "F8"), + "frontal_midline": ("Fz",), + "central": ("C3", "Cz", "C4"), + "parietal": ("P3", "Pz", "P4"), + "temporal_left": ("T3", "T5"), + "temporal_right": ("T4", "T6"), + "occipital": ("O1", "O2"), +} + + +@dataclass(frozen=True) +class Spindles: + events: list[tuple[float, float, str]] # (onset s, duration s, channel) + minutes: float + channels: list[str] # the channels searched (none when under a minute of the stage) + + +def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: + y = signals.bandpass(x, fs, *SIGMA) + envelope = np.abs(hilbert(np.nan_to_num(y), axis=0)) + k = max(1, int(0.2 * fs)) + envelope = np.apply_along_axis( + lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope + ) + envelope[~np.isfinite(y)] = np.nan + return y, envelope + + +def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]: + edges = np.diff(extent.astype(np.int8), prepend=0, append=0) + out = [] + for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True): + if not core[a:b].any(): + continue + if 0.5 <= (b - a) / fs <= 3.0: + out.append((int(a), int(b))) + elif (b - a) / fs > 3.0: + step = int(3.0 * fs) + for c in range(a, b, step): + e = min(c + step, b) + if 0.5 <= (e - c) / fs <= 3.0 and core[c:e].any(): + out.append((int(c), int(e))) + return out + + +def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool: + """Sigma over its flanks, and an instantaneous frequency in band.""" + if not np.isfinite(x).all(): + return False + nperseg = min(len(x), int(fs)) + f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4)) + inside = (f >= SIGMA[0]) & (f <= SIGMA[1]) + flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30)) + if not inside.any() or not flanks.any(): + return False + if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5: + return False + frequency = np.diff(np.unwrap(np.angle(hilbert(y)))) * fs / (2 * np.pi) + frequency = frequency[np.isfinite(frequency)] + in_band = frequency[(frequency >= SIGMA[0] - 1) & (frequency <= SIGMA[1] + 1)] + if len(in_band) < 0.5 * max(len(frequency), 1): + return False + return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1] + + +def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles: + """The spindles in the grid windows staged `stage`.""" + fs, n = prep.fs, int(WINDOW_S * prep.fs) + asleep = np.zeros(len(prep.x), bool) + for start, s in zip(prep.starts, staged, strict=True): + if s == stage: + a = int(round(float(start) * fs)) + asleep[a : a + n] = True + minutes = float(asleep.sum() / fs / 60) + names = prep.columns([c for c in prep.names if c in CHANNELS]) + if minutes < 1 or not names: + return Spindles([], minutes, []) + x = prep.data(names) + y, envelope = _envelope(x, fs) + events = [] + for i, name in enumerate(names): + in_stage = np.where(asleep, envelope[:, i], np.nan) + values = in_stage[np.isfinite(in_stage)] + if len(values) < fs * 30: + continue + median = float(np.median(values)) or 1e-9 + core = max(float(np.percentile(values, 95)), 3 * median) + extent = max(float(np.percentile(values, 70)), 1.6 * median) + finite = np.isfinite(in_stage) + for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs): + if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3: + events.append((round(a / fs, 3), round((b - a) / fs, 3), name)) + return Spindles(events, minutes, names) + + +def density(found: Spindles) -> tuple[float, dict[str, float]]: + """Spindles per minute and channel (rounded to 3), and per zone; NaN when none.""" + zones = dict.fromkeys(ZONES, np.nan) + if not found.events or found.minutes <= 0: + return np.nan, zones + counts = {} + for _, _, channel in found.events: + counts[channel] = counts.get(channel, 0) + 1 + for zone, electrodes in ZONES.items(): + searched = [e for e in electrodes if e in found.channels] + if searched: + total = sum(counts.get(e, 0) for e in searched) + zones[zone] = total / (found.minutes * len(searched)) + per_channel = len(found.events) / found.minutes / max(len(found.channels), 1) + return round(per_channel, 3), zones + + +def _episodes(events) -> list[list[float]]: + if not events: + return [] + a = np.array([onset for onset, _, _ in events], float) + b = a + np.array([length for _, length, _ in events], float) + order = np.argsort(a) + out = [[a[order[0]], b[order[0]]]] + for i in order[1:]: + if a[i] <= out[-1][1]: + out[-1][1] = max(out[-1][1], b[i]) + else: + out.append([a[i], b[i]]) + return out + + +def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]: + """Per spindle electrode, the envelope's median peak over episodes against its sleep median + (NaN for an absent electrode, or without spindles).""" + out = dict.fromkeys(CHANNELS, np.nan) + use = prep.columns(CHANNELS) + episodes = _episodes(found.events) + if not use or not episodes: + return out + fs = prep.fs + y = signals.bandpass(prep.data(use), fs, *SIGMA) + envelope = signals.by_runs(y, lambda run: np.abs(hilbert(run, axis=0)), int(fs)) + asleep = np.zeros(len(envelope), bool) + for start, label in zip(prep.starts, states, strict=True): + if label == "sleep": + asleep[int(start * fs) : int((start + WINDOW_S) * fs)] = True + median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0) + peaks = np.full((len(episodes), len(use)), np.nan) + for k, (t0, t1) in enumerate(episodes): + a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs)) + if b - a >= 3: + peaks[k] = np.nanmax(envelope[a:b], axis=0) + for j, name in enumerate(use): + if np.isfinite(median[j]) and median[j] > 0: + out[name] = float(np.nanmedian(peaks[:, j]) / median[j]) + return out diff --git a/models/tea/jobs.py b/models/tea/jobs.py new file mode 100644 index 0000000..e306dc5 --- /dev/null +++ b/models/tea/jobs.py @@ -0,0 +1,141 @@ +"""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.""" + +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 joblib import Parallel, delayed +from joblib.externals.loky import get_reusable_executor + +from models.tea.eeg import analysis, curves, reference +from persistance import eeg, registry, silver + +MODELS = curves.SCENARIOS +GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: _risk) + + +class Baseline(mlflow.pyfunc.PythonModel): + """An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z, + outside, p5, median and p95 out, for one of its features.""" + + def __init__(self, scenario: str, baseline: dict): + self.scenario, self.baseline = scenario, baseline + + def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: + feature = (params or {}).get("feature", "value") + rows = model_input.to_dict("records") + return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"), + r.get("age_months"), r.get("exposure")) + for r in rows]) # fmt: skip + + +def _analyze(edf: str, birth) -> tuple[str, analysis.Analysis]: + return edf, analysis.analyze(eeg.signal(edf), birth) + + +def analyze() -> int: + """Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt.""" + pending = eeg.pending() + found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"]) + for r in pending)) # fmt: skip + get_reusable_executor().shutdown(wait=True) + eeg.save_analyses(found) + silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) + 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, workers=os.cpu_count() or 4) + 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.""" + + def routine(self) -> list[str]: + return list(MODELS) + + +JOBS = Jobs() + + +def registered(name: str) -> str: + return f"tea.{name}" + + +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() + table = reference.tables(measured)[name] + baseline = curves.train(table, name) + valid = [m for m in measured if m["valid"] and m["error"] is None] + 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), + } # 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} + reports = {"technical_validation": technical, "interpretability": interpretability} + return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) + + +def score(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)) + if found is None: + return None + version, model = found + baseline = model.unwrap_python_model().baseline + scenario, label = MODELS[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) + if metric is None: + continue + exposure = ( + (one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None + ) + for part in scenario.parts: + sites = {"": metric["value"]} if part == "value" else metric[part] + prefix = "" if part == "value" else curves.PREFIX[part] + for site, value in sites.items(): + feature = "value" if part == "value" else prefix + site + if feature not in baseline: + continue + s = curves.score(baseline[feature], value, one["age_months"], exposure) + rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"], + "scenario": name, "model": label, "metric": scenario.metric, + "part": part, "site": site or None, **s}) # fmt: skip + eeg.save_scores(name, rows) + return version diff --git a/pyproject.toml b/pyproject.toml index 3db0f03..62646d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,6 +18,11 @@ dependencies = [ "scipy>=1.18.1", "joblib>=1.6.0", "lifelines>=0.30.0", + "mne>=1.13.2", + "edfio>=0.4.18", + "statsmodels>=0.15.0", + "pgmpy>=1.1.2", + "mpmath>=1.4.1", ] [build-system] diff --git a/tests/test_eeg.py b/tests/test_eeg.py new file mode 100644 index 0000000..c94fc0a --- /dev/null +++ b/tests/test_eeg.py @@ -0,0 +1,342 @@ +"""The rewritten TEA EEG analysis computes what the current one computes: for every hospital +EEG with an EDF, the same verdict, checks, metric values and per-electrode / per-zone values +(the reference tables, in the current platform's codes); and age baselines trained on our own +features of the HK1K reference cohort score each EEG as the current registered baselines did +(z, outside, p5, median, p95 of each metric, z of each electrode and zone). + +Tolerance: RTOL = 1e-9 relative (absolute below 1). Values are compared after the reference's +own storage (floats as captured); counts, texts, flags and levels exactly. The report at the +end of each test says how many compared fields are bit-identical. + +Needs the hospital database (`~/isssteleon-data/hospital_tea.db`), and for the curves the +Helsinki EDFs (`/mnt/drive/eeg-helsinki`) unless their features are cached +(`~/isssteleon-data/cache/eeg_hk1k_features.json`; `EEG_REBUILD_REFERENCE=1` measures the 223 +studies again: 10-20 min on 4 workers). The 78 hospital EEGs take about 40 s on 4 workers. +""" + +import json +import os +import sqlite3 +from concurrent.futures import ProcessPoolExecutor +from multiprocessing import get_context +from pathlib import Path + +import pandas as pd +import pytest + +pytest.importorskip("mne") +pytest.importorskip("edfio") + +from models.tea.eeg import curves, reference # noqa: E402 +from models.tea.eeg.analysis import analyze # noqa: E402 + +FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "tea" +DATA = Path.home() / "isssteleon-data" +HOSPITAL = DATA / "hospital_tea.db" +HELSINKI = Path("/mnt/drive/eeg-helsinki") +CACHE = DATA / "cache" / "eeg_hk1k_features.json" +OLD_FEATURES = DATA / "specs" / "eeg" / "hk1k_features.json" # only to check our own features +RTOL = 1e-9 +WORKERS = 4 + +pytestmark = pytest.mark.skipif(not HOSPITAL.exists(), reason="no hospital database") + +CODES = { + "RITMO_POSTERIOR": "posterior_rhythm", + "HUSOS_SUENO_N2": "spindles_n2", + "HUSOS_SUENO_N3": "spindles_n3", + "PICOS_PAROXISTICOS": "paroxysmal_spikes", + "GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient", +} +LEVELS = { + "completo": "complete", + "sin_referencia_auricular": "no_ear_reference", + "parcial": "partial", + "no_analizable": "not_analyzable", +} +ZONES = { + "frontal_izq": "frontal_left", + "frontal_der": "frontal_right", + "frontal_media": "frontal_midline", + "temporal_izq": "temporal_left", + "temporal_der": "temporal_right", +} +# The current platform's features of the HK1K studies, by our scenario's feature names. +OLD_SCENARIOS = { + "eeg-posterior-rhythm": ("posterior_rhythm|", {"value": "posterior_rhythm_hz"}), + "eeg-gradient": ("gradient|", {"value": "gradient_delta_sueno"}), + "eeg-spikes": ( + "spikes|", + { + "value": "spike_rate_nrem", + "minutes": "spike_minutes_nrem", + "electrode_": "spike_density_nrem_", + "zone_": "spike_zone_rate_nrem_", + }, + ), + **{ + f"eeg-spindles-{s}": ( + f"spindles|{s.upper()}", + {"value": "spindle_density_per_min_channel", "zone_": "spindle_zone_"}, + ) + for s in ("n2", "n3") + }, + **{ + f"eeg-spindle-topography-{s}": ( + f"spindle_topography|{s.upper()}", + {"electrode_": "topo_enh_"}, + ) + for s in ("n2", "n3") + }, +} + + +class Tally: + """Compared fields: bit-identical, within RTOL, and the mismatches.""" + + def __init__(self): + self.exact, self.close, self.wrong = 0, 0, [] + + def __call__(self, where, ours, theirs): + if isinstance(ours, bool): + ours = int(ours) + if ours is None or theirs is None or isinstance(ours, str) or isinstance(theirs, str): + ok = ours == theirs + self.exact += ok + else: + a, b = float(ours), float(theirs) + ok = a == b or abs(a - b) <= RTOL * max(1.0, abs(a), abs(b)) + self.exact += a == b + self.close += ok and a != b + if not ok: + self.wrong.append((where, ours, theirs)) + + def report(self, name): + total = self.exact + self.close + len(self.wrong) + print( + f"{name}: {total} fields, {self.exact} identical, {self.close} within {RTOL:g}, " + f"{len(self.wrong)} different" + ) + + +def _table(name): + return json.loads((FIXTURES / "tables" / f"{name}.json").read_text()) + + +def _edfs(): + with sqlite3.connect(f"file:{HOSPITAL}?mode=ro", uri=True) as con: + rows = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null") + return {key: bytes(edf) for key, edf in rows} + + +def _analysed(key_edf): + key, edf = key_edf + return key, analyze(edf) + + +@pytest.fixture(scope="module") +def analyses(): + edfs = _edfs() + with ProcessPoolExecutor(WORKERS, mp_context=get_context("spawn")) as pool: + return dict(pool.map(_analysed, [(k, edfs[k]) for k in sorted(edfs)])) + + +def test_verdicts_and_checks(analyses): + eeg = {r["eeg_id"]: r for r in _table("eeg")} + criteria = _table("eeg_criterio") + tally = Tally() + for key, a in analyses.items(): + ref = eeg[key] + assert a.error is None, (key, a.error) + pairs = { + "eeg_valido": a.valid, + "eeg_nivel": a.level, + "eeg_edad_meses": a.age_months, + "eeg_fraccion_limpia": a.clean_fraction, + "eeg_canales_malos": a.bad_channels, + "eeg_canales": a.channels, + "eeg_duracion_min": a.duration_min, + "eeg_ruido_linea_db": a.line_noise_db, + "eeg_con_sueno": a.sleep, + "eeg_error": a.error, + } + for field, ours in pairs.items(): + theirs = LEVELS[ref[field]] if field == "eeg_nivel" else ref[field] + tally((key, field), ours, theirs) + theirs = sorted( + ( + ( + r["cri_codigo"], + r["cri_electrodo"] or "", + r["cri_valor"], + LEVELS.get(r["cri_valor_texto"], r["cri_valor_texto"]), + r["cri_unidad"], + r["cri_bajo"], + r["cri_alto"], + r["cri_decisivo"], + r["cri_anormal"], + ) + for r in criteria + if r["cri_eeg_id"] == key + ), + key=lambda t: (t[0], t[1], str(t[3])), + ) + ours = sorted( + ( + ( + c["code"], + c["electrode"] or "", + c["value"], + c["text"], + c["unit"], + c["low"], + c["high"], + c["decisive"], + c["abnormal"], + ) + for c in a.checks + ), + key=lambda t: (t[0], t[1], str(t[3])), + ) + tally((key, "checks"), len(ours), len(theirs)) + for o, t in zip(ours, theirs, strict=False): + for name, x, y in zip( + ( + "code", + "electrode", + "value", + "text", + "unit", + "low", + "high", + "decisive", + "abnormal", + ), + o, + t, + strict=True, + ): + tally((key, o[0], o[1], name), x, y) + tally.report("eeg + eeg_criterio") + assert not tally.wrong, tally.wrong[:20] + + +def _reference_metrics(): + """(eeg, our code) -> (metric row, {electrode: row}, {our zone: row}).""" + electrodes, zones = {}, {} + for r in _table("eeg_metrica_electrodo"): + electrodes.setdefault(r["mel_met_id"], {})[r["mel_electrodo"]] = r + for r in _table("eeg_metrica_zona"): + zones.setdefault(r["mez_met_id"], {})[ZONES.get(r["mez_zona"], r["mez_zona"])] = r + return { + (r["met_eeg_id"], CODES[r["met_codigo"]]): ( + r, + electrodes.get(r["met_id"], {}), + zones.get(r["met_id"], {}), + ) + for r in _table("eeg_metrica") + } + + +def test_metric_values(analyses): + reference_rows = _reference_metrics() + tally = Tally() + for key, a in analyses.items(): + expected = sorted(code for k, code in reference_rows if k == key) + tally((key, "metrics"), ",".join(sorted(m.code for m in a.metrics)), ",".join(expected)) + for m in a.metrics: + row, electrodes, zones = reference_rows[key, m.code] + tally((key, m.code), m.value, row["met_valor"]) + tally( + (key, m.code, "electrodes"), + ",".join(sorted(m.electrodes)), + ",".join(sorted(electrodes)), + ) + tally((key, m.code, "zones"), ",".join(sorted(m.zones)), ",".join(sorted(zones))) + for e, v in m.electrodes.items(): + tally((key, m.code, e), v, electrodes[e]["mel_valor"]) + for z, v in m.zones.items(): + tally((key, m.code, z), v, zones[z]["mez_valor"]) + tally.report("eeg_metrica + electrodes + zones, values") + assert not tally.wrong, tally.wrong[:20] + + +def _measure_reference(): + studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv") + measured = reference.measure(studies, WORKERS) + CACHE.parent.mkdir(parents=True, exist_ok=True) + CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured})) + return measured + + +@pytest.fixture(scope="module") +def hk1k(): + if CACHE.exists() and os.environ.get("EEG_REBUILD_REFERENCE") != "1": + return json.loads(CACHE.read_text())["studies"] + if not HELSINKI.exists(): + pytest.skip("no cached HK1K features and no Helsinki EDFs") + return _measure_reference() + + +def _old_feature(feature: str, names: dict[str, str]) -> str: + """`electrode_Fp1` -> `topo_enh_Fp1`, `zone_frontal_left` -> `spindle_zone_frontal_izq`.""" + if feature in names: + return names[feature] + prefix, rest = feature.split("_", 1) + return names[prefix + "_"] + {ours: old for old, ours in ZONES.items()}.get(rest, rest) + + +def test_reference_features(hk1k): + """Our HK1K features are the current platform's (as it measured them for its baselines).""" + if not OLD_FEATURES.exists(): + pytest.skip("no captured HK1K features") + old = {s["key"]: s for s in json.loads(OLD_FEATURES.read_text())["studies"]} + tally = Tally() + assert len(hk1k) == len(old) == 223 + for study in hk1k: + theirs = old[study["key"]] + tally((study["key"], "age"), study["age_months"], theirs["age_months"]) + tally((study["key"], "valid"), study["valid"], theirs["valid"]) + for scenario, (old_name, names) in OLD_SCENARIOS.items(): + for feature, v in study["features"][scenario].items(): + old_feature = _old_feature(feature, names) + tally((study["key"], feature), v, theirs["features"][old_name][old_feature]) + tally.report("HK1K features") + assert not tally.wrong, tally.wrong[:20] + + +def test_curves(analyses, hk1k): + """Baselines trained on our HK1K features score each EEG as the registered ones did.""" + tables = reference.tables(hk1k) + assert all(len(t) == 223 for t in tables.values()) + models = {name: curves.train(table, name) for name, table in tables.items()} + json.dumps(models, allow_nan=False) # plain JSON, as MLflow logs it + reference_rows = _reference_metrics() + tally = Tally() + for key, a in analyses.items(): + for code, scored in curves.deviations(models, a).items(): + row, electrodes, zones = reference_rows[key, code] + value = scored["value"] + for ours, theirs in ( + ("z", "met_z"), + ("outside", "met_fuera"), + ("p5", "met_p5"), + ("median", "met_mediana"), + ("p95", "met_p95"), + ): + tally((key, code, ours), value[ours], row[theirs]) + for e, s in scored.get("electrodes", {}).items(): + tally((key, code, e, "z"), s["z"], electrodes[e]["mel_z"]) + for z, s in scored.get("zones", {}).items(): + tally((key, code, z, "z"), s["z"], zones[z]["mez_z"]) + tally.report("eeg_metrica z/outside/p5/median/p95 + electrode and zone z") + assert not tally.wrong, tally.wrong[:20] + + +def test_score_without_value_or_coverage(): + """No value, or an age the curve doesn't cover (too few studies anywhere): all None.""" + table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]}) + baseline = curves.train(table, "eeg-gradient")["value"] + empty = dict.fromkeys(("z", "outside", "p5", "median", "p95")) + assert curves.score(baseline, None, 25.0) == empty + assert curves.score(baseline, 2.0, 25.0) == empty diff --git a/tests/test_recurrence.py b/tests/test_recurrence.py new file mode 100644 index 0000000..a6d1132 --- /dev/null +++ b/tests/test_recurrence.py @@ -0,0 +1,223 @@ +"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two +published raw files (`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia). + +Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's +constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes +and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal +cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull +curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value +on a rounding edge may land one unit away). The fractional Weibull is not reproducible (v1 +stopped its fit on a 60-second wall clock): within FRACTIONAL_TOLERANCE of v1's curve. + +The full bootstrap (420 resampled fits, ~10 min on 8 cores) is marked `slow` and runs only +with RECURRENCE_SLOW=1; the default set takes about two minutes. +""" + +import json +import os +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from joblib.externals.loky import get_reusable_executor + +from models.cama import recurrence +from models.cama.recurrence import calculator, cohorts, curves, factors, modeling, reports + +RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia")) +V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1" +FRACTIONAL_TOLERANCE = 0.05 # max |S| difference to v1's fractional Weibull curve +FACTOR_TOLERANCE = 1.01e-4 + +pytestmark = pytest.mark.skipif( + not all((RAW / f).exists() for f in cohorts.FILES.values()), reason="no reference raw files" +) +slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset") + + +def _json(path: str): + return json.loads((V1 / path).read_text()) + + +VERSION = _json("version.json") if V1.exists() else {} +DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exists() else {} +FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else [] + + +def _raws() -> dict[str, pd.DataFrame]: + return {s: recurrence.read(s, RAW / f) for s, f in cohorts.FILES.items()} + + +@pytest.fixture(scope="module") +def prepared(): + return {s: cohorts.prepare(s, raw) for s, raw in _raws().items()} + + +@pytest.fixture(scope="module") +def fits(prepared): + found = modeling.fit(prepared, {}) + get_reusable_executor().shutdown(wait=True) + return found + + +# ---------------------------------------------------------------- comparisons + + +def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0): + assert len(mine) == len(ref) + for i, (a, b) in enumerate(zip(mine, ref, strict=True)): + assert a.keys() == b.keys(), i + for c, z in b.items(): + x = a[c] + if isinstance(z, float) and not isinstance(z, bool) and x is not None: + assert abs(x - z) <= tolerance, (i, c, x, z) + else: + assert x == z, (i, c, x, z) + + +def _auc_rows(rows: list[dict], with_bootstrap: bool) -> list[dict]: + keep = slice(None) if with_bootstrap else slice(0, 6) + return [dict(list(r.items())[keep]) for r in rows] + + +def _reference_selection(source: str) -> dict: + """v1's bootstrap selection shares, as its risk-factor table published them.""" + found = {} + for r in DEVELOPMENT["factores_riesgo"]["filas"]: + if r["cohorte"] == source and r["tipo"] == "factor de riesgo": + found.setdefault(r["horizonte_meses"], {})[r["variable"]] = r[ + "freq_seleccion_bootstrap" + ] + return found + + +def _check_figures(records: list[dict], fractional_tolerance: float): + assert [(r["cohorte"], r["escenario"]) for r in records] == [ + (r["cohorte"], r["escenario"]) for r in FIGURES + ] + for mine, ref in zip(records, FIGURES, strict=True): + fixed = ("condiciones", "n", "recaidas", "observado_hasta", "months_max", "cohorte_nombre") + assert {k: mine[k] for k in fixed} == {k: ref[k] for k in fixed} + assert mine["bootstrap_replicas"] == ref["bootstrap_replicas"] + assert mine["km"]["months"] == ref["km"]["months"] + for part in ("S", "low", "high"): + np.testing.assert_allclose(mine["km"][part], ref["km"][part], rtol=0, atol=1e-12) + got, want = mine["points"]["COMB"][part], ref["points"]["COMB"][part] + np.testing.assert_allclose(got, want, rtol=0, atol=1e-12) + np.testing.assert_allclose(mine["weibull"]["t"], ref["weibull"]["t"], rtol=0, atol=0) + np.testing.assert_allclose(mine["weibull"]["S"], ref["weibull"]["S"], rtol=0, atol=1e-12) + gap = np.nanmax(np.abs(np.subtract(mine["weibull_fractional"]["S"], + ref["weibull_fractional"]["S"]))) # fmt: skip + assert gap <= fractional_tolerance, (mine["escenario"], gap) + + +# ---------------------------------------------------------------- fast + + +def test_cohorts(prepared): + raws = _raws() + sampling = _json("rutinas/MUESTREO.json")["cohortes"] + missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"] + for source, c in prepared.items(): + assert len(c.frame) == sampling[source]["pacientes"] + assert int(c.frame["evento"].sum()) == sampling[source]["recaidas"] + assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"] + assert c.covariates == list(missing[source]) + assert cohorts.unknown_shares(c) == missing[source] + pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame) + assert prepared["metabric"].covariates == VERSION["model"]["covariates"] + + +def test_routines(prepared): + found = reports.routines(prepared, modeling.N_BOOTSTRAP) + for name, record in found.items(): + assert record == _json(f"rutinas/{name}.json"), name + + +def test_c_index_and_internal_auc(fits): + rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])] + assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False) + metrics = reports.metrics(rows) + assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k} + + +def test_saved_model(fits): + """METABRIC's terms (in order of entry), parents, and their whole-cohort refits.""" + tables = modeling.tables(fits["metabric"]) + for h, mine in tables.items(): + ref = VERSION["model"]["tables"][str(h)] + cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()} + assert {**mine, "hbn_cpt": cpt} == ref, h + frame, covariates = fits["metabric"].cohort.frame, fits["metabric"].cohort.covariates + model = recurrence.Recurrence("metabric", recurrence.HORIZONS, covariates, tables) + found = model.predict(frame.iloc[:5]) + assert list(found.columns) == ["recurrence_12m", "recurrence_36m", "recurrence_60m"] + t = tables[36] + row = frame.iloc[0] + x = np.array([float(f"{v}_{row[v]}" == term) for term in t["lr_terms"] + for v in [modeling.variable_of(term, model.covariates)]]) # fmt: skip + p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + x @ np.array(t["lr_coefficients"])))) + p_hbn = t["hbn_cpt"][tuple(row[p] for p in t["hbn_parents"])] + assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15) + + +def test_calculator(fits): + """All 60 table rows, and the 20 figures but their fractional Weibull's tolerance.""" + records, rows = [], [] + for source in recurrence.SOURCES: + found = calculator.calculator(fits[source]) + records += found[0] + rows += found[1] + get_reusable_executor().shutdown(wait=True) + table = reports.table(pd.DataFrame(rows).round(4)) + assert table["columnas"] == DEVELOPMENT["calculadora"]["columnas"] + _same_rows(table["filas"], DEVELOPMENT["calculadora"]["filas"]) + _check_figures(records, FRACTIONAL_TOLERANCE) + + +def test_risk_factors(fits): + """All 273 rows, with v1's bootstrap selection shares (the slow test computes them).""" + table = pd.concat( + [factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES], + ignore_index=True, + ) + _same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"], + FACTOR_TOLERANCE) # fmt: skip + summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)] + assert reports.table(summary) == DEVELOPMENT["escenarios_resumen"] + + +def test_fractional_weibull_reproduces_the_classic_one(): + """With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's.""" + t = np.linspace(0, 300, 61) + for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)): + np.testing.assert_allclose(curves.fractional(t, k, 1.0, 1.0, lam), + curves.weibull(t, k, lam), rtol=0, atol=1e-9) # fmt: skip + + +# ---------------------------------------------------------------- slow: the whole v1 run + + +@pytest.mark.slow +@slow +def test_train_reproduces_v1(): + model, metrics, found = recurrence.train(_raws(), bootstrap=True) + assert metrics == VERSION["metrics"] + for h in recurrence.HORIZONS: + mine = model.tables[h] + cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()} + assert {**mine, "hbn_cpt": cpt} == VERSION["model"]["tables"][str(h)] + technical = found["technical_validation"] + for name, record in technical["rutinas"].items(): + assert record == _json(f"rutinas/{name}.json"), name + tables = technical["recurrencia_desarrollo"]["tablas"] + _same_rows(tables["auc"]["filas"], DEVELOPMENT["auc"]["filas"]) + _same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"]) + _same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"], + FACTOR_TOLERANCE) # fmt: skip + assert tables["escenarios_resumen"] == DEVELOPMENT["escenarios_resumen"] + figures = found["interpretability"]["recurrencia"] + assert figures["horizons_months"] == [12, 36, 60] + _check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE) + json.dumps(found, allow_nan=False) # JSON-able as it is