From 8fd4930ca9ef56e057e9623fb951c0cc31746133 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 1 Dec 2026 00:53:27 -0600 Subject: [PATCH] T3: TEA age curves train from one training source: the site or a folder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PLAN-feature-parity ยง2.3 and user decisions 2 and 6. - jobs._cohort(source, as_of) replaces _reference: kind "site" (default) takes the valid EEGs of the children without the diagnosis by the cut-off (persistance.eeg .without_diagnosis, rebuild's ruled-out group in tea/parity's design); kind "folder" takes a folder under TEA_REFERENCE_ROOT with its EDFs and edades.csv (path, age in months), measured at the folder's mains and cached by content as before. - The legacy TEA_REFERENCE_DIR / TEA_REFERENCE_AGES path, the hk1k name and the years-to-months ages table are gone: Helsinki is one such folder. - Reports and params name the cohort (site or the folder), its digest, and the cut-off (site) or mains (folder). - definitions: Training.source (TrainingSourceConfig) replaces reference. - tests: test_tea_reference -> test_tea_training_source (folder listing and errors, the site cohort's cut-off rules). --- models/definitions.py | 19 +++--- models/tea/eeg/reference.py | 25 ++------ models/tea/jobs.py | 65 ++++++++----------- tests/test_tea_reference.py | 42 ------------- tests/test_tea_training_source.py | 101 ++++++++++++++++++++++++++++++ 5 files changed, 143 insertions(+), 109 deletions(-) delete mode 100644 tests/test_tea_reference.py create mode 100644 tests/test_tea_training_source.py diff --git a/models/definitions.py b/models/definitions.py index 70109bc..33a88fa 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -67,12 +67,13 @@ def _jobs(domain: str): raise ValueError(f"{domain} has no models") from e -class ReferenceConfig(dg.Config): - name: str +class TrainingSourceConfig(dg.Config): + kind: str = "site" + folder: str | None = None line_hz: int = 50 - def model(self) -> cluster.Reference: - return cluster.Reference(**self.model_dump()) + def model(self) -> cluster.TrainingSource: + return cluster.TrainingSource(**self.model_dump()) class Training(dg.Config): @@ -80,7 +81,7 @@ class Training(dg.Config): models: list[str] = [] # default: every model of the domain as_of: str | None = None # the date the data are taken up to (default: today) execution: ExecutionConfig = ExecutionConfig() - reference: ReferenceConfig | None = None + source: TrainingSourceConfig | None = None @dg.op @@ -89,10 +90,10 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict: jobs = _jobs(config.domain) as_of = date.fromisoformat(config.as_of) if config.as_of else None options = {} - if config.reference is not None: - if "reference" not in inspect.signature(jobs.train).parameters: - raise ValueError(f"{config.domain} models take no reference cohort") - options["reference"] = config.reference.model() + if config.source is not None: + if "source" not in inspect.signature(jobs.train).parameters: + raise ValueError(f"{config.domain} models take no training source") + options["source"] = config.source.model() found = {} with execution.running(context, config.execution.model()): for name in config.models or jobs.JOBS.routine(): diff --git a/models/tea/eeg/reference.py b/models/tea/eeg/reference.py index 9013919..396a7fb 100644 --- a/models/tea/eeg/reference.py +++ b/models/tea/eeg/reference.py @@ -1,13 +1,3 @@ -"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public), -children of 16 to 36 months, recorded on 50 Hz mains. - -`listing` pairs each EDF under a folder with its age from the cohort's table (first column the -file name, second the age in years; months = years x 12 to one decimal); keys are positions in -path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's -mains, with the table's age) in worker processes; `tables` gives each scenario's training table -from the valid studies. -""" - from pathlib import Path import pandas as pd @@ -16,21 +6,18 @@ from models import execution from models.tea.eeg.analysis import analyze from models.tea.eeg.curves import SCENARIOS -NAME = "hk1k" -MAINS_HZ = 50.0 AGES = (16.0, 36.0) def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]: - """(key, path, age in months) of each EDF with an age within `ages`.""" table = pd.read_csv(ages_table) - years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True)) + months = dict(zip(table["path"].astype(str), table["age"].astype(float), strict=True)) found = [] for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"): - age = round(float(years[path.name] * 12), 1) if path.name in years else None + age = months.get(path.relative_to(folder).as_posix()) if age is not None and age == age and ages[0] <= age <= ages[1]: - found.append((path, age)) - return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] + found.append((path, round(age, 1))) + return [(f"{Path(folder).name}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] def _one(study: tuple[str, Path, float, float]) -> dict: @@ -45,14 +32,12 @@ def _one(study: tuple[str, Path, float, float]) -> dict: } -def measure(studies, workers: int | None = None, mains_hz: float = MAINS_HZ) -> list[dict]: - """Each study's verdict and features, in listing order.""" +def measure(studies, mains_hz: float, workers: int | None = None) -> list[dict]: items = [(k, p, a, mains_hz) for k, p, a in studies] return execution.map(_one, items, phase="measuring_reference", workers=workers) def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: - """Scenario -> its training table: the valid studies' features and `age_months`.""" usable = [s for s in measured if s["valid"] and s["error"] is None] return { name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable]) diff --git a/models/tea/jobs.py b/models/tea/jobs.py index 360f443..6a9b465 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -1,11 +1,3 @@ -"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves -(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and -its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age. - -Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its -features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set -or ages table that changes is measured again.""" - import hashlib import json import os @@ -73,35 +65,32 @@ def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int return len(found) -def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]: - if reference is None: - folder = Path(os.environ["TEA_REFERENCE_DIR"]) - ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv")) - name, line_hz = cohort_reference.NAME, 50 - else: - folder = cluster.reference_dir(reference.name) - ages = folder / "edades.csv" - if not ages.is_file(): - raise ValueError(f"reference cohort {reference.name!r} has no edades.csv") - name, line_hz = reference.name, reference.line_hz - +def _cohort(source: cluster.TrainingSource, as_of: date) -> tuple[str, list[dict], str, int | None]: + if source.kind == "site": + measured = eeg.without_diagnosis(as_of) + if not measured: + raise EmptyCohort(f"no valid EEG of a child without the diagnosis by {as_of}") + digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest() + return digest, measured, "site", None + folder = cluster.reference_dir(source.folder) + ages = folder / "edades.csv" + if not ages.is_file(): + raise ValueError(f"folder {source.folder!r} has no edades.csv") studies = cohort_reference.listing(folder, ages) - if reference is not None and not studies: - raise ValueError(f"reference cohort {name!r} has no EDF with an age from 16 to 36 months") - content = "\n".join(f"{p.name}|{a}" for _, p, a in studies) - if line_hz != 50: - content += f"|line_hz={line_hz}" - digest = hashlib.sha256(content.encode()).hexdigest() + if not studies: + raise ValueError(f"folder {source.folder!r} has no EDF with an age from 16 to 36 months") + content = "\n".join(f"{p.relative_to(folder).as_posix()}|{a}" for _, p, a in studies) + digest = hashlib.sha256(f"{content}|line_hz={source.line_hz}".encode()).hexdigest() cache = os.environ.get("TEA_REFERENCE_CACHE") - path = Path(cache) / f"{name}-{digest[:16]}.json" if cache else None + path = Path(cache) / f"{source.folder}-{digest[:16]}.json" if cache else None if path and path.exists(): - return digest, json.loads(path.read_text()), name, line_hz - measured = cohort_reference.measure(studies, mains_hz=float(line_hz)) + return digest, json.loads(path.read_text()), source.folder, source.line_hz + measured = cohort_reference.measure(studies, mains_hz=float(source.line_hz)) measured = [{**m, "key": str(m["key"])} for m in measured] if path: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(measured)) - return digest, measured, name, line_hz + return digest, measured, source.folder, source.line_hz @dataclass(frozen=True) @@ -120,26 +109,26 @@ def registered(name: str) -> str: def train( - name: str, as_of: date | None = None, reference: cluster.Reference | None = None + name: str, as_of: date | None = None, source: cluster.TrainingSource | None = None ) -> int | None: - """A new version of one age curve, trained on the reference cohort's valid studies, - with its two reports: the cohort it learned from, and its centile curves.""" if name == ASSOCIATION: return train_association(as_of) - digest, measured, cohort, hz = _reference(reference) + day = as_of or date.today() + digest, measured, cohort, hz = _cohort(source or cluster.TrainingSource(), day) table = cohort_reference.tables(measured)[name] baseline = curves.train(table, name) valid = [m for m in measured if m["valid"] and m["error"] is None] + found = {"cohort": cohort, "cohort_sha256": digest} + found |= {"as_of": day.isoformat()} if hz is None else {"line_hz": hz} technical = { - "model": name, "method": "age curves (weighted centiles on log age)", - "cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured), - "valid_studies": len(valid), + "model": name, "method": "age curves (weighted centiles on log age)", **found, + "studies": len(measured), "valid_studies": len(valid), "ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)], "features": sorted(baseline), } # fmt: skip interpretability = {"model": name, "kind": "age_curves", "curves": baseline} metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))} - params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)} + params = {key: str(value) for key, value in found.items()} reports = {"technical_validation": technical, "interpretability": interpretability} return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) diff --git a/tests/test_tea_reference.py b/tests/test_tea_reference.py deleted file mode 100644 index 1047612..0000000 --- a/tests/test_tea_reference.py +++ /dev/null @@ -1,42 +0,0 @@ -import pytest -from edf_files import small_edf -from pydantic import ValidationError - -from models.tea import jobs -from persistance.cluster import Reference - - -@pytest.fixture -def cohort(tmp_path, monkeypatch): - monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path)) - monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False) - folder = tmp_path / "hel" - folder.mkdir() - for i in range(3): - small_edf(folder / f"{i}.edf") - ages = folder / "edades.csv" - ages.write_text("name,age\n0.edf,1.5\n1.edf,2.0\n2.edf,2.5\n") - return folder, ages - - -def test_bad_references_fail_with_a_reason(cohort): - folder, ages = cohort - for name in ("..", ".", "nope"): - with pytest.raises(ValueError) as exc: - jobs._reference(Reference(name=name)) - assert str(exc.value) == f"no reference cohort {name!r}" - - ages.write_text("name,age\n0.edf,1\n1.edf,4\n2.edf,5\n") - with pytest.raises( - ValueError, match="reference cohort 'hel' has no EDF with an age from 16 to 36 months" - ): - jobs._reference(Reference(name="hel")) - - ages.unlink() - with pytest.raises(ValueError, match=r"reference cohort 'hel' has no edades\.csv"): - jobs._reference(Reference(name="hel")) - - with pytest.raises(ValidationError, match="name"): - Reference(name="../x") - with pytest.raises(ValidationError, match="line_hz"): - Reference(name="hel", line_hz=55) diff --git a/tests/test_tea_training_source.py b/tests/test_tea_training_source.py new file mode 100644 index 0000000..57fa070 --- /dev/null +++ b/tests/test_tea_training_source.py @@ -0,0 +1,101 @@ +import json +from datetime import date + +import pytest +from edf_files import small_edf +from pydantic import ValidationError + +from models.jobs import EmptyCohort +from models.tea import jobs +from models.tea.eeg import reference +from persistance import eeg +from persistance.cluster import TrainingSource + + +@pytest.fixture +def folder(tmp_path, monkeypatch): + monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path)) + monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False) + cohort = tmp_path / "hel" + (cohort / "night").mkdir(parents=True) + for name in ("0.edf", "1.edf", "night/2.edf"): + small_edf(cohort / name) + ages = cohort / "edades.csv" + ages.write_text("path,age\n0.edf,18\n1.edf,24.04\nnight/2.edf,30\n") + return cohort, ages + + +def test_a_folder_lists_each_edf_with_its_age_in_months(folder): + cohort, ages = folder + assert reference.listing(cohort, ages) == [ + ("hel-0001", cohort / "0.edf", 18.0), + ("hel-0002", cohort / "1.edf", 24.0), + ("hel-0003", cohort / "night" / "2.edf", 30.0), + ] + ages.write_text("path,age\n0.edf,12\n1.edf,24\nnight/2.edf,40\n") + assert [age for _, _, age in reference.listing(cohort, ages)] == [24.0] + + +def test_bad_folders_fail_with_a_reason(folder): + cohort, ages = folder + for name in ("..", ".", "nope"): + with pytest.raises(ValueError) as exc: + jobs._cohort(TrainingSource(kind="folder", folder=name), date(2026, 1, 1)) + assert str(exc.value) == f"no reference cohort {name!r}" + + ages.write_text("path,age\n0.edf,12\n1.edf,48\nnight/2.edf,60\n") + with pytest.raises( + ValueError, match="folder 'hel' has no EDF with an age from 16 to 36 months" + ): + jobs._cohort(TrainingSource(kind="folder", folder="hel"), date(2026, 1, 1)) + + ages.unlink() + with pytest.raises(ValueError, match=r"folder 'hel' has no edades\.csv"): + jobs._cohort(TrainingSource(kind="folder", folder="hel"), date(2026, 1, 1)) + + with pytest.raises(ValidationError, match="folder"): + TrainingSource(kind="folder") + with pytest.raises(ValidationError, match="line_hz"): + TrainingSource(kind="folder", folder="hel", line_hz=55) + + +def test_the_site_trains_on_children_without_the_diagnosis_by_the_cut_off(fresh_platform): + with fresh_platform.begin() as con: + con.exec_driver_sql("create table silver.eeg (person_id text, study_date text, edf text)") + con.exec_driver_sql( + "insert into silver.eeg values (?, ?, ?)", + [("ruled_out", "2025-03-01", "a"), ("confirmed", "2025-03-01", "b"), + ("later", "2025-03-01", "c"), ("ruled_out", "2025-04-01", "d"), + ("ruled_out", "2025-09-01", "e")], + ) # fmt: skip + con.exec_driver_sql( + "create table bronze.eeg_analysis " + "(edf text, age_months real, features text, valid boolean, error text)" + ) + features = json.dumps({"eeg-gradient": {"value": 1.0}}) + con.exec_driver_sql( + "insert into bronze.eeg_analysis values (?, ?, ?, ?, ?)", + [("a", 20.0, features, True, None), ("b", 22.0, features, True, None), + ("c", 24.0, features, True, None), ("d", 21.0, features, False, None), + ("e", 26.0, features, True, None)], + ) # fmt: skip + con.exec_driver_sql( + "create table gold.tea_screening " + "(person_id text, not_confirmed_date text, confirmed_date text)" + ) + con.exec_driver_sql( + "insert into gold.tea_screening values (?, ?, ?)", + [("ruled_out", "2025-05-01", None), ("confirmed", "2025-02-01", "2025-05-01"), + ("later", "2025-07-01", None)], + ) # fmt: skip + + cut = date(2025, 6, 1) + assert eeg.without_diagnosis(cut) == [ + {"key": "a", "age_months": 20.0, "valid": True, "error": None, + "features": {"eeg-gradient": {"value": 1.0}}}, + ] # fmt: skip + digest, measured, cohort, hz = jobs._cohort(TrainingSource(), cut) + assert (cohort, hz, [m["key"] for m in measured]) == ("site", None, ["a"]) + assert len(digest) == 64 + with pytest.raises(EmptyCohort, match="without the diagnosis by 2025-01-01"): + jobs._cohort(TrainingSource(), date(2025, 1, 1))