TEA EEG analysis and age curves, TEA jobs; CaMa recurrence on METABRIC and SCAN-B; reference-data models and routine runs

This commit is contained in:
Roberto Treviño
2026-11-26 07:06:52 -06:00
parent e2f7e95e83
commit f305cdd044
29 changed files with 4039 additions and 15 deletions
+342
View File
@@ -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
+223
View File
@@ -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