diff --git a/tests/test_tea.py b/tests/test_tea.py index f3e0363..679622d 100644 --- a/tests/test_tea.py +++ b/tests/test_tea.py @@ -1,9 +1,10 @@ -"""Phase 4 gate, TEA: the synthetic hospital (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. +"""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 (205 MB) is kept outside git; its path is TEA_HOSPITAL (default +The hospital (2 GB) is kept outside git; its path is TEA_HOSPITAL (default ~/isssteleon-data), and its hash is the manifest's. """ @@ -59,16 +60,26 @@ METRICS = {"RITMO_POSTERIOR": "posterior_rhythm", "HUSOS_SUENO_N2": "spindles_n2 "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-26" # the day of the capture's load: durations counted to it +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"} # fmt: skip + "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: @@ -89,7 +100,7 @@ def _report(entry: dict, ours: bool) -> tuple: for p in x["population"]: kind = p["code"]["coding"][0]["code"] if not (ours and kind == "initial-population" and "denominator" in populations): - cells[CODES.get(x["value"]["text"], x["value"]["text"])][kind] = p["count"] + 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} @@ -108,6 +119,7 @@ def indicators(api) -> None: 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: @@ -139,15 +151,20 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path): # 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 == {"mchat": 216, "ados2": 113, "eeg": 84} + assert counts == {s: source[s] for s in counts} assert q("select count(*) from silver.clinical_note where specialty = 'pediatric_neurology'" - )[0][0] == 83 # fmt: skip - assert q("select count(*) from silver.eeg where edf is not null")[0][0] == 78 + )[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] == 78 + assert q(kept)[0][0] == signals - # ADOS-2: the results read from the 50 reports are the current platform's. + # 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 @@ -155,7 +172,7 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path): 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) == 50 + 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 @@ -190,9 +207,6 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path): value = theirs["met_valor"] assert ours.get(key) == (None if value is None else pytest.approx(value, rel=1e-12)), key - # 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. @@ -213,6 +227,10 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path): assert scored[key] == [None if v is None else pytest.approx(v, rel=1e-9) for v in expected], key # fmt: skip + # 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"]