Merge dev into feature/cohorts-dbt-canonical: TEA EEG analysis and baselines
Conflicts: the README keeps this branch's rows and adds TEA's; `__main__` keeps the Scenario-based commands and adds `_own_steps`; pyproject keeps the reports/ paths and adds the `eeg-reference` extra. `GIT_COMMIT_TAG` comes back in `models.io.lineage` as the name of MLflow's own tag, which `models.tea.eeg.bundle` reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
@@ -33,6 +33,13 @@ def cacu_db(tmp_path, monkeypatch):
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tea_db(tmp_path, monkeypatch):
|
||||
engine = _wire(monkeypatch, tmp_path, "tea", "core.tea.base", "TeaModel")
|
||||
yield
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mlflow_tracking(tmp_path, monkeypatch):
|
||||
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Synthetic EDF+ studies for the EEG analysis's tests: every signal is generated, nothing comes from a patient.
|
||||
|
||||
`edf_bytes(minutes=4, bad=...)` returns a file the `tea` library reads as a real study:
|
||||
- background: pink noise mixed over the head (sources weighted by distance), so neighbouring electrodes correlate;
|
||||
- wake: a posterior rhythm at `rhythm_hz`, strongest on O1 O2 P3 P4, and blinks on Fp1 Fp2;
|
||||
- sleep: frontal slow waves and 13 Hz spindles on the central and frontal electrodes;
|
||||
- EKG, EOG and the mains line; states annotated as the hospital writes them ("Paciente despierto", "Dormido");
|
||||
- `bad`: `flat` channels (no signal) or `loud` ones (eight times the amplitude).
|
||||
|
||||
Written as the hospital's converter writes them: plain labels, microvolts, one fixed range, digital ±32767.
|
||||
"""
|
||||
import tempfile
|
||||
from datetime import date, time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
EARS = ("A1", "A2")
|
||||
AUX = ("LOC", "ROC", "EKG")
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
SPINDLE = ("F3", "F4", "Fz", "C3", "C4", "Cz")
|
||||
FRONTAL = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8")
|
||||
FULL_SCALE = 4999.9
|
||||
|
||||
|
||||
def _positions():
|
||||
import mne
|
||||
|
||||
pos = mne.channels.make_standard_montage("colin27_1020").get_positions()["ch_pos"]
|
||||
return {ch: np.asarray(pos[ch], float) for ch in SCALP + list(EARS)}
|
||||
|
||||
|
||||
def _pink(rng, n, fs):
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
spec = rng.normal(size=f.size) + 1j * rng.normal(size=f.size)
|
||||
spec[1:] /= np.sqrt(f[1:])
|
||||
spec[0] = 0
|
||||
x = np.fft.irfft(spec, n)
|
||||
return x / x.std()
|
||||
|
||||
|
||||
def signals(*, fs: float, minutes: float, rhythm_hz: float, line_hz: float, bad: dict, seed: int):
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(round(minutes * 60 * fs))
|
||||
t = np.arange(n) / fs
|
||||
wake = t < t[-1] / 2
|
||||
sleep = ~wake
|
||||
pos = _positions()
|
||||
names = SCALP + list(EARS)
|
||||
src = rng.normal(size=(24, 3))
|
||||
src *= np.mean([np.linalg.norm(p) for p in pos.values()]) / np.linalg.norm(src, axis=1, keepdims=True)
|
||||
sources = np.stack([_pink(rng, n, fs) for _ in range(len(src))])
|
||||
data = {}
|
||||
for ch in names:
|
||||
w = np.exp(-np.linalg.norm(src - pos[ch], axis=1) / 0.04)
|
||||
w /= w.sum()
|
||||
data[ch] = 18.0 * (w @ sources) / np.sqrt((w ** 2).sum()) / np.sqrt(len(src)) * 3 + 4.0 * _pink(rng, n, fs)
|
||||
|
||||
alpha = np.sin(2 * np.pi * rhythm_hz * t + rng.uniform(0, 2 * np.pi))
|
||||
for ch in names:
|
||||
y = pos[ch][1]
|
||||
amp = 30.0 if ch in POSTERIOR else 12.0 * np.exp(-(y + 0.05) * 25) if y < 0.05 else 3.0
|
||||
data[ch] += amp * alpha * wake
|
||||
|
||||
slow = np.zeros(n)
|
||||
k = 0
|
||||
while k < n:
|
||||
length = int(fs * rng.uniform(0.8, 1.6))
|
||||
if k + length < n and sleep[k]:
|
||||
slow[k:k + length] = -rng.uniform(80, 200) * np.sin(np.pi * np.arange(length) / length)
|
||||
k += length + int(fs * rng.uniform(0.2, 1.5))
|
||||
spindles = np.zeros(n)
|
||||
for c in np.arange(5.0, n / fs, 8.0):
|
||||
i0 = int(c * fs)
|
||||
if i0 < n and sleep[i0]:
|
||||
length = int(fs * rng.uniform(0.6, 1.8))
|
||||
tt = np.arange(length) / fs
|
||||
seg = 35.0 * np.exp(-0.5 * ((tt - tt[-1] / 2) / (tt[-1] / 5)) ** 2) * np.sin(2 * np.pi * 13.0 * tt)
|
||||
spindles[i0:i0 + length] += seg[: max(0, min(length, n - i0))]
|
||||
for ch in names:
|
||||
data[ch] += slow if ch in FRONTAL else 0.6 * slow if ch in SPINDLE else 0
|
||||
if ch in SPINDLE:
|
||||
data[ch] += spindles
|
||||
|
||||
blinks = np.zeros(n)
|
||||
for c in np.arange(2.0, n / fs, 4.0):
|
||||
i0, length = int((c + rng.uniform(-0.5, 0.5)) * fs), int(0.3 * fs)
|
||||
if 0 <= i0 < n - length and wake[i0]:
|
||||
blinks[i0:i0 + length] += 120 * np.hanning(length)
|
||||
data["Fp1"] += blinks
|
||||
data["Fp2"] += blinks
|
||||
data["LOC"] = 0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
|
||||
data["ROC"] = -0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
|
||||
ekg = 20 * rng.normal(size=n)
|
||||
for c in np.arange(0.3, n / fs, 1 / 1.6):
|
||||
i0 = int(c * fs)
|
||||
if i0 + 10 < n:
|
||||
ekg[i0:i0 + 10] += 900 * np.hanning(10)
|
||||
data["EKG"] = ekg
|
||||
for ch in data:
|
||||
data[ch] = data[ch] + 2.0 * np.sin(2 * np.pi * line_hz * t)
|
||||
for ch in bad.get("flat", ()):
|
||||
data[ch] = rng.normal(0, 0.05, n)
|
||||
for ch in bad.get("loud", ()):
|
||||
data[ch] = data[ch] * 8
|
||||
return data, n / fs
|
||||
|
||||
|
||||
def edf_bytes(*, fs: float = 250.0, minutes: float = 4.0, rhythm_hz: float = 7.0, line_hz: float = 60.0,
|
||||
bad: dict | None = None, seed: int = 0, birthdate: date | None = None,
|
||||
startdate: date | None = None) -> bytes:
|
||||
"""`birthdate` and `startdate` go in the header; left out, it says `X` and the 01.01.85 placeholder."""
|
||||
from edfio import Edf, EdfAnnotation, EdfSignal, Patient, Recording
|
||||
|
||||
data, duration = signals(fs=fs, minutes=minutes, rhythm_hz=rhythm_hz, line_hz=line_hz, bad=bad or {}, seed=seed)
|
||||
labels = SCALP + list(EARS) + list(AUX)
|
||||
annotations = [EdfAnnotation(0.5, None, "Paciente despierto"), EdfAnnotation(duration / 2 + 0.5, None, "Dormido")]
|
||||
edf = Edf([EdfSignal(np.clip(data[ch], -FULL_SCALE, FULL_SCALE), fs, label=ch, physical_dimension="uV",
|
||||
physical_range=(-FULL_SCALE, FULL_SCALE), digital_range=(-32767, 32767)) for ch in labels],
|
||||
patient=Patient(birthdate=birthdate), recording=Recording(startdate=startdate),
|
||||
starttime=time(10, 0, 0), data_record_duration=1.0, annotations=annotations)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "study.edf"
|
||||
edf.write(path)
|
||||
return path.read_bytes()
|
||||
@@ -0,0 +1,140 @@
|
||||
"""What this module covers: the age an EEG is analysed at. The `tea` library reads it from the EDF header (recording
|
||||
start minus birth date, `header_age_months`) when no age is passed, and `measure` prefers it over the age the
|
||||
patient's rows give.
|
||||
|
||||
Fixtures: `dated` and `undated`, paths to one-minute synthetic studies (`synth_edf.py`); `dated`'s header says the
|
||||
child was born 2023-06-01 and recorded 2025-06-01 (24.0 months), `undated`'s has neither date. `measured_dated` is the
|
||||
four-minute dated study measured once, with 27.5 months from the rows.
|
||||
"""
|
||||
import logging
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from synth_edf import edf_bytes
|
||||
|
||||
from models.tea.eeg.analyze import measure, study_age
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
BORN, RECORDED = date(2023, 6, 1), date(2025, 6, 1)
|
||||
HEADER_AGE = 24.0
|
||||
ROW_AGE = 27.5
|
||||
|
||||
|
||||
def _write(tmp_path, name: str, **header) -> str:
|
||||
path = tmp_path / f"{name}.edf"
|
||||
path.write_bytes(edf_bytes(minutes=1, **header))
|
||||
return str(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dated(tmp_path):
|
||||
"""A study whose header has the birth date and the recording date."""
|
||||
return _write(tmp_path, "dated", birthdate=BORN, startdate=RECORDED)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def undated(tmp_path):
|
||||
"""A study whose header has neither date (`X` and the 01.01.85 placeholder)."""
|
||||
return _write(tmp_path, "undated")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured_dated():
|
||||
"""The dated study, four minutes long so it passes validation, measured with the rows' 27.5 months."""
|
||||
return measure("dated", edf_bytes(minutes=4, birthdate=BORN, startdate=RECORDED), ROW_AGE, settings())
|
||||
|
||||
|
||||
def test_header_age_is_start_minus_birth_in_months(dated):
|
||||
"""Pins down: the header age is (start - birth) days / 30.4375, to one decimal, like `eeg_analysis.age_months`.
|
||||
|
||||
Fails if `header_age_months` reads another header field, uses another month length or stops rounding, which
|
||||
would put the header age and the rows' age on different scales.
|
||||
"""
|
||||
from tea.contracts import header_age_months
|
||||
|
||||
assert header_age_months(dated) == HEADER_AGE
|
||||
assert header_age_months(dated, days_per_month=30.0) == round(731 / 30.0, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", [
|
||||
{},
|
||||
{"startdate": RECORDED},
|
||||
{"birthdate": BORN},
|
||||
{"birthdate": date(2025, 7, 1), "startdate": RECORDED},
|
||||
{"birthdate": date(2000, 1, 1), "startdate": RECORDED},
|
||||
], ids=["no-dates", "no-birth", "placeholder-start", "born-after-start", "over-18-years"])
|
||||
def test_header_without_a_usable_age_gives_none(tmp_path, header):
|
||||
"""Pins down: a missing birth date, the 01.01.85 placeholder start, a birth after the start and an age over 216
|
||||
months all give no header age.
|
||||
|
||||
Fails if `header_age_months` stops checking any of them: anonymised or mis-clocked files would then be analysed
|
||||
at a nonsense age instead of the rows' age.
|
||||
"""
|
||||
from tea.contracts import header_age_months
|
||||
|
||||
assert header_age_months(_write(tmp_path, "study", **header)) is None
|
||||
|
||||
|
||||
def test_recording_takes_the_header_age_unless_one_is_passed(dated):
|
||||
"""Pins down: `Recording.from_edf` without an age carries the header's, and an explicit age still wins.
|
||||
|
||||
Fails if `from_edf` stops falling back to the header, or lets the header override an age the caller passed
|
||||
(reference cohorts pass their manifest ages).
|
||||
"""
|
||||
from tea.contracts import Recording
|
||||
|
||||
assert Recording.from_edf(dated).age_months == HEADER_AGE
|
||||
assert Recording.from_edf(dated, age_months=ROW_AGE).age_months == ROW_AGE
|
||||
|
||||
|
||||
def test_preprocessing_takes_the_header_age_unless_one_is_passed(dated, undated):
|
||||
"""Pins down: modern preprocessing without an age carries the header's in `Preprocessed.age_months`, keeps an
|
||||
explicit one, and has none for a header without dates.
|
||||
|
||||
Fails if `Preprocessing.run` stops falling back to the header, which would leave the biomarkers' age baselines
|
||||
without an age for every caller that doesn't pass one.
|
||||
"""
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER, Preprocessing
|
||||
|
||||
plan = DIRECTOR_CLUSTER.to_dict()
|
||||
assert Preprocessing().run(dated, plan).age_months == HEADER_AGE
|
||||
assert Preprocessing().run(dated, plan, age_months=ROW_AGE).age_months == ROW_AGE
|
||||
assert Preprocessing().run(undated, plan).age_months is None
|
||||
|
||||
|
||||
def test_study_age_prefers_the_header_and_logs_a_disagreement(dated, caplog):
|
||||
"""Pins down: with both ages, `study_age` returns the header's and logs that the rows disagree by more than a
|
||||
month.
|
||||
|
||||
Fails if the rows' age wins again, or if a disagreement stops being logged.
|
||||
"""
|
||||
with caplog.at_level(logging.WARNING, logger="models.tea.eeg.analyze"):
|
||||
assert study_age("e1", dated, ROW_AGE, 30.4375) == HEADER_AGE
|
||||
assert "e1" in caplog.text and "24.0" in caplog.text and "27.5" in caplog.text
|
||||
caplog.clear()
|
||||
with caplog.at_level(logging.WARNING, logger="models.tea.eeg.analyze"):
|
||||
assert study_age("e1", dated, 24.3, 30.4375) == HEADER_AGE
|
||||
assert caplog.text == ""
|
||||
|
||||
|
||||
def test_study_age_falls_back_to_the_rows(undated, tmp_path):
|
||||
"""Pins down: a header without dates, or a file that isn't an EDF, gives the rows' age, which may be None.
|
||||
|
||||
Fails if `study_age` returns None, or raises, when the header has no age: EEGs from hospitals that anonymise
|
||||
their files would lose the age the platform has.
|
||||
"""
|
||||
broken = tmp_path / "broken.edf"
|
||||
broken.write_bytes(b"not an edf")
|
||||
assert study_age("e1", undated, ROW_AGE, 30.4375) == ROW_AGE
|
||||
assert study_age("e1", undated, None, 30.4375) is None
|
||||
assert study_age("e1", broken, ROW_AGE, 30.4375) == ROW_AGE
|
||||
|
||||
|
||||
def test_measure_analyses_and_reports_the_header_age(measured_dated):
|
||||
"""Pins down: `measure` on a study whose header has an age reports that age, not the rows', on a valid
|
||||
analysis; that is what `eeg_edad_meses` and the baseline deviations are written from.
|
||||
|
||||
Fails if `measure` reports the argument instead of the age it analysed at, or stops reading the header.
|
||||
"""
|
||||
m = measured_dated
|
||||
assert (m.valid, m.error, m.age_months) == (1, None, HEADER_AGE)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
|
||||
library.
|
||||
|
||||
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.
|
||||
"""
|
||||
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():
|
||||
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old."""
|
||||
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"
|
||||
@@ -0,0 +1,199 @@
|
||||
"""What this module covers: training the EEG age baselines on a cohort on the training machine's own disk
|
||||
(`models.tea.eeg.reference`), and moving the trained baselines between installations as a bundle
|
||||
(`models.tea.eeg.bundle`), with nothing per child in it.
|
||||
|
||||
Fixtures: `two_stores`, a site's MLflow store and a platform's, each a SQLite file with its own artifact folder,
|
||||
switched by the returned function; `trained`, the seven baselines trained in the site's store on a synthetic
|
||||
reference cohort with no EDF (200 children of 16 to 36 months whose features rise with age), as PROD versions.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from models.tea.eeg import bundle, train
|
||||
from models.tea.eeg.analyze import ReferenceStudy, pipeline
|
||||
from models.tea.eeg.reference import local, local_studies
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def two_stores(tmp_path, monkeypatch):
|
||||
"""`use("sitio")` or `use("plataforma")` points MLflow, and the registry, at that installation's store."""
|
||||
import mlflow
|
||||
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
def use(name: str) -> None:
|
||||
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / f"{name}-artefactos"))
|
||||
mlflow.set_tracking_uri(uri)
|
||||
|
||||
use("sitio")
|
||||
return use
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def trained(two_stores):
|
||||
"""The seven scenarios trained as PROD in the site's store; returns their versions by scenario."""
|
||||
s = settings()
|
||||
pipe = pipeline(s)
|
||||
rng = np.random.default_rng(0)
|
||||
ages = np.round(np.sort(rng.uniform(16, 36, 200)), 1)
|
||||
found = train.Listing.of("sitio", [(f"/datos/eeg/{k}.edf", float(a)) for k, a in enumerate(ages)])
|
||||
studies = [ReferenceStudy(key, age, 1, {(b, phase): {f: float(abs(1 + 0.02 * age + rng.normal(0, 0.2)))
|
||||
for f in pipe.module(b).features}
|
||||
for b, phase in s.scenarios.values()})
|
||||
for key, _, age in found.studies]
|
||||
return {k: v for k, (v, _) in train.train_all(s, "PROD", found=found, studies=studies).items()}
|
||||
|
||||
|
||||
def test_a_local_cohort_lists_its_edfs_with_the_table_or_header_age(tmp_path):
|
||||
"""Pins down: a local cohort is every EDF under its folder, at any depth, with the age of its ages table, or of
|
||||
its header without one; files without an age or outside the age range are left out.
|
||||
|
||||
Fails if a nested EDF is missed, an age outside `[reference] ages` gets in, or the header stops being the
|
||||
fallback.
|
||||
"""
|
||||
from synth_edf import edf_bytes
|
||||
|
||||
folder = tmp_path / "eeg"
|
||||
(folder / "2026").mkdir(parents=True)
|
||||
born = date(2023, 1, 1)
|
||||
(folder / "a.edf").write_bytes(edf_bytes(minutes=0.1, birthdate=born, startdate=date(2025, 1, 1))) # 24.0 m
|
||||
(folder / "2026" / "b.EDF").write_bytes(edf_bytes(minutes=0.1, birthdate=born, startdate=date(2026, 6, 1)))
|
||||
(folder / "c.edf").write_bytes(edf_bytes(minutes=0.1)) # no birth date in the header
|
||||
s = local(settings(), folder=folder, line_hz=60)
|
||||
assert [(p.split("/")[-1], a) for p, a in local_studies(s)] == [("a.edf", 24.0)] # b is 41 months
|
||||
|
||||
table = tmp_path / "edades.csv"
|
||||
table.write_text("archivo,edad_anos\na.edf,1.5\nb.EDF,2.5\nc.edf,\n")
|
||||
s = local(settings(), folder=folder, ages_table=table, line_hz=60)
|
||||
assert sorted((p.split("/")[-1], a) for p, a in local_studies(s)) == [("a.edf", 18.0), ("b.EDF", 30.0)]
|
||||
assert (s.reference.storage, s.reference.line_hz) == ("local", 60.0)
|
||||
|
||||
|
||||
def test_a_local_cohort_trains_through_the_listing(tmp_path, monkeypatch):
|
||||
"""Pins down: `listing` reads a local cohort on this machine, keyed by position, so its file names never reach
|
||||
MLflow; its hash still changes with the files.
|
||||
|
||||
Fails if the listing goes back to S3 for a local cohort, or a key carries a file name.
|
||||
"""
|
||||
from synth_edf import edf_bytes
|
||||
|
||||
folder = tmp_path / "eeg"
|
||||
folder.mkdir()
|
||||
(folder / "garcia-lopez.edf").write_bytes(edf_bytes(minutes=0.1, birthdate=date(2023, 1, 1),
|
||||
startdate=date(2025, 1, 1)))
|
||||
found = train.listing(local(settings(), folder=folder, name="sitio"), cluster="sync")
|
||||
assert [k for k, _, _ in found.studies] == ["sitio-0001"]
|
||||
assert "garcia" not in found.sha256
|
||||
|
||||
|
||||
def test_the_bundle_holds_group_numbers_only_and_imports_as_trained(trained, two_stores, tmp_path):
|
||||
"""Pins down: the bundle has every scenario's trained state, plan, routine records, metrics and tags, and no
|
||||
reference path or study key; imported into another store, each baseline is a new version with the same model
|
||||
hash, cohort and routine records, so the registry's checks pass as where it was trained, and it scores the
|
||||
analysis once promoted; importing the same bundle again registers nothing.
|
||||
|
||||
Fails if a per-study value or path reaches the bundle, the import changes the trained module, drops a promotion
|
||||
input, or duplicates versions.
|
||||
"""
|
||||
from models.io.registry import registry
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
|
||||
out = tmp_path / "baselines.zip"
|
||||
exported = bundle.export(settings(), out, environment="PROD")
|
||||
assert exported.versions == trained
|
||||
with zipfile.ZipFile(out) as z:
|
||||
names = z.namelist()
|
||||
text = b"".join(z.read(n) for n in names).decode()
|
||||
manifest = json.loads(z.read(bundle.MANIFEST))
|
||||
assert set(manifest["escenarios"]) == set(settings().scenarios)
|
||||
assert "eeg-spindles-n2/module/baseline.json" in names and "eeg-spindles-n2/rutinas/MUESTREO.json" in names
|
||||
assert "/datos/eeg" not in text and "sitio-0001" not in text
|
||||
site_sha = manifest["escenarios"]["eeg-posterior-rhythm"]["tags"]["modelo_sha"]
|
||||
|
||||
two_stores("plataforma")
|
||||
first = bundle.import_(settings(), out)
|
||||
assert all(new for _, new in first.values())
|
||||
assert bundle.import_(settings(), out) == {k: (v, False) for k, (v, _) in first.items()}
|
||||
version = first["eeg-posterior-rhythm"][0]
|
||||
mv = registry.get("tea", "eeg-posterior-rhythm", version)
|
||||
assert (mv.tags["modelo_sha"], mv.tags["cohort.source"], mv.tags[bundle.BUNDLE_TAG]) == \
|
||||
(site_sha, "referencia", exported.sha256)
|
||||
passed = {c.code for c in registry.checks("tea", "eeg-posterior-rhythm", version) if c.passed}
|
||||
assert {"ML-02", "ML-03", "ML-01a", "ML-01b"} <= passed
|
||||
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
|
||||
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
|
||||
registry.promote("tea", "eeg-posterior-rhythm", version)
|
||||
d = Baselines("tea").deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 1 + 0.02 * 26, 26.0)
|
||||
assert d is not None and d.outside == 0
|
||||
|
||||
|
||||
def _rewritten(data: bytes, change) -> bytes:
|
||||
"""The bundle with `change(files)` applied to its files (name -> bytes), the manifest kept as it was."""
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
files = {n: z.read(n) for n in z.namelist()}
|
||||
change(files)
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as z:
|
||||
for name, content in files.items():
|
||||
z.writestr(name, content)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_an_altered_bundle_is_refused(trained, two_stores, tmp_path):
|
||||
"""Pins down: the import refuses a bundle whose file changed after it was written, one with a path outside
|
||||
itself, and one whose module class, even with its manifest rewritten to match, isn't the one this platform runs
|
||||
for that scenario.
|
||||
|
||||
Fails if the import stops checking the manifest, unpacks outside its folder, or loads a class a bundle names.
|
||||
"""
|
||||
out = tmp_path / "baselines.zip"
|
||||
bundle.export(settings(), out, environment="PROD")
|
||||
data = out.read_bytes()
|
||||
two_stores("plataforma")
|
||||
|
||||
def bump(files):
|
||||
files["eeg-gradient/module/baseline.json"] += b" "
|
||||
|
||||
def escape(files):
|
||||
files["../fuera.json"] = b"{}"
|
||||
|
||||
def other_class(files):
|
||||
path = "eeg-gradient/module/module.json"
|
||||
files[path] = json.dumps({"class": "os:system"}).encode()
|
||||
manifest = json.loads(files[bundle.MANIFEST])
|
||||
manifest["escenarios"]["eeg-gradient"]["archivos"][path] = bundle._sha(files[path])
|
||||
files[bundle.MANIFEST] = json.dumps(manifest).encode()
|
||||
|
||||
for change, reason in ((bump, "changed after"), (escape, "outside itself"), (other_class, "module class")):
|
||||
target = tmp_path / f"{change.__name__}.zip"
|
||||
target.write_bytes(_rewritten(data, change))
|
||||
with pytest.raises(bundle.BundleError, match=reason):
|
||||
bundle.import_(settings(), target)
|
||||
|
||||
|
||||
def test_an_incomplete_export_is_refused(two_stores, tmp_path):
|
||||
"""Pins down: nothing is written while a scenario has no version to export.
|
||||
|
||||
Fails if a partial bundle leaves the site (the platform would score some metrics and not others).
|
||||
"""
|
||||
with pytest.raises(bundle.BundleError, match="no PROD version"):
|
||||
bundle.export(settings(), tmp_path / "baselines.zip", environment="PROD")
|
||||
assert not (tmp_path / "baselines.zip").exists()
|
||||
|
||||
|
||||
def test_run_takes_local_reference_flags_only_with_a_folder(two_stores):
|
||||
"""Pins down: the local cohort's ages and mains frequency go with its folder.
|
||||
|
||||
Fails if `--line-hz` alone is silently ignored and HK1K's 50 Hz is used for a cohort recorded at 60 Hz.
|
||||
"""
|
||||
from models.__main__ import main
|
||||
|
||||
assert main(["run", "tea", "eeg", "--train", "--line-hz", "60"]) == 2
|
||||
@@ -0,0 +1,223 @@
|
||||
"""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"}
|
||||
@@ -0,0 +1,186 @@
|
||||
"""What this module covers: the EEG age baselines (`models.tea.eeg.train`, `models.tea.eeg.model`): the reference
|
||||
listing, the training table, training and registering each scenario with what the registry's promotion checks read,
|
||||
promotion, and the analysis scoring a value with a promoted baseline.
|
||||
|
||||
Fixtures: `mlflow_tracking` (a SQLite MLflow per test); `reference`, a synthetic reference cohort with no EDF: 200
|
||||
children of 16 to 36 months whose every feature rises with age plus noise, as `ReferenceStudy` rows of each biomarker
|
||||
and sleep stage the metrics read, and the listing they'd come from.
|
||||
"""
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from models.tea.eeg import train
|
||||
from models.tea.eeg.analyze import ReferenceStudy, pipeline
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reference():
|
||||
"""(listing, studies): 200 valid children whose features are 1 + 0.02 x age + noise; one more invalid and one
|
||||
failed, which training must leave out."""
|
||||
s = settings()
|
||||
pipe = pipeline(s)
|
||||
rng = np.random.default_rng(0)
|
||||
ages = np.round(np.sort(rng.uniform(16, 36, 200)), 1)
|
||||
found = train.Listing.of("prueba", [(f"s3://prueba/{k}.edf", float(a)) for k, a in enumerate(ages)])
|
||||
studies = []
|
||||
for (key, _, age) in found.studies:
|
||||
features = {(b, phase): {f: float(abs(1 + 0.02 * age + rng.normal(0, 0.2))) for f in pipe.module(b).features}
|
||||
for b, phase in s.scenarios.values()}
|
||||
studies.append(ReferenceStudy(key, age, 1, features))
|
||||
studies += [ReferenceStudy("prueba-x", 20.0, 0), ReferenceStudy("prueba-y", 20.0, error="ValueError: boom")]
|
||||
return found, studies
|
||||
|
||||
|
||||
def test_a_listing_is_identified_by_its_studies_not_their_order():
|
||||
"""Pins down: the listing's keys are positions (no file names leave), and its hash depends on which studies and
|
||||
ages it holds, not on the order they were found in.
|
||||
|
||||
Fails if a key carries a file name, or the hash changes with the order S3 lists the files in.
|
||||
"""
|
||||
a = train.Listing.of("hk1k", [("s3://x/b.edf", 20.0), ("s3://x/a.edf", 30.0)])
|
||||
b = train.Listing.of("hk1k", [("s3://x/a.edf", 30.0), ("s3://x/b.edf", 20.0)])
|
||||
assert a == b and [k for k, _, _ in a.studies] == ["hk1k-0001", "hk1k-0002"]
|
||||
assert train.Listing.of("hk1k", [("s3://x/a.edf", 31.0), ("s3://x/b.edf", 20.0)]).sha256 != a.sha256
|
||||
|
||||
|
||||
def test_the_table_takes_only_valid_measured_studies(reference):
|
||||
"""Pins down: a baseline trains on the valid, measured studies' features of its biomarker and stage, with their
|
||||
ages. Fails if an invalid or failed study reaches a curve."""
|
||||
_, studies = reference
|
||||
data = train.table(studies, "spindles", "N2")
|
||||
assert len(data) == 200 and "age_months" in data and "spindle_density_per_min_channel" in data
|
||||
|
||||
|
||||
def test_each_scenario_is_registered_with_what_promotion_checks(mlflow_tracking, reference):
|
||||
"""Pins down: training registers every scenario as `tea-<scenario>` with its environment, the reference cohort
|
||||
(ML-03), its model hash (ML-01b), the five routine records (ML-01a) and metrics; training again on the same
|
||||
listing, plan and module versions registers nothing; and until the reports are attached, promotion is refused.
|
||||
|
||||
Fails if a scenario is missing, a promotion input stops being recorded, re-training duplicates versions, or a
|
||||
baseline reaches production without the clinical validation report.
|
||||
"""
|
||||
from models.io.registry import PromotionBlocked, registry
|
||||
|
||||
found, studies = reference
|
||||
s = settings()
|
||||
first = train.train_all(s, "PROD", found=found, studies=studies)
|
||||
assert set(first) == set(s.scenarios) and all(new for _, new in first.values())
|
||||
assert train.train_all(s, "PROD", found=found, studies=[]) == {k: (v, False) for k, (v, _) in first.items()}
|
||||
|
||||
version = first["eeg-posterior-rhythm"][0]
|
||||
checks = {(c.code, c.requirement): c for c in registry.checks("tea", "eeg-posterior-rhythm", version)}
|
||||
passed = {code for (code, _), c in checks.items() if c.passed}
|
||||
assert {"ML-02", "ML-03", "ML-01a", "ML-01b"} <= passed
|
||||
assert "listado" in checks["ML-03", "enlazada al armado de cohorte con el que se entrenó"].detail
|
||||
assert "MLD-01b" not in passed
|
||||
with pytest.raises(PromotionBlocked):
|
||||
registry.promote("tea", "eeg-posterior-rhythm", version)
|
||||
|
||||
|
||||
def test_each_baseline_keeps_its_artifacts_under_the_artifact_root(mlflow_tracking, reference, tmp_path, monkeypatch):
|
||||
"""Pins down: with `MLFLOW_ARTIFACT_ROOT` set, every scenario's run writes its model and routine records under
|
||||
that root, not in `./mlruns` of the working directory.
|
||||
|
||||
Fails if training lets `tea.serving.log_biomarker` create the experiment at MLflow's default location: in a
|
||||
container the working directory isn't the data volume, and the registered baselines would point at files that
|
||||
disappear with it.
|
||||
"""
|
||||
from mlflow import MlflowClient
|
||||
|
||||
root = tmp_path / "artefactos"
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(root))
|
||||
found, studies = reference
|
||||
trained = train.train_all(settings(), "PROD", found=found, studies=studies)
|
||||
|
||||
client = MlflowClient()
|
||||
for scenario, (version, _) in trained.items():
|
||||
run = client.get_run(client.get_model_version(f"tea-{scenario}", version).run_id)
|
||||
assert run.info.artifact_uri.startswith(str(root)), scenario
|
||||
assert any((root / f"tea-{scenario}").rglob("*.json")), scenario
|
||||
assert not (tmp_path / "mlruns").exists()
|
||||
|
||||
|
||||
def test_a_promoted_baseline_scores_the_analysis(mlflow_tracking, reference):
|
||||
"""Pins down: once its reports are attached, a baseline is promoted, and the analysis's `Baselines` loads it
|
||||
from the registry and gives a value at an age its curve covers a z, -1/0/+1 and the curve's centiles.
|
||||
|
||||
Fails if the registered model stops being the library's (the analysis couldn't load it), or promotion and the
|
||||
analysis disagree on the scenario's registered name.
|
||||
"""
|
||||
from models.io.registry import registry
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
|
||||
found, studies = reference
|
||||
s = settings()
|
||||
(version, _) = train.train_all(s, "PROD", found=found, studies=studies)["eeg-posterior-rhythm"]
|
||||
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
|
||||
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
|
||||
registry.promote("tea", "eeg-posterior-rhythm", version)
|
||||
baselines = Baselines("tea")
|
||||
median = 1 + 0.02 * 26
|
||||
d = baselines.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", median, 26.0)
|
||||
assert d is not None and abs(d.z) < 1 and d.outside == 0 and d.p5 < median < d.p95
|
||||
assert baselines.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", median + 2, 26.0).outside == 1
|
||||
assert baselines.label("eeg-posterior-rhythm") == f"tea-eeg-posterior-rhythm/{version}"
|
||||
|
||||
|
||||
def test_loading_a_baseline_leaves_the_import_path_alone(mlflow_tracking, reference):
|
||||
"""Pins down: loading a promoted baseline leaves `sys.path` as it was and `tea` the installed package, so a Dask
|
||||
worker spawned after the first batch still imports `tea.pipeline`.
|
||||
|
||||
Fails if `Baselines` loads through MLflow without restoring `sys.path`: the model's bundled partial `tea` would
|
||||
shadow the library in every worker spawned afterwards, and each of their studies would fail with
|
||||
`No module named 'tea.pipeline'`.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import tea
|
||||
|
||||
from models.io.registry import registry
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
|
||||
found, studies = reference
|
||||
(version, _) = train.train_all(settings(), "PROD", found=found, studies=studies)["eeg-posterior-rhythm"]
|
||||
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
|
||||
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
|
||||
registry.promote("tea", "eeg-posterior-rhythm", version)
|
||||
before, package = list(sys.path), tea.__file__
|
||||
|
||||
assert Baselines("tea").module("eeg-posterior-rhythm") is not None
|
||||
assert sys.path == before
|
||||
assert sys.modules["tea"].__file__ == package
|
||||
spawned = subprocess.run([sys.executable, "-c", "import sys, json; sys.path[:] = json.loads(sys.argv[1]); "
|
||||
"import tea.pipeline", __import__("json").dumps(sys.path)], capture_output=True)
|
||||
assert spawned.returncode == 0, spawned.stderr.decode()[-300:]
|
||||
|
||||
|
||||
def test_run_takes_only_train_and_promote_for_the_baselines(mlflow_tracking):
|
||||
"""Pins down: `models run tea eeg` runs the baselines' own steps: a cohort step is refused, and promoting with
|
||||
nothing trained says so and fails.
|
||||
|
||||
Fails if the scenario falls back to the cohort-file steps, which it has no file for.
|
||||
"""
|
||||
from models.__main__ import main
|
||||
|
||||
assert main(["run", "tea", "eeg", "--export"]) == 2
|
||||
assert main(["run", "tea", "eeg", "--promote"]) == 1
|
||||
|
||||
|
||||
def test_a_reference_study_is_measured_from_its_path(tmp_path):
|
||||
"""Pins down: `reference` reads a study from a path, at the cohort's mains frequency, and returns every feature
|
||||
of each biomarker and stage the metrics read.
|
||||
|
||||
Fails if the reference unit stops sharing the analysis's study (validation, processes, per-stage spindles).
|
||||
"""
|
||||
from synth_edf import edf_bytes
|
||||
|
||||
from models.tea.eeg.analyze import reference as measure_reference
|
||||
|
||||
path = tmp_path / "study.edf"
|
||||
path.write_bytes(edf_bytes(minutes=4, line_hz=50.0))
|
||||
st = measure_reference("prueba-0001", str(path), 27.0, settings(), 50.0)
|
||||
assert (st.valid, st.error) == (1, None)
|
||||
assert set(st.features) == set(settings().scenarios.values())
|
||||
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
|
||||
Reference in New Issue
Block a user