diff --git a/libs/tea b/libs/tea index 05ee029..fcf8e6e 160000 --- a/libs/tea +++ b/libs/tea @@ -1 +1 @@ -Subproject commit 05ee02990c6043148d74a192d4ded074847d2fe5 +Subproject commit fcf8e6ef03b54d0c1bbd7447f0e9a9009ffe31fe diff --git a/models/__main__.py b/models/__main__.py index 1bd308e..5a0cf9c 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -171,6 +171,30 @@ def _tea_analyze(args: argparse.Namespace) -> int: return 1 if s.failed else 0 +def _tea_score_ados2(args: argparse.Namespace) -> int: + """The ADOS-2 CSS and classification from the stored item scores (`models.ados2_scoring`).""" + from models.ados2_scoring import score_pending + + s = score_pending(overwrite=args.all) + print(f"{s.evaluations} evaluations: {s.scored} scored, {s.unscored} without enough to score") + return 0 + + +def _tea_relate_ados2(args: argparse.Namespace) -> int: + """The ADOS-2 association fitted on the analysed EEGs (`models.ados2_relation`).""" + from models.ados2_relation import relate + + s = relate() + if s.unchanged: + print(f"{s.children} children: the cohort is that of {s.version}, nothing written") + elif s.version is None: + print(f"{s.children} children: no association could be estimated, nothing written") + else: + print(f"{s.version}: {s.children} children, level {s.level}, {s.associations} associations, " + f"{s.scored} patient probabilities") + return 0 + + def _tea_export_baselines(args: argparse.Namespace) -> int: """The trained age baselines as one bundle (`models.tea.eeg.bundle`).""" from models.tea.eeg.bundle import BundleError, export @@ -521,6 +545,13 @@ def build_parser() -> argparse.ArgumentParser: analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto", help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process") analyze.set_defaults(run=_tea_analyze) + score_ados2 = tea_actions.add_parser( + "score-ados2", help="compute the ADOS-2 CSS and classification from the item scores, module and age") + score_ados2.add_argument("--all", action="store_true", help="also recompute values already stored") + score_ados2.set_defaults(run=_tea_score_ados2) + relate_ados2 = tea_actions.add_parser( + "relate-ados2", help="fit the ADOS-2 association on the analysed EEGs and store it as a new version") + relate_ados2.set_defaults(run=_tea_relate_ados2) export_baselines = tea_actions.add_parser( "export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child") export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)") diff --git a/models/ados2_relation.py b/models/ados2_relation.py new file mode 100644 index 0000000..ad3dcfc --- /dev/null +++ b/models/ados2_relation.py @@ -0,0 +1,189 @@ +"""The ADOS-2 association against the TEA database: the cohort from bronze, the `tea` library's fit, and its rows in +`relacion_ados2` and `relacion_ados2_paciente`. + +The cohort is one row per child with a valid analysed EEG and an ADOS-2: the child's first valid EEG with some +predictor (its zone z and metric z, its age) and first ADOS-2 (module, item scores, CSS). Every valid EEG of those +children is then scored, so the study's EEG has its probabilities whichever EEG it is. + +A fit is a version `tea--`: the time keeps versions in order (the gold view shows the +greatest), the fingerprint is that of the scored EEGs, which of them the fit used, and the module and level. Inputs +equal to the latest version's write nothing. Versions are +written unvalidated (`rel_validado` 0) until the domain expert validates them. +""" +from __future__ import annotations + +import hashlib +import math +from dataclasses import dataclass +from datetime import datetime, timezone + +import pandas as pd +from sqlmodel import Session, col, select + +from core.tea.enums import NivelRelacionAdos2 +from core.tea.models import ( + ADOS2_ITEMS, + Ados2, + Eeg, + EegMetrica, + EegMetricaZona, + RelacionAdos2, + RelacionAdos2Paciente, +) +from models.tea.ados2.settings import Settings, settings + +VERSION_PREFIX = "tea-" +LEVELS = {"item": NivelRelacionAdos2.ITEM.value, "domain": NivelRelacionAdos2.DOMINIO.value} +ZONED = ("spikes", "spindles") + + +@dataclass +class Summary: + version: str | None = None + level: str | None = None + children: int = 0 + associations: int = 0 + scored: int = 0 + unchanged: bool = False + + +def _predictors(session: Session, eeg_ids: list[str], s: Settings) -> pd.DataFrame: + """One row per EEG with a column per predictor: `z__` and `z_`.""" + codes = {code: b for b, code in s.biomarkers.items()} + metrics = session.exec(select(EegMetrica.met_id, EegMetrica.met_eeg_id, EegMetrica.met_codigo, EegMetrica.met_z) + .where(col(EegMetrica.met_eeg_id).in_(eeg_ids)) + .where(col(EegMetrica.met_codigo).in_(list(codes)))).all() + values: dict[str, dict[str, float]] = {e: {} for e in eeg_ids} + zoned = {} + for met_id, eeg_id, code, z in metrics: + biomarker = codes[code] + if biomarker in ZONED: + zoned[met_id] = (eeg_id, biomarker) + elif z is not None: + values[eeg_id][f"z_{biomarker}"] = z + if zoned: + for met_id, zone, z in session.exec(select(EegMetricaZona.mez_met_id, EegMetricaZona.mez_zona, + EegMetricaZona.mez_z) + .where(col(EegMetricaZona.mez_met_id).in_(list(zoned)))).all(): + if z is not None: + eeg_id, biomarker = zoned[met_id] + values[eeg_id][f"z_{biomarker}_{zone}"] = z + return pd.DataFrame.from_dict(values, orient="index") + + +def cohort(session: Session, s: Settings) -> tuple[pd.DataFrame, pd.DataFrame]: + """The fit's cohort (the first valid EEG of each child with an ADOS-2) and the table to score (every valid EEG + of those children), both keyed by EEG id, in the library's columns.""" + eegs = session.exec(select(Eeg.eeg_id, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio, Eeg.eeg_edad_meses) + .where(Eeg.eeg_valido == 1).where(col(Eeg.eeg_edad_meses).is_not(None))).all() + ados = session.exec(select(Ados2).where(col(Ados2.ado_pac_id).is_not(None))).all() + first: dict[int, Ados2] = {} + for a in sorted(ados, key=lambda a: (a.ado_fecha is None, a.ado_fecha, a.ado_id)): + first.setdefault(a.ado_pac_id, a) + rows = [] + for eeg_id, pac_id, fecha, edad in eegs: + a = first.get(pac_id) + if a is None: + continue + rows.append({"key": eeg_id, "pac_id": pac_id, "fecha": fecha, "age_months": float(edad), + "ados_module": a.ado_modulo, "css": a.ado_css, + **{code: getattr(a, f"ado_{code}") for code in ADOS2_ITEMS}}) + columns = ["key", "pac_id", "fecha", "age_months", "ados_module", "css", *ADOS2_ITEMS] + scored = pd.DataFrame(rows, columns=columns) + if len(scored): + z = _predictors(session, scored["key"].tolist(), s) + scored = scored.join(z, on="key") + scored = scored.sort_values(["pac_id", "fecha", "key"], na_position="last").reset_index(drop=True) + predictors = [c for c in scored.columns if c.startswith("z_")] + with_predictors = scored[predictors].notna().any(axis=1) if predictors else pd.Series(False, index=scored.index) + fit = scored[with_predictors].drop_duplicates("pac_id").reset_index(drop=True) + return fit.drop(columns=["pac_id", "fecha"]), scored.drop(columns=["pac_id", "fecha"]) + + +def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str: + """Eight hex digits of the scored EEGs, which of them the fit used, and `module` (name, version, level); + independent of row and column order.""" + t = scored.assign(_fit=scored["key"].isin(fit["key"])) + t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True) + text = module + "\n" + t.to_csv(index=False, float_format="%.6g") + return hashlib.sha256(text.encode()).hexdigest()[:8] + + +def _latest(session: Session) -> str | None: + versions = session.exec(select(RelacionAdos2.rel_version) + .where(col(RelacionAdos2.rel_version).startswith(VERSION_PREFIX))).all() + return max(versions, default=None) + + +def _finite(value) -> float | None: + """The value as a float, or none when missing or infinite (an open interval): not every engine stores inf.""" + if value is None or pd.isna(value): + return None + value = float(value) + return value if math.isfinite(value) else None + + +def _row_id(*parts) -> str: + from models.eeg_analysis import row_id + + return row_id("relacion-ados2", *parts) + + +def rows(module, version: str, associations: pd.DataFrame, scores: pd.DataFrame, + s: Settings) -> tuple[list[RelacionAdos2], list[RelacionAdos2Paciente]]: + """The estimated associations as `relacion_ados2` rows and their scores as `relacion_ados2_paciente` rows.""" + level = LEVELS[module.fitted["level"]] + # An odds ratio rounded to 0 or never estimated is no association to show (`rel_or` is above 0). + estimated = associations[associations["odds_ratio"].astype(float) > 0] + models, ids = [], {} + for a in estimated.itertuples(): + rel_id = _row_id(version, a.biomarker, a.zone, a.outcome_code) + ids[a.biomarker, a.zone, a.outcome_code] = rel_id + models.append(RelacionAdos2( + rel_id=rel_id, rel_version=version, rel_nivel=level, rel_validado=0, + rel_n_cohorte=int(module.fitted["n"]), rel_biomarcador=s.biomarkers[a.biomarker], rel_zona=a.zone, + rel_tipo=LEVELS[a.kind], rel_resultado=a.outcome_code, rel_evento=a.event, rel_or=_finite(a.odds_ratio), + rel_ic_inf=_finite(a.ci_low), rel_ic_sup=_finite(a.ci_high), rel_q=_finite(a.q))) + patients = [] + for r in scores.itertuples(): + rel_id = ids.get((r.biomarker, r.zone, r.outcome_code)) + if rel_id is None: + continue + patients.append(RelacionAdos2Paciente( + rap_id=_row_id(rel_id, r.key), rap_rel_id=rel_id, rap_eeg_id=r.key, rap_valor_z=float(r.z), + rap_probabilidad=float(r.probability), rap_probabilidad_referencia=float(r.reference_probability))) + return models, patients + + +def _now() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def relate(*, settings_: Settings | None = None, at: datetime | None = None) -> Summary: + """Fits the association on the current cohort and writes it as a new version, unless the cohort is the latest + version's. Nothing is written when no association could be estimated.""" + from tea.pipeline import registry + + from persistance.tea import relacion_ados2_repository + + s = settings_ or settings() + with relacion_ados2_repository.open_session() as session: + fit, scored = cohort(session, s) + summary = Summary(children=len(fit)) + if not len(fit): + return summary + module = type(registry.association(s.association, s.impl))(level=s.level) + mark = fingerprint(fit, scored, f"{module.name}/{module.version}/{module.impl}/{s.level}") + latest = _latest(session) + if latest is not None and latest.endswith(f"-{mark}"): + return Summary(version=latest, children=len(fit), unchanged=True) + module.fit(fit) + version = f"{VERSION_PREFIX}{(at or _now()):%Y%m%dT%H%M%S}-{mark}" + models, patients = rows(module, version, module.associations(), module.score(scored), s) + summary.level = module.fitted["level"] + if not models: + return summary + session.add_all([*models, *patients]) + session.commit() + summary.version, summary.associations, summary.scored = version, len(models), len(patients) + return summary diff --git a/models/ados2_scoring.py b/models/ados2_scoring.py new file mode 100644 index 0000000..93c5dc8 --- /dev/null +++ b/models/ados2_scoring.py @@ -0,0 +1,61 @@ +"""The ADOS-2 CSS and classification against the TEA database: each evaluation's item scores, module, algorithm and +the child's age at the evaluation go through `tea.scoring`, and the result is written to `ado_css` and +`ado_clasificacion`. + +A value a source already gave is kept unless `overwrite` is set. An evaluation without items or module is left as +it is. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from sqlmodel import Session, select + +from core.tea.models import ADOS2_ITEMS, Ados2, Pacientes +from tea.scoring import score + +DAYS_PER_MONTH = 30.4375 + + +@dataclass +class Summary: + evaluations: int = 0 + scored: int = 0 + unscored: int = 0 + + +def age_months(born, on) -> float | None: + if born is None or on is None: + return None + return (on - born).days / DAYS_PER_MONTH + + +def score_all(session: Session, *, overwrite: bool = False) -> Summary: + """Scores every evaluation in the session's database and commits.""" + births = dict(session.exec(select(Pacientes.pac_id, Pacientes.pac_fecha_nacimiento)).all()) + summary = Summary() + for row in session.exec(select(Ados2)).all(): + summary.evaluations += 1 + if not overwrite and row.ado_css is not None and row.ado_clasificacion is not None: + continue + items = {code: getattr(row, f"ado_{code}") for code in ADOS2_ITEMS} + result = score(row.ado_modulo, items, age_months=age_months(births.get(row.ado_pac_id), row.ado_fecha), + algorithm=row.ado_algoritmo) + if result is None or (result.css is None and result.classification is None): + summary.unscored += 1 + continue + if overwrite or row.ado_css is None: + row.ado_css = result.css if result.css is not None else row.ado_css + if overwrite or row.ado_clasificacion is None: + row.ado_clasificacion = result.classification or row.ado_clasificacion + session.add(row) + summary.scored += 1 + session.commit() + return summary + + +def score_pending(*, overwrite: bool = False) -> Summary: + from persistance.tea import relacion_ados2_repository + + with relacion_ados2_repository.open_session() as session: + return score_all(session, overwrite=overwrite) diff --git a/models/eeg_analysis.py b/models/eeg_analysis.py index 191bc7f..a3b8e11 100644 --- a/models/eeg_analysis.py +++ b/models/eeg_analysis.py @@ -4,8 +4,8 @@ An EEG is pending when it has an EDF and was never analysed, or was analysed wit versions, or, being valid, against baselines other than those now in production. One that failed with the current plan and versions waits for a new one instead of failing again on every run. -Each result replaces the EEG's previous checks, metrics and electrode values in `eeg`, `eeg_criterio`, -`eeg_metrica` and `eeg_metrica_electrodo`. Row ids derive from the EEG and what each row is, so a row keeps its id +Each result replaces the EEG's previous checks, metrics, electrode and zone values in `eeg`, `eeg_criterio`, +`eeg_metrica`, `eeg_metrica_electrodo` and `eeg_metrica_zona`. Row ids derive from the EEG and what each row is, so a row keeps its id from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished. @@ -20,11 +20,11 @@ from datetime import datetime, timedelta, timezone from sqlmodel import Session, col, delete, select from core.tea.enums import MetricaEeg -from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes +from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, EegMetricaZona, Pacientes from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions from models.tea.eeg.baselines import Baselines -from models.tea.eeg.settings import Settings, settings as model_settings +from models.tea.eeg.settings import Settings, scenario_of, settings as model_settings COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo" @@ -83,6 +83,7 @@ class Rows: criteria: list[EegCriterio] metrics: list[EegMetrica] electrodes: list[EegMetricaElectrodo] + zones: list[EegMetricaZona] def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows: @@ -108,23 +109,34 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None )) by_code = {metric.code: metric for metric in s.metrics} - metrics, electrodes = [], [] + metrics, electrodes, zones = [], [], [] for value in m.metrics: metric = by_code[value.code] met_id = row_id(m.key, "metrica", value.code) - deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months) + deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months, value.exposure) used = [metric.scenario] if deviation is not None else [] for electrode, raw in sorted(value.electrodes.items()): at_electrode = None if metric.electrode_scenario: at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode, - raw, m.age_months) + raw, m.age_months, value.exposure) if at_electrode is not None and metric.electrode_scenario not in used: used.append(metric.electrode_scenario) electrodes.append(EegMetricaElectrodo( mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode, mel_valor=raw, mel_z=at_electrode.z if at_electrode else None, )) + for zone, raw in sorted(value.zones.items()): + at_zone = None + if metric.zone_scenario: + at_zone = baselines.deviation(metric.zone_scenario, metric.zone_prefix + zone, raw, m.age_months, + value.exposure) + if at_zone is not None and metric.zone_scenario not in used: + used.append(metric.zone_scenario) + zones.append(EegMetricaZona( + mez_id=row_id(m.key, "metrica", value.code, "zona", zone), mez_met_id=met_id, mez_zona=zone, + mez_valor=raw, mez_z=at_zone.z if at_zone else None, + )) metrics.append(EegMetrica( met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value, met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None, @@ -132,7 +144,7 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None met_p95=deviation.p95 if deviation else None, met_modelo=";".join(baselines.label(scenario) for scenario in used) or None, )) - return Rows(eeg, criteria, metrics, electrodes) + return Rows(eeg, criteria, metrics, electrodes, zones) def save(session: Session, eeg_id: str, new: Rows) -> None: @@ -145,10 +157,11 @@ def save(session: Session, eeg_id: str, new: Rows) -> None: session.add(eeg) metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id) session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids))) + session.exec(delete(EegMetricaZona).where(col(EegMetricaZona.mez_met_id).in_(metric_ids))) session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id)) session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id)) session.flush() - session.add_all([*new.criteria, *new.metrics, *new.electrodes]) + session.add_all([*new.criteria, *new.metrics, *new.electrodes, *new.zones]) def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings): @@ -181,7 +194,7 @@ class Summary: def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]: out = {} for m in s.metrics: - scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario] + scenarios = [scenario_of(n, m.phase) for n in m.readers] out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None return out diff --git a/models/tea/__init__.py b/models/tea/__init__.py index 179d5eb..313366c 100644 --- a/models/tea/__init__.py +++ b/models/tea/__init__.py @@ -1 +1 @@ -"""TEA's models: the EEG analysis (`eeg`).""" +"""TEA's models: the EEG analysis (`eeg`) and the ADOS-2 association (`ados2`).""" diff --git a/models/tea/ados2/__init__.py b/models/tea/ados2/__init__.py new file mode 100644 index 0000000..bdcd739 --- /dev/null +++ b/models/tea/ados2/__init__.py @@ -0,0 +1,2 @@ +"""TEA's ADOS-2 association: the `tea` library module and the metrics it reads (`model.toml`); fitted on the +database by `models.ados2_relation`.""" diff --git a/models/tea/ados2/model.toml b/models/tea/ados2/model.toml new file mode 100644 index 0000000..dc5c806 --- /dev/null +++ b/models/tea/ados2/model.toml @@ -0,0 +1,13 @@ +# The ADOS-2 association: the `tea` library's cohort-level module, and the stored EEG metric each of its biomarkers +# reads. Spike and spindle predictors are the metric's zone z (`eeg_metrica_zona`); the posterior rhythm and the +# gradient are the metric's own z (`eeg_metrica.met_z`). +association = "ados2_association" +impl = "modern" +# "auto": by item when the cohort has ADOS-2 item scores, by the CSS otherwise; or "item", "domain". +level = "auto" + +[biomarkers] +spikes = "PICOS_PAROXISTICOS" +spindles = "HUSOS_SUENO_N2" +posterior_rhythm = "RITMO_POSTERIOR" +gradient = "GRADIENTE_ANTEROPOSTERIOR" diff --git a/models/tea/ados2/settings.py b/models/tea/ados2/settings.py new file mode 100644 index 0000000..850c50c --- /dev/null +++ b/models/tea/ados2/settings.py @@ -0,0 +1,20 @@ +"""The ADOS-2 association's settings (`model.toml`): the library module, its implementation and level, and the +stored EEG metric each of its biomarkers reads.""" +import tomllib +from dataclasses import dataclass +from functools import cache +from pathlib import Path + + +@dataclass(frozen=True) +class Settings: + association: str + impl: str + level: str + biomarkers: dict[str, str] # library biomarker -> `MetricaEeg` code + + +@cache +def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings: + raw = tomllib.loads(path.read_text()) + return Settings(raw["association"], raw["impl"], raw["level"], dict(raw["biomarkers"])) diff --git a/models/tea/eeg/analyze.py b/models/tea/eeg/analyze.py index 307e06d..023f2eb 100644 --- a/models/tea/eeg/analyze.py +++ b/models/tea/eeg/analyze.py @@ -46,6 +46,8 @@ class MetricValue: code: str value: float | None electrodes: dict[str, float | None] = field(default_factory=dict) + zones: dict[str, float | None] = field(default_factory=dict) + exposure: float | None = None # what a count baseline divides the value, electrodes and zones by @dataclass(frozen=True) @@ -90,7 +92,7 @@ def processes(pipe, settings: Settings) -> list[str]: the phased biomarkers contribute only what their stage's detector requires.""" from tea.pipeline.run_study import order_for - needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n] + needs = [n for m in settings.metrics if not m.phase for n in m.readers] requires = {r for n in needs for r in pipe.module(n).requires} for phase in settings.phases: requires.update(phase_detector(pipe, phase).requires) @@ -158,22 +160,26 @@ def features(pipe, study, settings: Settings) -> Features: by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study)) out: Features = {} for m in settings.metrics: - for biomarker in (m.biomarker, m.electrodes): - if biomarker and (biomarker, m.phase) not in out: + for biomarker in m.readers: + if (biomarker, m.phase) not in out: out[biomarker, m.phase] = {k: _number(v) for k, v in pipe.module(biomarker).measure(by_phase[m.phase]).items()} return out +def _prefixed(measured: Features, biomarker: str | None, phase: str | None, prefix: str) -> dict[str, float | None]: + """The features of `biomarker` whose name starts with `prefix`, by the rest of the name.""" + if not biomarker: + return {} + return {name.removeprefix(prefix): v for name, v in measured[biomarker, phase].items() if name.startswith(prefix)} + + def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]: - out = [] - for m in settings.metrics: - electrodes = {} - if m.electrodes: - electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items() - if name.startswith(m.electrode_prefix)} - out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes)) - return tuple(out) + return tuple(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), + _prefixed(measured, m.electrodes, m.phase, m.electrode_prefix), + _prefixed(measured, m.zones, m.phase, m.zone_prefix), + measured[m.biomarker, m.phase].get(m.exposure) if m.exposure else None) + for m in settings.metrics) def _error(exc: Exception) -> str: diff --git a/models/tea/eeg/baselines.py b/models/tea/eeg/baselines.py index d9a351d..d123bf1 100644 --- a/models/tea/eeg/baselines.py +++ b/models/tea/eeg/baselines.py @@ -47,9 +47,15 @@ def _load(model_uri: str): sys.path[:] = path +def _takes_exposure(baseline) -> bool: + import inspect + + return "exposure" in inspect.signature(baseline.deviation).parameters + + def _feature_baseline(module, feature: str): baselines = getattr(module, "baselines", None) - return baselines[feature] if baselines is not None else module.baseline + return baselines.get(feature) if baselines is not None else module.baseline def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]: @@ -103,16 +109,30 @@ class Baselines: self._loaded[scenario] = _load(resolved.model_uri) return self._loaded[scenario] - def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None: + def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None, + exposure: float | None = None) -> Deviation | None: """None without a baseline in production; with one, a deviation whose fields are null where the value or - the age is missing or the curve doesn't cover the age.""" + the age is missing or the curve doesn't cover the age. `exposure` reaches a baseline that takes one (a count + against its minutes), whose p5, median and p95 are then the rates expected in those minutes; the others + ignore it.""" module = self.module(scenario) if module is None: return None baseline = _feature_baseline(module, feature) + if baseline is None: + return None if value is None or age_months is None: return Deviation(None, None, None, None, None) - outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float)) + args = (np.array([value], float), np.array([age_months], float)) + minutes = np.array([np.nan if exposure is None else exposure], float) + if _takes_exposure(baseline): + outside, z = baseline.deviation(*args, exposure=minutes) + else: + outside, z = baseline.deviation(*args) z_value = _number(z[0]) - p5, median, p95 = centiles(baseline, age_months) - return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95) + if hasattr(baseline, "percentiles"): + p5, median, p95 = (_number(v) for v in baseline.percentiles(args[1], minutes)[0]) + else: + p5, median, p95 = centiles(baseline, age_months) + outside_value = _number(outside[0]) + return Deviation(z_value, int(outside_value) if outside_value is not None else None, p5, median, p95) diff --git a/models/tea/eeg/model.toml b/models/tea/eeg/model.toml index 86ebb84..241febf 100644 --- a/models/tea/eeg/model.toml +++ b/models/tea/eeg/model.toml @@ -18,7 +18,10 @@ line_hz = 50.0 ages = [16.0, 36.0] # One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the -# biomarker whose `` features are the metric's value per 10-20 electrode. +# biomarker whose `` features are the metric's value per 10-20 electrode, and `zones` the +# one whose `` features are its value per scalp zone (`tea.contracts.ZONES`), which the ADOS-2 +# association reads. `exposure` names the feature a count baseline divides by: spikes are counted against the +# minutes they were looked for in, since most children of the reference have none. # The feature each metric maps to is provisional until the domain expert confirms it. [[metrics]] code = "RITMO_POSTERIOR" @@ -32,6 +35,8 @@ phase = "N2" feature = "spindle_density_per_min_channel" electrodes = "spindle_topography" electrode_prefix = "topo_enh_" +zones = "spindles" +zone_prefix = "spindle_zone_" [[metrics]] code = "HUSOS_SUENO_N3" @@ -40,11 +45,18 @@ phase = "N3" feature = "spindle_density_per_min_channel" electrodes = "spindle_topography" electrode_prefix = "topo_enh_" +zones = "spindles" +zone_prefix = "spindle_zone_" [[metrics]] code = "PICOS_PAROXISTICOS" biomarker = "spikes" feature = "spike_rate_nrem" +electrodes = "spikes" +electrode_prefix = "spike_density_nrem_" +zones = "spikes" +zone_prefix = "spike_zone_rate_nrem_" +exposure = "spike_minutes_nrem" [[metrics]] code = "GRADIENTE_ANTEROPOSTERIOR" diff --git a/models/tea/eeg/settings.py b/models/tea/eeg/settings.py index 600bb86..5d08340 100644 --- a/models/tea/eeg/settings.py +++ b/models/tea/eeg/settings.py @@ -17,6 +17,9 @@ class Metric: phase: str | None = None electrodes: str | None = None electrode_prefix: str = "" + zones: str | None = None + zone_prefix: str = "" + exposure: str | None = None # the biomarker's feature a count baseline divides by (its minutes) @property def scenario(self) -> str: @@ -26,6 +29,15 @@ class Metric: def electrode_scenario(self) -> str | None: return scenario_of(self.electrodes, self.phase) if self.electrodes else None + @property + def zone_scenario(self) -> str | None: + return scenario_of(self.zones, self.phase) if self.zones else None + + @property + def readers(self) -> tuple[str, ...]: + """The biomarkers the metric reads: its own, its electrodes' and its zones'.""" + return tuple(dict.fromkeys(n for n in (self.biomarker, self.electrodes, self.zones) if n)) + @dataclass(frozen=True) class Reference: @@ -55,13 +67,13 @@ class Settings: @property def scenarios(self) -> dict[str, tuple[str, str | None]]: """Each baseline to train, by scenario: (biomarker, sleep stage).""" - pairs = [(n, m.phase) for m in self.metrics for n in (m.biomarker, m.electrodes) if n] + pairs = [(n, m.phase) for m in self.metrics for n in m.readers] return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)} @property def biomarkers(self) -> tuple[str, ...]: - """Every biomarker a metric reads, its own or its electrodes'.""" - names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n] + """Every biomarker a metric reads, its own, its electrodes' or its zones'.""" + names = [n for m in self.metrics for n in m.readers] return tuple(dict.fromkeys(names)) diff --git a/tests/tea/ados2_cohort.py b/tests/tea/ados2_cohort.py new file mode 100644 index 0000000..078b855 --- /dev/null +++ b/tests/tea/ados2_cohort.py @@ -0,0 +1,35 @@ +"""An invented ADOS-2 association cohort: one row per child in the `tea` library's cohort columns, with two planted +effects (spikes in temporal_izq raise item 18, spindles in central lower the CSS) and everything else null.""" +import numpy as np +import pandas as pd + +from tea.associations.ados2 import _items as items +from tea.contracts import ZONES + +ITEM_CODES = sorted({c for _, _, codes in items.ITEMS.values() for c in codes.values()}) + + +def cohort(n: int = 60, seed: int = 4, with_items: bool = True) -> pd.DataFrame: + rng = np.random.default_rng(seed) + age = rng.uniform(16, 37, n).round(1) + module = np.where(age < 31, "TODDLER", np.where(rng.random(n) < .7, "MODULO_1", "MODULO_2")) + t = pd.DataFrame({"key": [f"e-{i:03d}" for i in range(n)], "age_months": age, "ados_module": module}) + shared = rng.normal(0, 1, n) + for zone in ZONES: + t[f"z_spikes_{zone}"] = (.5 * shared + .85 * rng.normal(0, 1, n)).round(3) + t[f"z_spindles_{zone}"] = rng.normal(0, 1, n).round(3) + t["z_posterior_rhythm"] = rng.normal(0, 1, n).round(3) + t["z_gradient"] = rng.normal(0, 1, n).round(3) + for number, (_, _, codes) in items.ITEMS.items(): + latent = rng.logistic(0, 1, n) + (1.6 * t["z_spikes_temporal_izq"].to_numpy() if number == 18 else 0) + level = np.digitize(latent, [-.3, 1.4, 3.2]) + for m, code in codes.items(): + if code not in t: + t[code] = np.nan + t.loc[t.ados_module == m, code] = level[t.ados_module.to_numpy() == m] + severity = rng.normal(0, 1, n) - .9 * t["z_spindles_central"].to_numpy() + t["css"] = np.clip(np.round(6 + 1.8 * severity), 1, 10).astype(int) + for code in ITEM_CODES: + if code not in t: + t[code] = np.nan + return t if with_items else t.drop(columns=ITEM_CODES) diff --git a/tests/tea/test_ados2_association.py b/tests/tea/test_ados2_association.py new file mode 100644 index 0000000..45415fd --- /dev/null +++ b/tests/tea/test_ados2_association.py @@ -0,0 +1,141 @@ +"""What this module covers: the `tea` library's ADOS-2 association (`tea.associations.ados2`, modern, and +`tea.legacy.associations.ados2`, the research code vendored): the pairs it tests, the module-independent outcome +codes, recovery of planted effects, legacy and modern agreeing, the per-child scores and the saved state. + +Fixtures: `cohort_items`, 60 invented children of 16 to 37 months (Toddler module under 31 months, Module 1 or 2 +above) with item scores and a CSS, whose spike z in temporal_izq raises item 18 (intonation) and whose spindle z in +central lowers the CSS, everything else null; `cohort_css`, the same children without item scores; `fits`, both +implementations fitted once on each cohort. +""" +import numpy as np +import pandas as pd +import pytest +from ados2_cohort import ITEM_CODES, cohort + +from tea.associations.ados2 import Ados2Association +from tea.associations.ados2 import _items as items +from tea.contracts import ASSOCIATION_COLUMNS, SCORE_COLUMNS, ZONES +from tea.legacy.associations.ados2 import LegacyAdos2Association + +@pytest.fixture(scope="module") +def cohort_items(): + """60 children with item scores: spikes in temporal_izq raise item 18, spindles in central lower the CSS.""" + return cohort() + + +@pytest.fixture(scope="module") +def cohort_css(cohort_items): + """The same children with the CSS only, as when the psychologist reports no items.""" + return cohort_items.drop(columns=[c for c in ITEM_CODES if c in cohort_items]) + + +@pytest.fixture(scope="module") +def fits(cohort_items, cohort_css): + """Modern and legacy, each fitted once on both cohorts, by (impl, level).""" + return {(impl, level): cls().fit(c) for impl, cls in (("modern", Ados2Association), + ("legacy", LegacyAdos2Association)) + for level, c in (("item", cohort_items), ("domain", cohort_css))} + + +def test_level_follows_the_cohort_and_codes_are_module_independent(fits): + """Pins down: a cohort with items is fitted by item and one without by the CSS; item outcomes carry + `ados2_item_NN` and domain outcomes `CSS`, with events `>=1` and `>=8`; zones are the library's, `posterior` + or `global`. Fails if the level stops following the data, an outcome goes back to a per-module column code (one + code is another item in another module), or a zone code leaves the shared list.""" + for impl in ("modern", "legacy"): + assert fits[impl, "item"].fitted["level"] == "item" + assert fits[impl, "domain"].fitted["level"] == "domain" + a = fits[impl, "item"].associations() + assert list(a.columns) == list(ASSOCIATION_COLUMNS) + assert set(a.outcome_code) <= {items.item_code(n) for n in items.ITEMS} | {"CSS"} + assert set(a.loc[a.kind == "item", "event"]) == {">=1"} + assert set(a.loc[a.kind == "domain", "event"]) == {">=8"} + assert set(a.zone) <= set(ZONES) | {"posterior", "global"} + assert set(fits[impl, "domain"].associations().outcome_code) == {"CSS"} + + +def test_the_planted_effects_are_found(fits): + """Pins down: the item fit finds spikes in temporal_izq raising item 18 (odds ratio above 1, q < 0.05) and the CSS + fit finds spindles in central lowering the CSS (odds ratio below 1, q < 0.05). Fails if the Firth or ordinal fit, + the item read per module, or the q values break.""" + a = fits["modern", "item"].associations().set_index(["biomarker", "zone", "outcome_code"]) + item = a.loc[("spikes", "temporal_izq", "ados2_item_18")] + assert item.odds_ratio > 1 and item.q < .05 + d = fits["modern", "domain"].associations().set_index(["biomarker", "zone", "outcome_code"]) + css = d.loc[("spindles", "central", "CSS")] + assert css.odds_ratio < 1 and css.q < .05 + + +@pytest.mark.parametrize("level", ["item", "domain"]) +def test_legacy_and_modern_agree(fits, cohort_items, cohort_css, level): + """Pins down: the modern port gives the vendored research code's odds ratios, intervals, p, q and per-child + probabilities exactly, at both levels. Fails if either side's design matrix, fit, interval search, FLIC + intercept or pair list drifts from the other.""" + cohort = cohort_items if level == "item" else cohort_css + m, legacy = fits["modern", level], fits["legacy", level] + keys = ["biomarker", "zone", "outcome_code"] + joined = m.associations().merge(legacy.associations(), on=keys, suffixes=("_m", "_l"), validate="1:1") + assert len(joined) == len(m.associations()) == len(legacy.associations()) + for c in ("odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio"): + np.testing.assert_allclose(joined[f"{c}_m"].astype(float), joined[f"{c}_l"].astype(float), rtol=1e-9) + scores = m.score(cohort).merge(legacy.score(cohort), on=["key", *keys], suffixes=("_m", "_l"), validate="1:1") + assert len(scores) == len(legacy.score(cohort)) > 0 + np.testing.assert_allclose(scores.probability_m, scores.probability_l, atol=1e-9) + np.testing.assert_allclose(scores.reference_probability_m, scores.reference_probability_l, atol=1e-9) + + +def test_an_item_is_read_from_the_column_of_the_childs_module(cohort_items): + """Pins down: item 11 (showing) is `sa_b12` in the Toddler module, `sa_b9` in Module 1 and `sa_b5` in Module 2, + and each child's score comes from its own module's column, with 3 as 2 and 7 as 0. Fails if items are read by + one column code for every module.""" + t = pd.DataFrame({"ados_module": ["TODDLER", "MODULO_1", "MODULO_2", "MODULO_2"], + "sa_b12": [1, 2, 0, 0], "sa_b9": [0, 3, 0, 0], "sa_b5": [2, 0, 7, np.nan]}) + assert items.item_scores(t, 11).tolist()[:3] == [1.0, 2.0, 0.0] + assert np.isnan(items.item_scores(t, 11).iloc[3]) + + +def test_scores_cover_only_the_modules_with_the_item_and_survive_save_and_load(fits, cohort_items, tmp_path): + """Pins down: a child is scored on an item only when its module has that item, every score row has a z and a + probability in [0, 1], and a saved and reloaded fit scores the same. Fails if scoring ignores the module, the + saved state misses what scoring needs, or the columns drift from `SCORE_COLUMNS`.""" + m = fits["modern", "item"] + scores = m.score(cohort_items) + assert list(scores.columns) == list(SCORE_COLUMNS) + modules = cohort_items.set_index("key").ados_module + item_16 = scores[scores.outcome_code == "ados2_item_16"] # Module 2 only + assert set(modules[item_16.key]) <= {"MODULO_2"} + assert scores.probability.between(0, 1).all() and scores.z.notna().all() + m.save(tmp_path) + again = Ados2Association.load(tmp_path).score(cohort_items) + pd.testing.assert_frame_equal(scores, again) + + +def test_registered_under_the_association_groups(): + """Pins down: both implementations resolve through the entry points and pass the association protocol, and + the per-study pipeline does not load them. Fails if a registration is dropped or the association lands in the + pipeline's module groups.""" + from tea.pipeline import registry + + assert registry.association("ados2_association").impl == "modern" + assert registry.association("ados2_association", "legacy").impl == "legacy" + assert "ados2_association" not in registry.available("modern") + + +def test_a_module_the_fit_never_saw_is_not_scored_as_the_reference(fits, cohort_items): + """Pins down: a child whose module was not in the pair's fit (here an unknown `MODULO_3`) gets no probability + instead of the reference module's. Fails if unseen levels fall back to all-zero indicators.""" + m = fits["modern", "domain"] + other = cohort_items.head(3).assign(ados_module="MODULO_3", key=["x-1", "x-2", "x-3"]) + assert m.score(other).empty + + +def test_a_singular_pair_or_an_infinite_z_does_not_stop_the_fit(cohort_css): + """Pins down: a predictor equal to the module indicator (a rank-deficient design) leaves that pair with a reason + and no estimate while every other pair is fitted, and an infinite z is dropped rather than fitted. Fails if a + singular information matrix aborts the whole fit, or `inf` reaches the design.""" + t = cohort_css.copy() + t["z_gradient"] = (t["ados_module"] == "TODDLER").astype(float) + t.loc[0, "z_posterior_rhythm"] = np.inf + a = Ados2Association().fit(t).associations().set_index(["biomarker", "zone"]) + assert a["odds_ratio"].notna().sum() >= len(a) - 2 + assert a.loc[("posterior_rhythm", "posterior"), "n"] == len(t) - 1 diff --git a/tests/tea/test_ados2_relate.py b/tests/tea/test_ados2_relate.py new file mode 100644 index 0000000..2d4638f --- /dev/null +++ b/tests/tea/test_ados2_relate.py @@ -0,0 +1,140 @@ +"""What this module covers: the ADOS-2 association against the TEA database (`models.ados2_relation`): the cohort +it builds from bronze (first valid EEG and first ADOS-2 per child), the rows it writes to `relacion_ados2` and +`relacion_ados2_paciente`, and versions (a new cohort is a later version, the same cohort writes nothing). + +Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, the invented cohort of `ados2_cohort` without item +scores (60 children, spindles in central lowering the CSS) written to bronze: each child with an ADOS-2 and a valid +analysed EEG `e-NNN` whose metric z and zone z are the cohort's, plus a later valid EEG `e-000-b` of child 1, an +invalid EEG of child 2 and a child 99 with an EEG and no ADOS-2. +""" +from datetime import date, datetime + +import pytest +from ados2_cohort import ITEM_CODES, cohort +from sqlmodel import Session, select + +from core.tea.models import Ados2, Eeg, EegMetrica, EegMetricaZona, Pacientes, RelacionAdos2, RelacionAdos2Paciente +from models import ados2_relation as rel +from tea.contracts import ZONES + +CODES = {"spikes": "PICOS_PAROXISTICOS", "spindles": "HUSOS_SUENO_N2", "posterior_rhythm": "RITMO_POSTERIOR", + "gradient": "GRADIENTE_ANTEROPOSTERIOR"} + + +def _eeg(session, eeg_id, pac_id, row, *, studied=date(2025, 6, 1), valid=1): + session.add(Eeg(eeg_id=eeg_id, eeg_pac_id=pac_id, eeg_fecha_estudio=studied, eeg_valido=valid, + eeg_edad_meses=float(row.age_months))) + for biomarker, code in CODES.items(): + met_id = f"{eeg_id}/{code}" + zoned = biomarker in rel.ZONED + session.add(EegMetrica(met_id=met_id, met_eeg_id=eeg_id, met_codigo=code, + met_z=None if zoned else float(row[f"z_{biomarker}"]))) + if zoned: + session.add_all([EegMetricaZona(mez_id=f"{met_id}/{z}", mez_met_id=met_id, mez_zona=z, + mez_z=float(row[f"z_{biomarker}_{z}"])) for z in ZONES]) + + +def _engine(): + from persistance.db import get_tea_engine + + return get_tea_engine() + + +@pytest.fixture +def stored(tea_db): + """The CSS-only invented cohort in bronze, with the extra EEGs and child the module docstring lists.""" + t = cohort().drop(columns=ITEM_CODES) + with Session(_engine()) as s: + for i, row in t.iterrows(): + pac_id = i + 1 + s.add(Pacientes(pac_id=pac_id, pac_id_hospital=f"H-{pac_id}")) + s.add(Ados2(ado_id=f"a-{pac_id}", ado_pac_id=pac_id, ado_fecha=date(2025, 5, 1), + ado_modulo=row.ados_module, ado_css=int(row.css))) + _eeg(s, row.key, pac_id, row) + _eeg(s, "e-000-b", 1, t.iloc[0], studied=date(2025, 9, 1)) + _eeg(s, "e-001-x", 2, t.iloc[1], studied=date(2025, 3, 1), valid=0) + s.add(Pacientes(pac_id=99, pac_id_hospital="H-99")) + _eeg(s, "e-099", 99, t.iloc[2]) + s.commit() + return t + + +def _read(): + with Session(_engine()) as s: + return s.exec(select(RelacionAdos2)).all(), s.exec(select(RelacionAdos2Paciente)).all() + + +def test_a_fit_writes_one_version_of_estimated_rows_on_the_platform_codes(stored): + """Pins down: one fit writes a `tea-