Files
models/tests/tea/test_eeg_analyze.py

193 lines
8.8 KiB
Python

"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
library, plus EEG selection and the CLI summary. Fails if explicit selection skips current studies or the CLI
stops reporting its final counts.
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
posterior channels flat; and bytes that are not an EDF. `selection_session` holds three EEG rows in SQLite.
"""
import pytest
from synth_edf import edf_bytes
from core.tea.enums import CriterioEeg, ELECTRODOS_10_20, MetricaEeg
from models.eeg_analysis import checked_settings
from models.tea.eeg.analyze import criterion_code, measure, pipeline
from models.tea.eeg.settings import scenario_of, settings
FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
@pytest.fixture(scope="module")
def measured():
"""Measure clean, flat, and broken studies to expose changes in triage and metrics."""
s = settings()
return {
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
"flat": measure("flat", edf_bytes(minutes=4, bad={"flat": FLAT}, seed=1), 27.5, s),
"broken": measure("broken", b"not an edf", None, s),
}
def test_every_metric_is_a_feature_of_its_biomarker():
"""Pins down: each `MetricaEeg` code maps to a feature the library's biomarker actually measures.
Fails if `model.toml` names a feature, biomarker or electrode prefix the library doesn't have (a renamed feature
would otherwise leave the metric null on every EEG), or leaves a `MetricaEeg` code unmapped.
"""
s = checked_settings()
pipe = pipeline(s)
assert sorted(m.code for m in s.metrics) == sorted(c.value for c in MetricaEeg)
for m in s.metrics:
assert m.feature in pipe.module(m.biomarker).features, m.code
if m.electrodes:
electrodes = [f.removeprefix(m.electrode_prefix) for f in pipe.module(m.electrodes).features
if f.startswith(m.electrode_prefix)]
assert electrodes and set(electrodes) <= set(ELECTRODOS_10_20), m.code
def test_each_baseline_has_its_own_scenario_per_sleep_stage():
"""Pins down: a biomarker's baseline is registered per sleep stage, as `eeg-<biomarker>[-<stage>]`.
Fails if the two stages' spindles share one registered model, or the naming changes without the trained models.
"""
assert scenario_of("spindle_topography", "N2") == "eeg-spindle-topography-n2"
assert scenario_of("posterior_rhythm", None) == "eeg-posterior-rhythm"
assert len({m.scenario for m in settings().metrics}) == len(settings().metrics)
def test_a_clean_study_is_valid_and_has_every_metric(measured):
"""Pins down: a clean study gets the verdict, the study-wide checks and one value per metric, with the
spindles' value per electrode, the sleep it contains and the age it was measured at.
Fails if `measure` stops running the processes the biomarkers need, drops a metric, or loses the electrodes.
"""
m = measured["clean"]
assert (m.valid, m.level, m.error, m.asleep, m.age_months) == (1, "completo", None, 1, 27.5)
assert {c.code for c in m.checks} >= {"clean-windows", "internal-coverage", "usable-scalp", "triage-level"}
assert not any(c.abnormal for c in m.checks)
values = {v.code: v for v in m.metrics}
assert set(values) == {c.value for c in MetricaEeg}
assert values["RITMO_POSTERIOR"].value == pytest.approx(7.0, abs=0.5)
assert values["HUSOS_SUENO_N2"].value > 0
assert set(values["HUSOS_SUENO_N2"].electrodes) <= set(ELECTRODOS_10_20)
assert m.plan_hash and "spindle_detection=" in m.versions
def test_flat_channels_make_the_study_not_valid_with_a_check_per_electrode(measured):
"""Pins down: a study the validator rejects keeps its checks, one per bad channel with its electrode, and has
no metrics.
Fails if a rejected study is measured anyway, or the channel checks lose their electrode or normalised code.
"""
m = measured["flat"]
assert (m.valid, m.error, m.metrics) == (0, None, ())
dead = {c.electrode for c in m.checks if c.code == CriterioEeg.CANAL_MUERTO.value}
assert dead == set(FLAT)
assert any(c.decisive and c.abnormal and c.electrode is None for c in m.checks)
def test_a_file_that_is_not_an_edf_is_not_valid_rather_than_an_error(measured):
"""Pins down: unreadable bytes are the validator's `file` check, not an analysis error.
Fails if `measure` raises, or reports the file as an error (which would retry it on every run).
"""
m = measured["broken"]
assert (m.valid, m.error) == (0, None)
assert [c.code for c in m.checks] == [CriterioEeg.ARCHIVO.value]
def test_every_check_code_is_in_the_catalog(measured):
"""Pins down: the codes `measure` stores are `CriterioEeg` values.
Fails if the library adds or rewords a check and `criterion_code` stops normalising it.
"""
codes = {c.code for m in measured.values() for c in m.checks}
assert codes <= {c.value for c in CriterioEeg}
def test_channel_codes_lose_their_numbers():
"""Pins down: the library's channel codes, which embed the measured numbers, become fixed codes.
Fails if `criterion_code` stops mapping amplitude or burst reasons, or touches the study-wide codes.
"""
assert criterion_code("amplitude-4.5-x", "amplitude 4.5 x the scalp median", "C3") == "amplitude"
assert criterion_code("amplitude-25000-uv,", "amplitude 25000 uV, out of range even for ekg", "EKG") == \
"aux-amplitude"
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
"intermittent-bursts"
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
@pytest.fixture
def selection_session():
"""Store current, pending, and EDF-less EEGs to expose scope regressions."""
from sqlmodel import Session, create_engine
from core.tea.models import Eeg
engine = create_engine("sqlite://")
Eeg.__table__.create(engine)
with Session(engine) as session:
session.add_all([
Eeg(eeg_id="1", eeg_estudio=b"edf", eeg_plan_hash="current", eeg_versiones="current", eeg_valido=0),
Eeg(eeg_id="2"),
Eeg(eeg_id="3", eeg_estudio=b"edf"),
])
session.commit()
yield session
engine.dispose()
def test_explicit_ids_select_current_edfs(selection_session):
"""Pin explicit reanalysis. Fail if current EEGs are skipped or EDF-less and unrequested rows are selected."""
from models.eeg_analysis import pending_ids
options = {"plan_hash": "current", "versions": "current", "models": dict}
assert pending_ids(selection_session, **options) == ["3"]
assert pending_ids(selection_session, ids=[2, 1, 1], **options) == ["1"]
with pytest.raises(LookupError, match=r"8, 9"):
pending_ids(selection_session, ids=[1, 9, 8], **options)
@pytest.mark.parametrize("failed", [0, 1])
def test_analyze_cli_emits_summary_and_passes_ids(monkeypatch, capsys, failed):
"""Pin the final JSON line and failure status. Fail if explicit IDs or the failed count are ignored."""
import json
from models import eeg_analysis
from models.__main__ import main
def analyze(**options):
assert options == {"everything": False, "limit": None, "ids": ["1", "2"], "cluster": "sync"}
return eeg_analysis.Summary(pending=2, valid=1, not_valid=1 - failed, failed=failed)
monkeypatch.setattr(eeg_analysis, "analyze_pending", analyze)
assert main(["tea", "analyze", "--ids", "1,2", "--cluster", "sync"]) == failed
line = capsys.readouterr().out.splitlines()[-1]
assert line.startswith("summary: ")
assert json.loads(line.removeprefix("summary: ")) == {
"pending": 2, "valid": 1, "not_valid": 1 - failed, "failed": failed,
}
def test_explicit_ids_may_be_uuids(selection_session):
"""Pin that ids are matched as strings, so the UUID ids real EEGs carry select their rows. Fail if ids go back
to being parsed as integers."""
from core.tea.models import Eeg
from models.eeg_analysis import selected_ids
uuid = "ed257fbd-61d5-4c9c-bb72-00c4ec550961"
selection_session.add(Eeg(eeg_id=uuid, eeg_estudio=b"EDF"))
selection_session.commit()
assert selected_ids(selection_session, [uuid]) == [uuid]
with pytest.raises(LookupError, match="no-such-id"):
selected_ids(selection_session, [uuid, "no-such-id"])
@pytest.mark.parametrize("other", [["--all"], ["--limit", "2"]])
def test_analyze_cli_rejects_conflicting_scope(other):
"""Pin exit 2 for ambiguous scopes. Fail if an explicit ID request can start with another scope."""
from models.__main__ import main
assert main(["tea", "analyze", "--ids", "1", *other]) == 2