Files
WebApi/tests/test_tea.py
T
2026-11-28 16:31:56 -06:00

305 lines
16 KiB
Python

"""Phase 4 gate, TEA: the sitio-b hospital (62 children with real EEG signals, and ADOS-2
reports, as BLOBs), loaded through one drawn pipeline, gives what the current platform gives
on the same hospital (the reference fixtures, captured at the last load): the ADOS-2 results
read from the reports and their scores, the EEG analysis, its indicators and its pages. Real
API, Dagster and MLflow.
The hospital (2 GB) is kept outside git; its path is TEA_HOSPITAL (default
~/isssteleon-data), and its hash is the manifest's.
"""
import hashlib
import json
import os
import sqlite3
from collections import defaultdict
from datetime import date
from pathlib import Path
import dagster as dg
import pytest
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.definitions import tea_preview
from persistance import config, previews
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"
# The current platform's item columns, by module, for each item's meaning.
ITEMS = {
"vocalization_directed": {"module_1": "sa_a2"},
"pointing": {"module_1": "sa_a7", "module_2": "sa_a6"},
"gestures": {"module_1": "sa_a8", "module_2": "sa_a7"},
"unusual_eye_contact": {"module_1": "sa_b1", "module_2": "sa_b1"},
"facial_expressions": {"module_1": "sa_b3", "module_2": "sa_b2"},
"gaze_integration": {"module_1": "sa_b4"},
"shared_enjoyment": {"module_1": "sa_b5", "module_2": "sa_b3"},
"showing": {"module_1": "sa_b9", "module_2": "sa_b5"},
"joint_attention_initiation": {"module_1": "sa_b10", "module_2": "sa_b6"},
"joint_attention_response": {"module_1": "sa_b11"},
"social_overtures_quality": {"module_1": "sa_b12", "module_2": "sa_b8"},
"reciprocal_communication": {"module_2": "sa_b11"},
"rapport_quality": {"module_2": "sa_b12"},
"intonation": {"module_1": "rrb_a3"},
"stereotyped_language": {"module_1": "rrb_a5", "module_2": "rrb_a4"},
"unusual_sensory_interest": {"module_1": "rrb_d1", "module_2": "rrb_d1"},
"hand_finger_mannerisms": {"module_1": "rrb_d2", "module_2": "rrb_d2"},
"repetitive_interests": {"module_1": "rrb_d4", "module_2": "rrb_d4"},
} # fmt: skip
MODULES = {"MODULO_1": "module_1", "MODULO_2": "module_2"}
CLASSIFICATION = {"NO_ESPECTRO": "non_spectrum", "ESPECTRO_AUTISTA": "autism_spectrum",
"AUTISMO": "autism"} # fmt: skip
METRICS = {"RITMO_POSTERIOR": "posterior_rhythm", "HUSOS_SUENO_N2": "spindles_n2",
"HUSOS_SUENO_N3": "spindles_n3", "PICOS_PAROXISTICOS": "paroxysmal_spikes",
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient"} # fmt: skip
LEVELS = {"completo": "complete", "no_analizable": "not_analyzable", "parcial": "partial",
"sin_referencia_auricular": "no_ear_reference"} # fmt: skip
CAPTURED_ON = "2026-11-28" # the day of the capture's load: durations counted to it
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
CODES = { # the current platform's code -> the platform's
"CONFIRMADO": "confirmed", "EN_PROCESO": "in_process", "SIN_TEA": "not_confirmed",
"SOLO_MCHAT": "mchat_only", "PSICOLOGIA": "psychology", "NEUROPEDIATRIA": "neuropediatrics",
"EEG": "eeg", "BUENO": "good", "MALO": "bad", "SIN_ANALIZAR": "not_analyzed",
"16_23": "16-23", "24_29": "24-29", "30_36": "30-36", "sin_dato": "no_data",
"FEMENINO": "female", "MASCULINO": "male", "EN_POBLACION": "in_population",
} # fmt: skip
STRATA = {"estado": "category", "paso": "category", "calidad": "category",
"grupo_edad": "age_group", "edad_sexo": "age_sex", "sexo": "sex"} # fmt: skip
# Stratifiers only the platform reports: the current platform's M30 gives the total alone, so
# its group per alteration has nothing here to be compared with (gold.tea_alterations is
# tested in dbt).
ONLY_OURS = {"M30_RESULTADO_EEG": {"alteration"}}
def _code(text: str) -> str:
"""A stratum value in the platform's codes; "16_23|FEMENINO" part by part."""
return "|".join(CODES.get(part, part) for part in text.split("|"))
def _report(entry: dict, ours: bool) -> tuple:
"""Counts, score and its extensions, and strata of one report, in the platform's codes.
The current platform's proportions report no initial population."""
group = entry["resource"]["group"][0]
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
if ours and "denominator" in populations:
populations.pop("initial-population")
score = group.get("measureScore", {})
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
strata = {}
for s in group.get("stratifier", []):
code = s["code"][0]
name = code["coding"][0]["code"] if "coding" in code else STRATA[code["text"]]
cells: dict = defaultdict(dict)
for x in s.get("stratum", []):
for p in x["population"]:
kind = p["code"]["coding"][0]["code"]
if not (ours and kind == "initial-population" and "denominator" in populations):
cells[_code(x["value"]["text"])][kind] = p["count"]
strata[name] = dict(cells)
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
def indicators(api) -> None:
"""Every measure, every semester, as the current platform answers them."""
reference = {k.upper(): v for k, v in
json.loads((REFERENCE / "indicators.json").read_text()).items()} # fmt: skip
(measures,) = pages(api, "/tea/fhir/Measure")
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
for measure in [e["resource"] for e in measures["entry"]]:
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
found = [e for b in pages(api, "/tea/fhir/MeasureReport", params) for e in b["entry"]]
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
name = measure["name"]
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
a, b = _report(ours, True), _report(theirs, False)
a = (*a[:3], {k: v for k, v in a[3].items() if k not in ONLY_OURS.get(name, ())})
where = (name, ours["resource"]["period"]["start"])
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
if cohort:
assert b[1] is None and a[1] == a[0]["initial-population"], where
continue
assert (a[1] is None) == (b[1] is None), where
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
assert a[2] == pytest.approx(b[2]), where
pytestmark = pytest.mark.skipif(
not (HOSPITAL / "hospital_tea.db").exists(), reason="the TEA hospital is outside git"
)
def _day(value) -> date:
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
@pytest.fixture
def scored_hospital(api, platform):
db = HOSPITAL / "hospital_tea.db"
expected = json.loads(MANIFEST.read_text())["files"]["hospital_tea.db"]["sha256"]
assert hashlib.sha256(db.read_bytes()).hexdigest() == expected
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
put_concept_map(api, "hospital_tea")
ok(api.put("/ingest/pipelines/tea", json=pipeline))
wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], 1800)
q = platform.query
# Silver holds every study of the hospital; each file (EEG signal, ADOS-2 report) is
# kept once, by its hash.
with sqlite3.connect(db) as con:
source = {s: con.execute(f"select count(*) from {s}").fetchone()[0]
for s in ("mchat", "ados2", "eeg", "evaluacion_neuropediatrica")} # fmt: skip
signed = "select count(*) from eeg where eeg_estudio is not null"
signals = con.execute(signed).fetchone()[0]
counts = {s: q(f"select count(*) from silver.{s}")[0][0] for s in ("mchat", "ados2", "eeg")}
assert counts == {s: source[s] for s in counts}
assert q("select count(*) from silver.clinical_note where specialty = 'pediatric_neurology'"
)[0][0] == source["evaluacion_neuropediatrica"] # fmt: skip
assert q("select count(*) from silver.eeg where edf is not null")[0][0] == signals
kept = "select count(*) from bronze.files where key in (select edf from silver.eeg)"
assert q(kept)[0][0] == signals
# ADOS-2: the results read from every report are the current platform's.
reference = {(r["ado_fecha"], r["ado_pac_id"]): r for r in
json.loads((REFERENCE / "tables" / "ados2.json").read_text())
if r["ado_modulo"]} # fmt: skip
numbers = dict(q("select distinct person_id, record_number from bronze.staged__identity"))
names = ["person_id", "evaluation_date", "module", *ITEMS]
sql = f"select {', '.join(names)} from silver.ados2 where module is not null"
found = [dict(zip(names, r, strict=True)) for r in q(sql)]
assert len(found) == len(reference) == counts["ados2"]
for row in found:
theirs = reference[(str(row["evaluation_date"])[:10],
int(numbers[row["person_id"]].removeprefix("N")))] # fmt: skip
module = MODULES[theirs["ado_modulo"]]
assert row["module"] == module
for item, by_module in ITEMS.items():
value = theirs["ado_" + by_module[module]] if module in by_module else None
assert row[item] == (None if value is None else pytest.approx(value)), item
# and their scores: the calibrated severity and the classification.
birth = q(f"select birth_date from silver.person where person_id = '{row['person_id']}'")
css, label = ados2.score({**row, "evaluation_date": _day(row["evaluation_date"])},
_day(birth[0][0])) # fmt: skip
assert (css, label) == (theirs["ado_css"], CLASSIFICATION[theirs["ado_clasificacion"]])
# The EEG analysis: every signal's verdict, level and metrics are the current platform's.
wait_for(api, ok(api.post("/models/tea/analyze"))["run_id"], 3600) # 62 EEGs, 2 CPUs: ~45 min
with sqlite3.connect(db) as con:
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
tables = REFERENCE / "tables"
reference = {hashes[r["eeg_id"]]: r for r in json.loads((tables / "eeg.json").read_text())
if r["eeg_id"] in hashes} # fmt: skip
found = {e: (v, lvl) for e, v, lvl in q("select edf, valid, level from bronze.eeg_analysis")}
assert set(found) == set(reference)
for edf, theirs in reference.items():
assert found[edf] == (bool(theirs["eeg_valido"]), LEVELS[theirs["eeg_nivel"]]), edf
by_id = {r["eeg_id"]: hashes.get(r["eeg_id"]) for r in reference.values()}
metrics = {(by_id.get(r["met_eeg_id"]), METRICS[r["met_codigo"]]): r
for r in json.loads((tables / "eeg_metrica.json").read_text())} # fmt: skip
ours = {(e, c): v for e, c, v in q("select edf, code, value from bronze.eeg_metrics")}
for key, theirs in metrics.items():
value = theirs["met_valor"]
assert ours.get(key) == (None if value is None else pytest.approx(value, rel=1e-12)), key
# 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.
wait_for(api, ok(api.post("/models/tea/train", json={}))["run_id"], 3600)
names = ok(api.get("/models/tea"))
assert len(names) == 7
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
for name in names:
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)
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
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
return platform
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
# Indicators, from the platform's own EEG verdicts and, for M30, the alterations the
# promoted curves found (as the current platform's were captured: curves trained).
indicators(api)
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
listed = ok(api.get("/tea/eegs"))
summary = json.loads((REFERENCE / "pages.json").read_text())["/governance/tea/eeg/summary"]
expected = summary["body"]
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
one = next(e for e in listed if e["valid"])
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
for m in shown["metrics"]) # fmt: skip
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
def _preview_matches_the_analysis_and_leaves_bronze_unchanged(platform, monkeypatch):
"""P3.5: previewing one of the hospital's EDFs gives its stored analysis and scores, and
writes nothing (run here, on the already scored hospital, not as a second 80-minute load)."""
q = platform.query
tables = (
"bronze.eeg_analysis", "bronze.eeg_checks", "bronze.eeg_metrics",
"bronze.eeg_scores", "bronze.files", "silver.eeg",
) # fmt: skip
before = {table: platform.count(table) for table in tables}
edf, content, birth, valid, level = q("""
select a.edf, f.content, p.birth_date, a.valid, a.level
from bronze.eeg_analysis a
join bronze.files f on f.key = a.edf
join silver.eeg e on e.edf = a.edf
join silver.person p on p.person_id = e.person_id
where a.valid and p.birth_date is not null and exists (
select 1 from gold.tea_eeg_metrics m where m.edf = a.edf and m.z is not null
)
order by a.edf
limit 1
""")[0]
values = dict(q(f"select code, value from bronze.eeg_metrics where edf = '{edf}'"))
scores = dict(q(f"select code, z from gold.tea_eeg_metrics where edf = '{edf}'"))
for name in ("PLATFORM_DATABASE_URL", "MLFLOW_TRACKING_URI", "ISSSTELEON_DATA"):
monkeypatch.setenv(name, platform.env[name])
monkeypatch.setattr(config, "DATA_DIR", Path(platform.env["ISSSTELEON_DATA"]))
key = previews.put(bytes(content))
with dg.DagsterInstance.ephemeral() as instance:
run = tea_preview.execute_in_process(
run_config={"ops": {"preview_study": {"config": {
"edf": key, "birth_date": _day(birth).isoformat(),
}}}},
instance=instance,
) # fmt: skip
assert run.success
(event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT)
result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value)
assert (result.eeg.valid, result.eeg.level) == (valid, level)
assert {metric.code for metric in result.eeg.metrics} == values.keys() == scores.keys()
for metric in result.eeg.metrics:
value, z = values[metric.code], scores[metric.code]
assert metric.value == (None if value is None else pytest.approx(value, rel=1e-12))
assert (metric.score.z if metric.score else None) == (
None if z is None else pytest.approx(z, rel=1e-9)
)
assert {table: platform.count(table) for table in tables} == before
assert not list(previews.area().iterdir())