Training config: reference name and mains frequency: train takes a named reference cohort and its mains frequency; legacy TEA_REFERENCE_DIR stays the default

This commit is contained in:
2026-11-28 13:26:18 -06:00
parent 9ed686e87a
commit b7eaf7055d
3 changed files with 197 additions and 23 deletions
+16 -1
View File
@@ -2,6 +2,7 @@
import hashlib import hashlib
import importlib import importlib
import inspect
import io import io
import json import json
import zipfile import zipfile
@@ -67,11 +68,20 @@ def _jobs(domain: str):
raise ValueError(f"{domain} has no models") from e raise ValueError(f"{domain} has no models") from e
class ReferenceConfig(dg.Config):
name: str
line_hz: int = 50
def model(self) -> cluster.Reference:
return cluster.Reference(**self.model_dump())
class Training(dg.Config): class Training(dg.Config):
domain: str domain: str
models: list[str] = [] # default: every model of the domain but the slow ones models: list[str] = [] # default: every model of the domain but the slow ones
as_of: str | None = None # the date the data are taken up to (default: today) as_of: str | None = None # the date the data are taken up to (default: today)
execution: ExecutionConfig = ExecutionConfig() execution: ExecutionConfig = ExecutionConfig()
reference: ReferenceConfig | None = None
@dg.op @dg.op
@@ -79,11 +89,16 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports.""" """A new registered version of each model (MLflow), with its reports."""
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None 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()
found = {} found = {}
with execution.running(context, config.execution.model()): with execution.running(context, config.execution.model()):
for name in config.models or jobs.JOBS.routine(): for name in config.models or jobs.JOBS.routine():
try: try:
found[name] = jobs.train(name, as_of) found[name] = jobs.train(name, as_of, **options)
except EmptyCohort as e: # the site has no such patients; the others still train except EmptyCohort as e: # the site has no such patients; the others still train
found[name] = None found[name] = None
context.log.warning(f"{e}: not trained") context.log.warning(f"{e}: not trained")
+37 -22
View File
@@ -1,10 +1,10 @@
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves """TEA jobs analyse the hospital's EEGs and score them against seven age curves
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and (models.tea.eeg.curves). Training uses a named reference cohort or the legacy
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age. TEA_REFERENCE_DIR and TEA_REFERENCE_AGES settings.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its 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 features are kept in TEA_REFERENCE_CACHE in a JSON file named by the cohort and its hash.
or ages table that changes is measured again.""" Changes to the study list, ages or mains frequency require measuring the cohort again."""
import hashlib import hashlib
import json import json
@@ -17,8 +17,9 @@ import mlflow.pyfunc
import pandas as pd import pandas as pd
from models import execution from models import execution
from models.tea.eeg import analysis, curves, reference from models.tea.eeg import analysis, curves
from persistance import eeg, registry, silver from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
MODELS = curves.SCENARIOS MODELS = curves.SCENARIOS
CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2 CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2
@@ -59,22 +60,36 @@ def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int
return len(found) return len(found)
def _reference() -> tuple[str, list[dict]]: def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
"""The reference cohort's hash and each study's verdict and features, cached.""" """The reference cohort's hash, cached measurements, name and mains frequency."""
folder = Path(os.environ["TEA_REFERENCE_DIR"]) if reference is None:
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv")) folder = Path(os.environ["TEA_REFERENCE_DIR"])
studies = reference.listing(folder, ages) ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest() 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
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()
cache = os.environ.get("TEA_REFERENCE_CACHE") cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None path = Path(cache) / f"{name}-{digest[:16]}.json" if cache else None
if path and path.exists(): if path and path.exists():
return digest, json.loads(path.read_text()) return digest, json.loads(path.read_text()), name, line_hz
measured = reference.measure(studies) measured = cohort_reference.measure(studies, mains_hz=float(line_hz))
measured = [{**m, "key": str(m["key"])} for m in measured] measured = [{**m, "key": str(m["key"])} for m in measured]
if path: if path:
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(measured)) path.write_text(json.dumps(measured))
return digest, measured return digest, measured, name, line_hz
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -92,23 +107,23 @@ def registered(name: str) -> str:
return f"tea.{name}" return f"tea.{name}"
def train(name: str, as_of: date | None = None) -> int: def train(name: str, as_of: date | None = None, reference: cluster.Reference | None = None) -> int:
"""A new version of one age curve, trained on the reference cohort's valid studies, """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.""" with its two reports: the cohort it learned from, and its centile curves."""
digest, measured = _reference() digest, measured, cohort, hz = _reference(reference)
table = reference.tables(measured)[name] table = cohort_reference.tables(measured)[name]
baseline = curves.train(table, name) baseline = curves.train(table, name)
valid = [m for m in measured if m["valid"] and m["error"] is None] valid = [m for m in measured if m["valid"] and m["error"] is None]
technical = { technical = {
"model": name, "method": "age curves (weighted centiles on log age)", "model": name, "method": "age curves (weighted centiles on log age)",
"cohort": reference.NAME, "cohort_sha256": digest, "studies": len(measured), "cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured),
"valid_studies": len(valid), "valid_studies": len(valid),
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)], "ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
"features": sorted(baseline), "features": sorted(baseline),
} # fmt: skip } # fmt: skip
interpretability = {"model": name, "kind": "age_curves", "curves": baseline} interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))} metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
params = {"cohort": reference.NAME, "cohort_sha256": digest} params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)}
reports = {"technical_validation": technical, "interpretability": interpretability} reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
+144
View File
@@ -0,0 +1,144 @@
import hashlib
from types import SimpleNamespace
import pytest
from edf_files import small_edf
from pydantic import ValidationError
from models import definitions
from models.tea import jobs
from models.tea.eeg import curves, reference
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
@pytest.fixture
def measurements(monkeypatch):
calls = []
def measure(studies, *, mains_hz):
calls.append((studies, mains_hz))
return [
{"key": key, "age_months": age, "valid": True, "error": None, "features": {}}
for key, _, age in studies
]
monkeypatch.setattr(reference, "measure", measure)
return calls
def test_a_named_reference_resolves_under_the_root(cohort, measurements):
_, measured, name, hz = jobs._reference(Reference(name="hel"))
[(studies, mains_hz)] = measurements
assert len(studies) == len(measured) == 3
assert all(path.parent == cohort[0] for _, path, _ in studies)
assert mains_hz == 50.0
assert (name, hz) == ("hel", 50)
def test_60_hz_changes_the_digest_and_is_passed_on(cohort, measurements):
digest_50, *_ = jobs._reference(Reference(name="hel"))
digest_60, _, _, hz = jobs._reference(Reference(name="hel", line_hz=60))
assert digest_50 == hashlib.sha256(b"0.edf|18.0\n1.edf|24.0\n2.edf|30.0").hexdigest()
assert digest_60 != digest_50
assert hz == 60
assert measurements[-1][1] == 60.0
def test_the_cache_is_named_by_cohort_and_digest_and_reused(cohort, measurements, monkeypatch):
cache = cohort[0].parent / "c"
monkeypatch.setenv("TEA_REFERENCE_CACHE", str(cache))
result = jobs._reference(Reference(name="hel"))
assert [p.name for p in cache.iterdir()] == [f"hel-{result[0][:16]}.json"]
assert jobs._reference(Reference(name="hel")) == result
assert len(measurements) == 1
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)
def test_legacy_environment_still_works(cohort, measurements, monkeypatch):
folder, ages = cohort
monkeypatch.setenv("TEA_REFERENCE_DIR", str(folder))
monkeypatch.setenv("TEA_REFERENCE_AGES", str(ages))
_, measured, name, hz = jobs._reference(None)
assert len(measured) == 3
assert (name, hz) == ("hk1k", 50)
assert measurements[0][1] == 50.0
def test_train_records_cohort_and_line_hz(cohort, measurements, monkeypatch):
monkeypatch.setattr(reference, "tables", lambda measured: {"curve": measured})
monkeypatch.setattr(curves, "train", lambda table, name: {"value": {}})
registrations = []
def register(*args):
registrations.append(args)
return 1
monkeypatch.setattr(jobs.registry, "register", register)
config = Reference(name="hel", line_hz=60)
assert jobs.train("curve", reference=config) == 1
[(_, _, params, _, reports)] = registrations
digest, *_ = jobs._reference(config)
assert params == {"cohort": "hel", "cohort_sha256": digest, "line_hz": "60"}
technical = reports["technical_validation"]
assert technical["cohort"] == "hel"
assert technical["line_hz"] == 60
def test_the_train_op_passes_the_reference_or_refuses_it(monkeypatch):
calls = []
def train(name, as_of, reference=None):
calls.append((name, as_of, reference))
return 1
fake = SimpleNamespace(train=train)
monkeypatch.setattr(definitions, "_jobs", lambda domain: fake)
config = {"ops": {"train_models": {"config": {
"domain": "tea", "models": ["curve"], "execution": {"mode": "sync"},
"reference": {"name": "a", "line_hz": 60},
}}}} # fmt: skip
assert definitions.train.execute_in_process(run_config=config).success
assert calls == [("curve", None, Reference(name="a", line_hz=60))]
fake.train = lambda name, as_of: 1
with pytest.raises(ValueError, match="tea models take no reference cohort"):
definitions.train.execute_in_process(run_config=config)
def test_reference_config_mirrors_the_shared_model():
assert definitions.ReferenceConfig.model_fields.keys() == Reference.model_fields.keys()