Files
models/tests/test_eeg.py
T

343 lines
13 KiB
Python

"""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