"""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-` 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) def test_training_reads_the_cluster_choice_from_the_environment(monkeypatch): """Pins down: training measures its studies on the runner `EEG_ANALYSIS_CLUSTER` names, and falls back to `auto` for an unset or unknown value (including `off`, which only the analysis understands). Fails if `run_steps` stops passing the choice to `train_all`, or lets an unknown value reach the runner. """ from models.tea.eeg import model monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False) assert model._cluster() == "auto" for chosen in ("auto", "local", "remote", "sync"): monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", chosen) assert model._cluster() == chosen monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "off") assert model._cluster() == "auto"