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
+24 -4
View File
@@ -45,7 +45,7 @@ def _sent(bundles: list[dict]) -> Counter:
biopsies = set()
for b in bundles:
studied = False
treated = 0
treated = recurred = 0
for e in b["entry"]:
r = e["resource"]
codes = [c for c in (r.get("code") or {}).get("coding", []) if c["system"] == STUDY]
@@ -58,9 +58,11 @@ def _sent(bundles: list[dict]) -> Counter:
found[c["code"]] += 1
studied |= c["code"] in ("mammography", "breast_biopsy")
treated += c["code"] == "breast_treatment"
recurred += c["code"] == "breast_recurrence"
if r["resourceType"] == "Patient" and r.get("deceasedDateTime"):
found["death"] += 1
found["timeline_treatment"] += treated if studied else 0
found["timeline_recurrence"] += recurred if studied else 0
found["breast_biopsy"] = len(biopsies)
return found
@@ -69,6 +71,7 @@ def test_a_synthea_cama_population_comes_in_through_the_fhir_door(api, platform,
bundles = population(tmp_path / "synthea")
sent = _sent(bundles)
assert sent["breast_biopsy"] > 50 and sent["breast_treatment"] > 20 and sent["death"] > 0
assert sent["breast_recurrence"] > 0
receiving = DOOR.read_text().replace("{sender}", "synthea")
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
@@ -78,13 +81,30 @@ def test_a_synthea_cama_population_comes_in_through_the_fhir_door(api, platform,
assert answer.status_code == 202, answer.text[:500]
wait_for(api, answer.headers["location"].rsplit("/", 1)[1], 1800)
for study in ("mammography", "breast_biopsy", "breast_treatment"):
for study in ("mammography", "breast_biopsy", "breast_treatment", "breast_recurrence"):
assert ok(api.get("/review/held", params={"entity": study})) == [], study
assert platform.count(f"silver.{study}") == sent[study], study
q = platform.query
# Each invasive biopsy holds all of its results; gold's timeline has them and the course.
assert q("select count(*) from silver.breast_biopsy where histology = 'invasive' and "
"(stage is null or her2 is null or grade is null)")[0][0] == 0 # fmt: skip
"(stage is null or her2 is null or grade is null or positive_nodes is null)"
)[0][0] == 0 # fmt: skip
kinds = dict(q("select type, count(*) from gold.cama_events where type in "
"('stage', 'her2', 'treatment', 'death') group by type")) # fmt: skip
"('stage', 'her2', 'positive_nodes', 'treatment', 'recurrence', 'death') "
"group by type")) # fmt: skip
assert kinds.get("stage", 0) > 0 and kinds.get("treatment", 0) == sent["timeline_treatment"]
assert (
kinds.get("positive_nodes", 0) > 0
and kinds.get("recurrence", 0) == sent["breast_recurrence"]
)
# Recurrence, a roundtrip: trained through the API on these patients, its cohort is gold's
# recurrence cohort and its recurrences are the ones Synthea wrote (slow: minutes).
if not os.environ.get("RECURRENCE_SLOW"):
return
wait_for(api, ok(api.post("/models/cama/train", json={"models": ["recurrence"]}))["run_id"],
3600) # fmt: skip
report = ok(api.get("/models/cama/recurrence/versions/1/reports/technical_validation"))
assert report["cohort"] == "site"
members = q("select count(*) from gold.cama_cohort_recurrence where excluded_by is null")[0][0]
assert report["rutinas"] and members > 0
+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"))