224 lines
11 KiB
Python
224 lines
11 KiB
Python
"""What this module covers: the EEG analysis around `measure`: the baselines' deviation (`models.tea.eeg.baselines`),
|
|
and `models.eeg_analysis`: writing an analysis back to bronze, choosing the pending EEGs, and the batch with its
|
|
governance log.
|
|
|
|
Fixtures: `tea_db` and `governance_db` (empty SQLite databases); `bronze`, two patients born 2024-01-01 with one EEG
|
|
each, studied 2026-03-01 (26.0 months): `e-1` with an EDF, `e-2` without one; `curves`, a baselines stand-in whose
|
|
posterior-rhythm curve has p5/median/p95 of 5/6/7 Hz at 24 months; `fake_measure`, a `measure` that returns a valid
|
|
measurement with a 9 Hz posterior rhythm and a spindle value at Fz, without the library.
|
|
"""
|
|
import math
|
|
from datetime import date
|
|
from types import SimpleNamespace
|
|
|
|
import pandas as pd
|
|
import pytest
|
|
from sqlmodel import select
|
|
|
|
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
|
|
from models.eeg_analysis import age_months, analyze_pending, checked_settings as settings, rows, save
|
|
from models.tea.eeg.analyze import Check, Measurement, MetricValue
|
|
from models.tea.eeg.baselines import Baselines, centiles
|
|
|
|
|
|
@pytest.fixture
|
|
def curves():
|
|
"""`Baselines` whose only production version is `tea-eeg-posterior-rhythm/3`, a centile curve over 12-36 months."""
|
|
from tea.biomarkers.posterior_rhythm._baseline import CentileCurves
|
|
|
|
curve = pd.DataFrame({"edad_meses": [12.0, 24.0, 36.0], "n_efectivo": [50.0] * 3, "p5": [4.0, 5.0, 6.0],
|
|
"p25": [4.5, 5.5, 6.5], "mediana": [5.0, 6.0, 7.0], "p75": [5.5, 6.5, 7.5],
|
|
"p95": [6.0, 7.0, 8.0]})
|
|
module = SimpleNamespace(baseline=CentileCurves(curva=curve))
|
|
|
|
class Registry:
|
|
def resolve(self, domain, scenario):
|
|
if scenario != "eeg-posterior-rhythm":
|
|
raise LookupError(scenario)
|
|
return SimpleNamespace(version="3", model_uri="models:/tea-eeg-posterior-rhythm/3")
|
|
|
|
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
|
|
|
|
|
|
@pytest.fixture
|
|
def bronze(tea_db):
|
|
"""Patients 1 and 2, born 2024-01-01; EEG `e-1` (patient 1, with an EDF) and `e-2` (patient 2, without)."""
|
|
from persistance.tea import eeg_repository
|
|
|
|
with eeg_repository.open_session() as session:
|
|
session.add_all([
|
|
Pacientes(pac_id=1, pac_fecha_nacimiento=date(2024, 1, 1)),
|
|
Pacientes(pac_id=2, pac_fecha_nacimiento=date(2024, 1, 1)),
|
|
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1), eeg_estudio=b"edf", eeg_canales=99),
|
|
Eeg(eeg_id="e-2", eeg_pac_id=2, eeg_fecha_estudio=date(2026, 3, 1)),
|
|
])
|
|
session.commit()
|
|
|
|
|
|
def current(s):
|
|
"""The plan hash and module versions an analysis made now would store."""
|
|
from models.tea.eeg.analyze import pipeline, plan, versions
|
|
|
|
return plan(s)["hash"], versions(pipeline(s), s)
|
|
|
|
|
|
def fake_measure(key, edf, age, s):
|
|
"""A valid measurement of `key` with the current plan and versions: 9 Hz posterior rhythm, N2 spindles
|
|
3.0/min, 1.5 at Fz for each sleep stage's spindles, and one channel check."""
|
|
assert edf == b"edf"
|
|
values = {"RITMO_POSTERIOR": 9.0, "HUSOS_SUENO_N2": 3.0}
|
|
plan_hash, versions = current(s)
|
|
return Measurement(
|
|
key=key, age_months=age, plan_hash=plan_hash, versions=versions, valid=1, level="completo", clean_fraction=0.9,
|
|
bad_channels=1, line_db=10.0, channels=21, duration_min=20.0, asleep=1,
|
|
checks=(Check("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, True, False),
|
|
Check("dead-channel", "T3", None, "dead channel", None, None, None, False, True)),
|
|
metrics=tuple(MetricValue(m.code, values.get(m.code), {"Fz": 1.5} if m.electrodes else {})
|
|
for m in s.metrics),
|
|
)
|
|
|
|
|
|
def _all(model):
|
|
from persistance.tea import eeg_repository
|
|
|
|
with eeg_repository.open_session() as session:
|
|
return session.exec(select(model)).all()
|
|
|
|
|
|
def test_a_value_is_compared_with_the_curve_at_the_childs_age(curves):
|
|
"""Pins down: z, -1/0/+1 and the curve's p5/median/p95 come from the promoted baseline at the age given.
|
|
|
|
Fails if `deviation` reads the wrong baseline, stops interpolating the centiles at the age, or reports a
|
|
deviation for a metric without a baseline in production.
|
|
"""
|
|
d = curves.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 9.0, 24.0)
|
|
assert (d.outside, d.p5, d.median, d.p95) == (1, 5.0, 6.0, 7.0)
|
|
assert d.z == pytest.approx((9.0 - 6.0) / (1.0 / 1.645))
|
|
assert curves.deviation("eeg-spikes", "spike_rate_nrem", 1.0, 24.0) is None
|
|
assert curves.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 9.0, None).z is None
|
|
assert curves.label("eeg-posterior-rhythm") == "tea-eeg-posterior-rhythm/3"
|
|
|
|
|
|
def test_an_age_outside_the_curve_has_no_centiles(curves):
|
|
"""Pins down: no p5/median/p95 outside the ages the curve covers, as the library gives no z there.
|
|
|
|
Fails if `centiles` extrapolates the curve.
|
|
"""
|
|
baseline = curves.module("eeg-posterior-rhythm").baseline
|
|
assert centiles(baseline, 60.0) == (None, None, None)
|
|
assert centiles(baseline, 18.0)[1] == pytest.approx(5.0 + math.log(18 / 12) / math.log(2))
|
|
|
|
|
|
def test_the_age_is_completed_months_at_the_study():
|
|
"""Pins down: the age is days / 30.4375 to one decimal, and unknown without both dates or before birth.
|
|
|
|
Fails if the analysis counts ages differently from the TEA cohort.
|
|
"""
|
|
assert age_months(date(2024, 1, 1), date(2026, 3, 1), 30.4375) == 26.0
|
|
assert age_months(None, date(2026, 3, 1), 30.4375) is None
|
|
assert age_months(date(2026, 3, 2), date(2026, 3, 1), 30.4375) is None
|
|
|
|
|
|
def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves):
|
|
"""Pins down: writing an analysis sets the EEG's columns and replaces its checks, metrics and electrodes; a
|
|
second write of the same analysis leaves the same rows with the same ids.
|
|
|
|
Fails if `save` appends instead of replacing, or row ids stop deriving from the EEG and what each row is (the
|
|
silver load would then see every re-analysis as new rows).
|
|
"""
|
|
from persistance.tea import eeg_repository
|
|
|
|
m = fake_measure("e-1", b"edf", 26.0, settings())
|
|
for _ in range(2):
|
|
with eeg_repository.open_session() as session:
|
|
save(session, "e-1", rows(m, settings(), curves))
|
|
session.commit()
|
|
eeg = eeg_repository.get("e-1")
|
|
assert (eeg.eeg_valido, eeg.eeg_nivel, eeg.eeg_canales, eeg.eeg_edad_meses, eeg.eeg_plan_hash) == \
|
|
(1, "completo", 21, 26.0, current(settings())[0])
|
|
assert sorted((c.cri_codigo, c.cri_electrodo) for c in _all(EegCriterio)) == \
|
|
[("dead-channel", "T3"), ("usable-scalp", None)]
|
|
metrics = {x.met_codigo: x for x in _all(EegMetrica)}
|
|
assert len(metrics) == 5
|
|
assert (metrics["RITMO_POSTERIOR"].met_fuera, metrics["RITMO_POSTERIOR"].met_modelo) == \
|
|
(1, "tea-eeg-posterior-rhythm/3")
|
|
assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None
|
|
electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo))
|
|
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"))
|
|
|
|
|
|
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
|
|
"""Pins down: only EEGs with an EDF are analysed, the child's age goes to the measurement, each result is
|
|
logged as an `ExtractionRun`, and a second batch with the same plan, versions and baselines does nothing.
|
|
|
|
Fails if the pending selection stops skipping analysed EEGs or EEGs without an EDF, or the batch stops logging.
|
|
"""
|
|
from persistance.governance import extraction_run_repository
|
|
|
|
first = analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure)
|
|
assert (first.pending, first.valid, first.failed) == (1, 1, 0)
|
|
assert {e.eeg_id: e.eeg_edad_meses for e in _all(Eeg)} == {"e-1": 26.0, "e-2": None}
|
|
assert [(r.entity, r.entity_pk, r.estatus) for r in extraction_run_repository.list()] == \
|
|
[("eeg", "e-1", "COMPLETADA")]
|
|
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure).pending == 0
|
|
|
|
|
|
def test_a_new_baseline_in_production_makes_valid_eegs_pending(bronze, governance_db, curves):
|
|
"""Pins down: a valid EEG analysed against one baseline version is pending again once another is promoted.
|
|
|
|
Fails if the pending selection stops comparing `met_modelo` with the versions now in production.
|
|
"""
|
|
analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure)
|
|
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure).pending == 0
|
|
curves._resolved["eeg-posterior-rhythm"] = SimpleNamespace(version="4", model_uri="models:/x/4")
|
|
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure, log_runs=False).pending == 1
|
|
|
|
|
|
def test_a_failed_study_is_stored_and_not_retried(bronze, governance_db, curves):
|
|
"""Pins down: a study whose analysis failed is written with its error and logged FALLIDA, and the next batch
|
|
with the same plan and versions leaves it alone.
|
|
|
|
Fails if a failure stops being stored (the EEG would be retried on every cycle) or stops being logged.
|
|
"""
|
|
from persistance.governance import extraction_run_repository
|
|
|
|
def failed(key, edf, age, s):
|
|
plan_hash, versions = current(s)
|
|
return Measurement(key=key, age_months=age, plan_hash=plan_hash, versions=versions,
|
|
error="MemoryError: worker killed")
|
|
|
|
def never(*args):
|
|
raise AssertionError("an EEG that failed with these versions was analysed again")
|
|
|
|
summary = analyze_pending(cluster="sync", baselines=curves, measure_fn=failed)
|
|
assert (summary.pending, summary.failed) == (1, 1)
|
|
assert {e.eeg_id: e.eeg_error for e in _all(Eeg)}["e-1"] == "MemoryError: worker killed"
|
|
assert [r.estatus for r in extraction_run_repository.list()] == ["FALLIDA"]
|
|
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=never).pending == 0
|
|
|
|
|
|
def test_the_real_analysis_writes_a_synthetic_study(tea_db, governance_db, curves):
|
|
"""Pins down: the whole chain on the real library, from an EDF stored in `eeg` to its verdict, checks and
|
|
metrics in bronze, with the posterior rhythm compared with its curve.
|
|
|
|
Fails if `measure` and `store` stop agreeing on the shape of a measurement, or the batch stops reading the
|
|
stored EDF.
|
|
"""
|
|
from synth_edf import edf_bytes
|
|
|
|
from persistance.tea import eeg_repository
|
|
|
|
with eeg_repository.open_session() as session:
|
|
session.add_all([Pacientes(pac_id=1, pac_fecha_nacimiento=date(2024, 1, 1)),
|
|
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 7, 1),
|
|
eeg_estudio=edf_bytes(minutes=4))])
|
|
session.commit()
|
|
summary = analyze_pending(cluster="sync", baselines=curves)
|
|
assert (summary.valid, summary.failed) == (1, 0)
|
|
assert eeg_repository.get("e-1").eeg_con_sueno == 1
|
|
rhythm = {m.met_codigo: m for m in _all(EegMetrica)}["RITMO_POSTERIOR"]
|
|
assert rhythm.met_valor == pytest.approx(7.0, abs=0.5)
|
|
assert 6.0 < rhythm.met_mediana < 7.0 and rhythm.met_p5 < rhythm.met_valor < rhythm.met_p95
|
|
assert rhythm.met_fuera == 0
|
|
assert {c.cri_codigo for c in _all(EegCriterio)} >= {"clean-windows", "usable-scalp"}
|