"""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