EEG study serves its ADOS-2 association rows; TEA gate as roundtrips

This commit is contained in:
Roberto Treviño
2026-11-28 21:28:38 -06:00
parent f6e8b09dd0
commit d8d834f308
3 changed files with 109 additions and 17 deletions
+63 -13
View File
@@ -16,17 +16,20 @@ from datetime import date
from pathlib import Path
import pytest
from sqlalchemy import inspect
from fhir_checks import pages
from test_conectar import ok, wait_for
from conftest import put_concept_map
from core.tea import ados2
from models.tea import association, jobs
from models.tea.eeg import curves
from models.tea.eeg import reference as eeg_reference
from persistance import destination
from persistance import eeg as eeg_store
ROOT = Path(__file__).parents[2]
HOSPITAL = Path(os.environ.get("TEA_HOSPITAL", Path.home() / "isssteleon-data"))
# The age curves' reference cohort (public, outside git) and where its measures are kept.
os.environ.setdefault("TEA_REFERENCE_DIR", "/mnt/drive/eeg-helsinki")
os.environ.setdefault("TEA_REFERENCE_CACHE", str(HOSPITAL / "cache"))
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "tea"
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_tea.json"
MANIFEST = ROOT / "tests" / "fixtures" / "hospital" / "manifest.json"
@@ -125,6 +128,14 @@ pytestmark = pytest.mark.skipif(
)
def platform_eeg(platform):
"""persistance.eeg reading this test's platform (never the deployed data folder)."""
os.environ["PLATFORM_DATABASE_URL"] = platform.env["PLATFORM_DATABASE_URL"]
destination.DATA_DIR = Path(platform.env["ISSSTELEON_DATA"])
destination.engine.cache_clear()
return eeg_store
def _day(value) -> date:
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
@@ -195,25 +206,64 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path):
# Indicators, from the platform's own EEG verdicts.
indicators(api)
# The age curves: one training run gives a version of each, from the reference cohort;
# promoted after their clinical validation, they score every analysed EEG as the
# current platform's curves do.
# The age curves, a roundtrip: one training run gives a version of each, learned from the
# site's own reference group (the valid EEGs of the children whose diagnosis ruled TEA
# out); each is what the curves' math (proved on HK1K by models/tests/test_eeg.py) gives
# on those EEGs, and once promoted it scores every analysed EEG with that curve.
group = platform_eeg(platform).ruled_out(date.today())
assert len(group) >= 5, "the hospital needs children with TEA ruled out and a good EEG"
wait_for(api, ok(api.post("/models/tea/train", json={}))["run_id"], 3600)
names = ok(api.get("/models/tea"))
assert len(names) == 7
assert set(names) >= set(curves.SCENARIOS)
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
for name in names:
for name in curves.SCENARIOS:
report = ok(api.get(f"/models/tea/{name}/versions/1/reports/technical_validation"))
assert report["cohort"] == "site: children with TEA ruled out"
assert report["studies"] == len(group)
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
wait_for(api, ok(api.post("/models/tea/score"))["run_id"], 1800)
trained = {name: curves.train(table, name)
for name, table in eeg_reference.tables(group).items()} # fmt: skip
analysed = {a["edf"]: a for a in platform_eeg(platform).analysed()}
scored = {(e, c): r for e, c, *r in q(
"select edf, code, z, outside, p5, median, p95 from gold.tea_eeg_metrics")} # fmt: skip
for key, theirs in metrics.items():
if key not in scored: # an EEG of a child outside the cohort: not in gold
assert scored
for name, scenario in curves.SCENARIOS.items():
if "value" not in trained[name]: # too few children for its whole-head curve
continue
expected = [theirs[f"met_{k}"] for k in ("z", "fuera", "p5", "mediana", "p95")]
assert scored[key] == [None if v is None else pytest.approx(v, rel=1e-9)
for v in expected], key # fmt: skip
for (edf, code), found in scored.items():
if code != scenario.metric or edf not in analysed:
continue
one = analysed[edf]
metric = next(m for m in one["metrics"] if m["code"] == code)
features = one["features"].get(name, {})
exposure = features.get(curves.EXPOSURE) if scenario.counts else None
expected = curves.score(trained[name]["value"], metric["value"], one["age_months"],
exposure) # fmt: skip
want = [expected[k] for k in ("z", "outside", "p5", "median", "p95")]
assert found == [None if v is None else pytest.approx(v, rel=1e-9)
for v in want], (name, edf) # fmt: skip
# The EEG–ADOS-2 association, a roundtrip: trained on the promoted curves' z of the
# site's children, it is what the association's math (proved against the old platform by
# tests/test_tea_association.py) gives on that cohort; promoted, it scores every EEG.
wait_for(api, ok(api.post("/models/tea/train", json={"models": [jobs.ASSOCIATION]}))["run_id"],
1800) # fmt: skip
platform_eeg(platform)
fit, scored_eegs = jobs.association_cohort()
expected = association.fit(fit)
report = ok(api.get(f"/models/tea/{jobs.ASSOCIATION}/versions/1/reports/interpretability"))
assert (report["level"], report["children"]) == (expected["level"], expected["n"])
assert report["rows"] == json.loads(json.dumps(association.associations(expected)))
ok(api.post(f"/models/tea/{jobs.ASSOCIATION}/versions/1/reports/clinical_validation",
files=files)) # fmt: skip
ok(api.post(f"/models/tea/{jobs.ASSOCIATION}/versions/1/promote"))
wait_for(api, ok(api.post("/models/tea/score"))["run_id"], 1800) # curves, then it
with destination.engine().connect() as con: # no table when no pair was estimated
written = inspect(con).has_table("ados2_association_scores", schema="bronze")
stored = q("select count(*) from bronze.ados2_association_scores")[0][0] if written else 0
assert stored == len(association.score(expected, scored_eegs))
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
listed = ok(api.get("/tea/eegs"))