From 3669aa9eae72f929f20fb8f09d8d3d75dbc410fb Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Thu, 19 Nov 2026 19:20:29 -0600 Subject: [PATCH] TEA EEG analysis at the age the EDF header gives, the patient's rows as fallback; tea library 0.2.0 --- libs/tea | 2 +- models/tea/eeg/analyze.py | 41 +++++++++-- tests/tea/synth_edf.py | 9 ++- tests/tea/test_eeg_age.py | 140 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 181 insertions(+), 11 deletions(-) create mode 100644 tests/tea/test_eeg_age.py diff --git a/libs/tea b/libs/tea index 9cef555..05ee029 160000 --- a/libs/tea +++ b/libs/tea @@ -1 +1 @@ -Subproject commit 9cef5554d0c60dce1cdb59c4141e16ca3fc347da +Subproject commit 05ee02990c6043148d74a192d4ded074847d2fe5 diff --git a/models/tea/eeg/analyze.py b/models/tea/eeg/analyze.py index ee5a2f4..307e06d 100644 --- a/models/tea/eeg/analyze.py +++ b/models/tea/eeg/analyze.py @@ -1,11 +1,16 @@ """One EEG through the `tea` library: validation, then preprocessing, the processes and the metrics' biomarkers. -`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age, touches -no database and returns a `Measurement` with the verdict, every quality check and each metric's raw value. The -deviation from the age baselines is added afterwards (`baselines.py`), where the registered models are. +`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age the +patient's rows give, touches no database and returns a `Measurement` with the verdict, every quality check and each +metric's raw value. The deviation from the age baselines is added afterwards (`baselines.py`), where the registered +models are. + +The age is the EDF header's (recording start minus birth date) when the header has both, and the rows' otherwise: +the file is written when the study is recorded, the rows' birth date may be missing or mistyped. The library reads EDFs from paths only, so the bytes go to a temporary file for the duration of the call. """ +import logging import re import tempfile import time @@ -15,8 +20,12 @@ from types import SimpleNamespace from models.tea.eeg.settings import Settings +log = logging.getLogger(__name__) + # Channel codes the library builds from the reason's first words, and the fixed code each is stored as. CHANNEL_CODES = {"intermittent-contact-by": "intermittent-bursts"} +# Header and rows further apart than this, in months, are logged. +AGE_DISAGREEMENT_MONTHS = 1.0 @dataclass(frozen=True) @@ -42,7 +51,7 @@ class MetricValue: @dataclass(frozen=True) class Measurement: key: str - age_months: float | None + age_months: float | None # the age the study was analysed at plan_hash: str versions: str valid: int | None = None @@ -190,9 +199,26 @@ def _study(pipe, path, settings: Settings, the_plan: dict, age_months: float | N return run, summary, valid, study +def study_age(key: str, path: Path, row_age: float | None, days_per_month: float) -> float | None: + """The header's age if it has one, else `row_age`. An unreadable header counts as none: validation reports the + file.""" + from tea.contracts import header_age_months + + try: + header = header_age_months(path, days_per_month=days_per_month) + except Exception: # noqa: BLE001 + header = None + if header is None: + return row_age + if row_age is not None and abs(header - row_age) > AGE_DISAGREEMENT_MONTHS: + log.warning("EEG %s: the EDF header gives %.1f months and the patient's rows %.1f; using the header", + key, header, row_age) + return header + + def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) -> Measurement: - """Never raises: a failure is a `Measurement` with `error` set, keeping the verdict and checks if validation - finished before it.""" + """`age_months` is the rows' age, used when the EDF header has none (`study_age`). Never raises: a failure is a + `Measurement` with `error` set, keeping the verdict and checks if validation finished before it.""" started = time.time() pipe = pipeline(settings) the_plan = plan(settings) @@ -201,8 +227,9 @@ def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "study.edf" path.write_bytes(edf) + result["age_months"] = age = study_age(key, path, age_months, settings.days_per_month) validation = pipe.module("validation") - run, summary, valid, study = _study(pipe, path, settings, the_plan, age_months, settings.line_hz) + run, summary, valid, study = _study(pipe, path, settings, the_plan, age, settings.line_hz) result.update( valid=valid, level=summary.level, clean_fraction=_number(summary.clean_fraction), bad_channels=len(summary.bad_channels), line_db=_number(summary.line_db), diff --git a/tests/tea/synth_edf.py b/tests/tea/synth_edf.py index 608223e..a21c2eb 100644 --- a/tests/tea/synth_edf.py +++ b/tests/tea/synth_edf.py @@ -10,7 +10,7 @@ Written as the hospital's converter writes them: plain labels, microvolts, one fixed range, digital ±32767. """ import tempfile -from datetime import time +from datetime import date, time from pathlib import Path import numpy as np @@ -108,14 +108,17 @@ def signals(*, fs: float, minutes: float, rhythm_hz: float, line_hz: float, bad: 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) -> bytes: - from edfio import Edf, EdfAnnotation, EdfSignal + 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" diff --git a/tests/tea/test_eeg_age.py b/tests/tea/test_eeg_age.py new file mode 100644 index 0000000..41dcfa2 --- /dev/null +++ b/tests/tea/test_eeg_age.py @@ -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)