ec5d945f71
1. No prose in code - Remove parity-added Python comments and docstrings across the EEG, FHIR, execution, preview, training and run code and tests. Preserve endpoint descriptions as explicit FastAPI schema metadata. 2. No hacks, no glued code - Read the declared TEA patient filters and training inputs directly and use the same TEA check for exposing and validating reference options. - Give the Dagster GraphQL request one helper. Keep lock backoff and cancellation polling because their timing and error behavior are covered by run tests and they handle different Dagster states. - Use the renamed FHIR report ID helper in the hospital test. Keep TEA_GATE_SLOW local to that test and preserve the test assertions. 3. Everything in its place - Keep endpoint and run handling in WebApi and reuse Core and Persistance for domain rules and reads. Leave tests in the existing testpaths.
770 lines
37 KiB
Python
770 lines
37 KiB
Python
"""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.
|
|
|
|
The hospital (205 MB) is kept outside git; its path is TEA_HOSPITAL (default
|
|
~/isssteleon-data), and its hash is the manifest's.
|
|
"""
|
|
|
|
import gzip
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import time
|
|
from collections import defaultdict
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
from pathlib import Path
|
|
from urllib.parse import parse_qsl
|
|
|
|
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 import fhir
|
|
from core.tea import ados2
|
|
from core.tea import fhir as tea_fhir
|
|
from models.definitions import tea_preview
|
|
from persistance import config, previews
|
|
|
|
ROOT = Path(__file__).parents[2]
|
|
SLOW = float(os.environ.get("TEA_GATE_SLOW", "1"))
|
|
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
|
|
BIOMARKERS = {
|
|
"PICOS_PAROXISTICOS": "spikes",
|
|
"HUSOS_SUENO_N2": "spindles",
|
|
"RITMO_POSTERIOR": "posterior_rhythm",
|
|
"GRADIENTE_ANTEROPOSTERIOR": "gradient",
|
|
}
|
|
ZONES = {
|
|
"frontal_izq": "frontal_left",
|
|
"frontal_der": "frontal_right",
|
|
"frontal_media": "frontal_midline",
|
|
"temporal_izq": "temporal_left",
|
|
"temporal_der": "temporal_right",
|
|
}
|
|
CAPTURED_ON = "2026-11-28"
|
|
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
|
|
ONLY_OURS = {"M30_RESULTADO_EEG": {"alteration"}}
|
|
|
|
|
|
def _code(text: str) -> str:
|
|
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])
|
|
|
|
|
|
def _wait_for_sensor_analysis(api):
|
|
deadline = time.monotonic() + 3600 * SLOW
|
|
while time.monotonic() < deadline:
|
|
runs = ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))
|
|
for run in runs:
|
|
if run["state"] == "failed":
|
|
pytest.fail(ok(api.get(f"/runs/{run['id']}"))["error"])
|
|
if any(run["state"] == "succeeded" for run in runs):
|
|
return
|
|
time.sleep(2)
|
|
pytest.fail("The sensor's tea_eeg run did not succeed within 3600 seconds")
|
|
|
|
|
|
@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"], int(1800 * SLOW))
|
|
_wait_for_sensor_analysis(api)
|
|
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
|
|
|
|
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.
|
|
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"], int(3600 * SLOW))
|
|
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"))
|
|
pending = {"scope": {"mode": "pending"}}
|
|
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], int(1800 * SLOW))
|
|
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 _association_gate(api, platform):
|
|
name = "ados2_association"
|
|
training = ok(api.post("/models/tea/train", json={"models": [name]}))["run_id"]
|
|
wait_for(api, training, int(3600 * SLOW))
|
|
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
|
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
|
|
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
|
|
pending = {"scope": {"mode": "pending"}}
|
|
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], int(1800 * SLOW))
|
|
|
|
tables = REFERENCE / "tables"
|
|
reference = json.loads((tables / "relacion_ados2.json").read_text())
|
|
pair_keys = {}
|
|
expected_pairs = {}
|
|
for row in reference:
|
|
zone = row["rel_zona"]
|
|
pair = "|".join(
|
|
(BIOMARKERS[row["rel_biomarcador"]], ZONES.get(zone, zone), row["rel_resultado"])
|
|
)
|
|
pair_keys[row["rel_id"]] = pair
|
|
expected_pairs[pair] = row
|
|
q = platform.query
|
|
pairs = {key: values for key, *values in q(
|
|
"select key, n, n_cohort, method, same_direction, odds_ratio, ci_low, ci_high, p, q "
|
|
"from gold.tea_associations"
|
|
)} # fmt: skip
|
|
assert pairs.keys() == expected_pairs.keys()
|
|
for key, row in expected_pairs.items():
|
|
n, n_cohort, method, same_direction, *stats = pairs[key]
|
|
assert (n, n_cohort, method, same_direction) == (
|
|
row["rel_n"],
|
|
row["rel_n_cohorte"],
|
|
row["rel_modelo"],
|
|
row["rel_mismo_sentido"],
|
|
), key
|
|
for value, field in zip(stats, ("or", "ic_inf", "ic_sup", "p", "q"), strict=True):
|
|
expected = row[f"rel_{field}"]
|
|
assert value == (None if expected is None else pytest.approx(expected, rel=1e-3)), (
|
|
key,
|
|
field,
|
|
)
|
|
|
|
with sqlite3.connect(HOSPITAL / "hospital_tea.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}
|
|
eeg_ids = {
|
|
(edf, str(day)[:10]): f"{person}|{str(day)[:10]}"
|
|
for edf, person, day in q("select edf, person_id, study_date from silver.eeg")
|
|
}
|
|
reference_eegs = {
|
|
row["eeg_id"]: eeg_ids.get((hashes.get(row["eeg_id"]), row["eeg_fecha_estudio"]))
|
|
for row in json.loads((tables / "eeg.json").read_text())
|
|
}
|
|
reference = json.loads((tables / "relacion_ados2_paciente.json").read_text())
|
|
expected_scores = {
|
|
(reference_eegs[row["rap_eeg_id"]], pair_keys[row["rap_rel_id"]]): row for row in reference
|
|
}
|
|
score_rows = q(
|
|
"select eeg_id, pair, z, probability, reference_probability "
|
|
"from gold.tea_association_scores"
|
|
)
|
|
scores = {(eeg_id, pair): (z, prob, ref) for eeg_id, pair, z, prob, ref in score_rows}
|
|
assert scores.keys() == expected_scores.keys()
|
|
for key, row in expected_scores.items():
|
|
z, prob, ref = scores[key]
|
|
assert z == pytest.approx(row["rap_valor_z"], rel=1e-9), key
|
|
assert prob == pytest.approx(row["rap_probabilidad"], abs=1e-4), key
|
|
assert ref == pytest.approx(row["rap_probabilidad_referencia"], abs=1e-4), key
|
|
|
|
|
|
def _fhir_code(concept):
|
|
return concept["coding"][0]["code"]
|
|
|
|
|
|
def _fhir_extensions(resource):
|
|
return {
|
|
e["url"].rsplit("/", 1)[-1]: next(
|
|
(v for k, v in e.items() if k.startswith("value")), e.get("extension")
|
|
)
|
|
for e in resource.get("extension", [])
|
|
}
|
|
|
|
|
|
def _assert_reference_number(actual, expected, *, rel=1e-9):
|
|
if expected is None or isinstance(expected, int):
|
|
assert actual == expected
|
|
else:
|
|
precision = float(Decimal("0.5").scaleb(expected.as_tuple().exponent))
|
|
assert actual == pytest.approx(float(expected), rel=rel, abs=precision)
|
|
|
|
|
|
def _fhir_check_gate(actual, reference):
|
|
units = {"electrodos": "electrodes", "fracción": "fraction"}
|
|
for a, b in [
|
|
(actual.get("valueQuantity"), reference.get("valueQuantity")),
|
|
*(
|
|
(
|
|
actual.get("referenceRange", [{}])[0].get(bound),
|
|
reference.get("referenceRange", [{}])[0].get(bound),
|
|
)
|
|
for bound in ("low", "high")
|
|
),
|
|
]:
|
|
if b is None:
|
|
assert a is None
|
|
else:
|
|
assert a.get("unit") == units.get(b.get("unit"), b.get("unit"))
|
|
_assert_reference_number(a["value"], b["value"])
|
|
text = reference.get("valueString")
|
|
assert actual.get("valueString") == LEVELS.get(text, text)
|
|
assert _fhir_code(actual["interpretation"][0]) == _fhir_code(reference["interpretation"][0])
|
|
decisive = next(c["valueBoolean"] for c in reference["component"]
|
|
if c["code"]["text"] == "decisive") # fmt: skip
|
|
assert _fhir_extensions(actual)["eeg-check-decisive"] == decisive
|
|
|
|
|
|
def _fhir_risk_gate(actual, reference):
|
|
def pair(prediction):
|
|
extensions = _fhir_extensions(prediction)
|
|
biomarker = BIOMARKERS[extensions["biomarcador"]["code"]]
|
|
zone = extensions["zona"]["code"]
|
|
return "|".join((biomarker, ZONES.get(zone, zone), _fhir_code(prediction["outcome"])))
|
|
|
|
predictions = {_fhir_code(p["outcome"]): p for p in actual["prediction"]}
|
|
expected = {pair(p): p for p in reference["prediction"]}
|
|
assert predictions.keys() == expected.keys()
|
|
for code, prediction in predictions.items():
|
|
theirs = expected[code]
|
|
_assert_reference_number(prediction["probabilityDecimal"], theirs["probabilityDecimal"],
|
|
rel=1e-3) # fmt: skip
|
|
extensions, theirs = _fhir_extensions(prediction), _fhir_extensions(theirs)
|
|
for ours, name in (
|
|
("odds-ratio", "odds-ratio"),
|
|
("ci-low", "ic-inf"),
|
|
("ci-high", "ic-sup"),
|
|
("q", "q"),
|
|
("reference-probability", "probabilidad-referencia"),
|
|
):
|
|
_assert_reference_number(extensions.get(f"association-{ours}"), theirs.get(name),
|
|
rel=1e-3) # fmt: skip
|
|
assert extensions.get("association-same-direction") == theirs.get("mismo-sentido")
|
|
|
|
|
|
def _fhir_eeg_gate(api, platform, patients, reference):
|
|
tables = REFERENCE / "tables"
|
|
|
|
def table(name):
|
|
return json.loads((tables / f"{name}.json").read_text(), parse_float=Decimal)
|
|
|
|
records = {r["eeg_pac_id"]: r["eeg_id"] for r in table("eeg")}
|
|
metric_ids = {(r["met_eeg_id"], METRICS[r["met_codigo"]]): r["met_id"]
|
|
for r in table("eeg_metrica")} # fmt: skip
|
|
sites = defaultdict(dict)
|
|
for kind, name, prefix, site in (
|
|
("eeg-electrode-10-20", "electrodo", "mel", "electrodo"),
|
|
("tea-eeg-zone", "zona", "mez", "zona"),
|
|
):
|
|
for r in table(f"eeg_metrica_{name}"):
|
|
code = r[f"{prefix}_{site}"]
|
|
sites[r[f"{prefix}_met_id"]][kind, ZONES.get(code, code)] = r[f"{prefix}_valor"]
|
|
|
|
scores = {
|
|
(tea_fhir._eeg_report_id(person, day), metric): z
|
|
for person, day, metric, z in platform.query(
|
|
"select e.person_id, e.study_date, s.metric, s.z from bronze.eeg_scores as s "
|
|
"join silver.eeg as e on e.edf = s.edf where s.part = 'value' and s.model is not null"
|
|
)
|
|
}
|
|
by_child = defaultdict(list)
|
|
for resource in reference:
|
|
if "subject" in resource:
|
|
by_child[resource["subject"]["reference"]].append(resource)
|
|
params = [("follow-up-cutoff", "2026-12-31"), ("_count", 20)]
|
|
params += [("_revinclude", f"{kind}:subject") for kind in
|
|
("DiagnosticReport", "Observation", "Condition", "RiskAssessment")] # fmt: skip
|
|
served = defaultdict(dict)
|
|
for bundle in pages(api, "/tea/fhir/Patient", params):
|
|
for entry in bundle.get("entry", []):
|
|
r = entry["resource"]
|
|
if entry["search"]["mode"] == "include":
|
|
served[r["subject"]["reference"]][f"{r['resourceType']}/{r['id']}"] = r
|
|
|
|
for child, (person, number) in patients.items():
|
|
actual = served[f"Patient/{person}"]
|
|
theirs = by_child[child]
|
|
for kind in ("Observation", "DiagnosticReport", "RiskAssessment", "Condition"):
|
|
direct = {
|
|
f"{kind}/{r['id']}": r
|
|
for bundle in pages(api, f"/tea/fhir/{kind}", {"subject": f"Patient/{person}"})
|
|
for entry in bundle.get("entry", [])
|
|
if (r := entry["resource"])
|
|
}
|
|
assert direct == {key: r for key, r in actual.items() if key.startswith(f"{kind}/")}
|
|
|
|
def resources(kind, code=None, actual=actual):
|
|
return [
|
|
r
|
|
for r in actual.values()
|
|
if r["resourceType"] == kind and (code is None or _fhir_code(r["code"]) == code)
|
|
]
|
|
|
|
(expected_ados,) = [r for r in theirs if r["id"].startswith("ados2-")]
|
|
(ados,) = resources("Observation", "ados2")
|
|
components = {_fhir_code(c["code"]): c for c in expected_ados["component"]}
|
|
assert ados.get("valueInteger") == components.get("ados2.css", {}).get("valueInteger")
|
|
classification = components["ados2.clasificacion"]["valueCodeableConcept"]
|
|
assert (
|
|
_fhir_code(ados["interpretation"][0])
|
|
== CLASSIFICATION[_fhir_code(classification).rsplit(".", 1)[-1]]
|
|
)
|
|
(expected_mchat,) = [r for r in theirs if r["id"].startswith("mchat-")]
|
|
(mchat,) = resources("Observation", "mchat.score")
|
|
assert mchat["valueQuantity"]["value"] == expected_mchat["valueInteger"]
|
|
(expected_condition,) = [r for r in theirs if r["resourceType"] == "Condition"]
|
|
assert any(
|
|
r["recordedDate"] == expected_condition["recordedDate"]
|
|
and {"system": fhir.ICD10, "code": "F84.0"} in r["code"].get("coding", [])
|
|
for r in resources("Condition")
|
|
)
|
|
|
|
(expected_report,) = [r for r in theirs if r["resourceType"] == "DiagnosticReport"]
|
|
(report,) = resources("DiagnosticReport", "eeg")
|
|
quality, validity = map(_fhir_code, expected_report["conclusionCode"])
|
|
assert list(map(_fhir_code, report["conclusionCode"])) == [
|
|
CODES[quality],
|
|
validity.replace("-", "_"),
|
|
]
|
|
extensions = _fhir_extensions(report)
|
|
expected_extensions = _fhir_extensions(expected_report)
|
|
for name, code in (("duration-min", "duracion-min"), ("age-months", "edad-meses"),
|
|
("channels", "canales")): # fmt: skip
|
|
_assert_reference_number(extensions.get(f"eeg-{name}"), expected_extensions.get(code))
|
|
result = [actual[r["reference"]] for r in report["result"]]
|
|
assert all(r["subject"] == report["subject"] for r in result)
|
|
checks = {
|
|
(_fhir_code(r["code"]), _fhir_code(r["component"][0]["code"]) if r.get("component")
|
|
else None): r for r in result
|
|
if r["code"]["coding"][0]["system"].endswith("/tea-eeg-check")
|
|
} # fmt: skip
|
|
expected_checks = {
|
|
(_fhir_code(r["code"]), next((c["valueString"] for c in r["component"]
|
|
if c["code"]["text"] == "electrode"), None)): r
|
|
for r in theirs if r["id"].startswith("calidad-")
|
|
} # fmt: skip
|
|
assert checks.keys() == expected_checks.keys()
|
|
for key, check in checks.items():
|
|
_fhir_check_gate(check, expected_checks[key])
|
|
|
|
metrics = {_fhir_code(r["code"]): r for r in result
|
|
if r["code"]["coding"][0]["system"].endswith("/tea-eeg-metric")} # fmt: skip
|
|
expected_metrics = {METRICS[_fhir_code(r["code"]).upper()]: r for r in theirs
|
|
if r.get("code", {}).get("coding", [{}])[0].get("code", "").upper()
|
|
in METRICS} # fmt: skip
|
|
assert metrics.keys() == expected_metrics.keys()
|
|
for code, metric in metrics.items():
|
|
expected = expected_metrics[code]
|
|
_assert_reference_number(metric.get("valueQuantity", {}).get("value"),
|
|
expected.get("valueQuantity", {}).get("value")) # fmt: skip
|
|
z = _fhir_extensions(metric).get("eeg-z")
|
|
stored = scores.get((report["id"], code))
|
|
assert z == (pytest.approx(stored, rel=1e-9) if stored is not None else None)
|
|
expected_z = next((c["valueQuantity"]["value"] for c in expected.get("component", [])
|
|
if _fhir_code(c["code"]) == "z"), None) # fmt: skip
|
|
_assert_reference_number(z, expected_z)
|
|
components = {
|
|
(c["code"]["coding"][0]["system"].rsplit("/", 1)[-1], _fhir_code(c["code"])): c.get(
|
|
"valueQuantity", {}
|
|
).get("value")
|
|
for c in metric.get("component", [])
|
|
}
|
|
expected_sites = sites[metric_ids[records[number], code]]
|
|
assert components.keys() == expected_sites.keys()
|
|
for site, value in components.items():
|
|
_assert_reference_number(value, expected_sites[site])
|
|
|
|
expected_risks = [r for r in theirs if r["resourceType"] == "RiskAssessment"]
|
|
for risk, expected in zip(resources("RiskAssessment"), expected_risks, strict=True):
|
|
assert [b["reference"] for b in risk["basis"]] == [
|
|
f"DiagnosticReport/{report['id']}",
|
|
f"Observation/{ados['id']}",
|
|
]
|
|
_fhir_risk_gate(risk, expected)
|
|
|
|
|
|
def _follow_up_gate(api, platform):
|
|
with gzip.open(REFERENCE / "follow_up.json.gz", "rt") as file:
|
|
reference = json.load(file, parse_float=Decimal)
|
|
persons = {
|
|
int(number.removeprefix("N")): person
|
|
for person, number in platform.query(
|
|
"select distinct person_id, record_number from bronze.staged__identity"
|
|
)
|
|
}
|
|
params_map = {
|
|
"etapa": "tea-step", "status": "follow-up-status", "resultado-eeg": "tea-eeg-result",
|
|
"modelo": "tea-model", "grupo-edad": "tea-age-group", "sexo": "tea-sex",
|
|
"mchat": "tea-mchat", "css": "tea-css",
|
|
} # fmt: skip
|
|
values = {
|
|
**CODES, "NEUROPEDIATRIA": "neurology", "anormal": "abnormal",
|
|
"sin-eeg-valido": "no_valid_eeg",
|
|
"si": "yes",
|
|
} # fmt: skip
|
|
counts = {
|
|
"con_eeg_valido": "valid", "sin_eeg_valido": "not_valid",
|
|
"normales": "normal", "anormales": "abnormal",
|
|
} # fmt: skip
|
|
for query, expected in reference.items():
|
|
params = []
|
|
for name, value in parse_qsl(query):
|
|
if name == "date":
|
|
dates = {"ge": "follow-up-start", "le": "follow-up-cutoff"}
|
|
params.append((dates[value[:2]], value[2:]))
|
|
else:
|
|
params.append((params_map[name], values.get(value, value)))
|
|
resources = [entry["resource"] for entry in expected["episodes"]["body"].get("entry", [])]
|
|
records = {
|
|
f"Patient/{r['id']}": int(next(
|
|
identifier["value"].removeprefix("N-") for identifier in r["identifier"]
|
|
if identifier["system"].endswith("/expediente")
|
|
))
|
|
for r in resources if r["resourceType"] == "Patient"
|
|
} # fmt: skip
|
|
children = {
|
|
persons[records[r["patient"]["reference"]]]
|
|
for r in resources if r["resourceType"] == "EpisodeOfCare"
|
|
} # fmt: skip
|
|
bundles = pages(api, "/tea/fhir/Patient", params)
|
|
assert {entry["resource"]["id"] for bundle in bundles
|
|
for entry in bundle.get("entry", [])} == children, query # fmt: skip
|
|
|
|
parameters = {}
|
|
alterations = {}
|
|
for parameter in expected["summary"]["body"]["parameter"]:
|
|
name = parameter["name"]
|
|
if name == "por_alteracion":
|
|
parts = {p["name"]: p for p in parameter["part"]}
|
|
metric = METRICS[parts["alteracion"]["valueCode"].upper()]
|
|
alterations[metric] = parts["pacientes"]["valueInteger"]
|
|
else:
|
|
parameters[counts[name]] = parameter["valueInteger"]
|
|
found = ok(api.get("/tea/fhir/Patient/$eeg-summary", params=params))
|
|
assert found["resourceType"] == "Parameters", query
|
|
assert {p["name"]: p["valueInteger"] for p in found["parameter"]
|
|
if p["name"] != "by_alteration"} == parameters, query # fmt: skip
|
|
assert {
|
|
p["part"][0]["valueCode"]: p["part"][1]["valueInteger"]
|
|
for p in found["parameter"] if p["name"] == "by_alteration"
|
|
} == alterations, query # fmt: skip
|
|
if query == "date=le2026-12-31":
|
|
patients = {child: (persons[number], number) for child, number in records.items()}
|
|
_fhir_eeg_gate(api, platform, patients, resources)
|
|
|
|
|
|
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
|
|
_association_gate(api, scored_hospital)
|
|
|
|
indicators(api)
|
|
_follow_up_gate(api, scored_hospital)
|
|
|
|
# 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
|
|
actual_summary = ok(api.get("/tea/eegs/summary"))
|
|
assert actual_summary == expected
|
|
assert (actual_summary["fhir_eegs"], actual_summary["fhir_metrics"]) == (62, 215)
|
|
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
|
|
|
|
assert shown["checks"] and shown["regions"]
|
|
curve = ok(api.get("/models/tea/eeg-posterior-rhythm/versions/1/curve"))
|
|
assert [row["age_months"] for row in curve] == list(range(16, 37))
|
|
|
|
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
|
|
_reanalysis_by_id_in_local_mode_matches_sync(api, scored_hospital)
|
|
_cancel_during_analysis_leaves_bronze_and_gold_untouched(api, scored_hospital)
|
|
|
|
|
|
def _cancel_during_analysis_leaves_bronze_and_gold_untouched(api, platform):
|
|
def snapshot():
|
|
return (
|
|
platform.query(
|
|
"select edf, valid, level, analysed_at from bronze.eeg_analysis order by edf"
|
|
),
|
|
platform.count("bronze.eeg_metrics"),
|
|
platform.count("gold.tea_eeg_metrics"),
|
|
)
|
|
|
|
before = snapshot()
|
|
ids = [study["id"] for study in ok(api.get("/tea/eegs")) if study["valid"]]
|
|
body = {"scope": {"mode": "ids", "ids": ids}}
|
|
run_id = ok(api.post("/tea/eegs/analyze", json=body))["run_id"]
|
|
url = f"/runs/{run_id}"
|
|
deadline = time.monotonic() + 300
|
|
while (run := ok(api.get(url)))["state"] != "running":
|
|
assert run["state"] not in {"succeeded", "failed", "cancelled"}, run
|
|
assert time.monotonic() < deadline, run
|
|
time.sleep(1)
|
|
|
|
ok(api.post(f"{url}/cancel"))
|
|
deadline = time.monotonic() + 900
|
|
while (run := ok(api.get(url)))["state"] != "cancelled":
|
|
assert run["state"] not in {"succeeded", "failed"}, run
|
|
assert time.monotonic() < deadline, run
|
|
time.sleep(1)
|
|
assert snapshot() == before
|
|
|
|
|
|
def _reanalysis_by_id_in_local_mode_matches_sync(api, platform):
|
|
study_id = next(study["id"] for study in ok(api.get("/tea/eegs")) if study["valid"])
|
|
person, day = study_id.split("|")
|
|
person = person.replace("'", "''")
|
|
((edf,),) = platform.query(
|
|
f"select edf from silver.eeg where person_id = '{person}' "
|
|
f"and cast(study_date as varchar(10)) = '{_day(day).isoformat()}'"
|
|
)
|
|
|
|
def snapshot():
|
|
(row,) = platform.query(
|
|
"select valid, level, age_months, clean_fraction "
|
|
f"from bronze.eeg_analysis where edf = '{edf}'"
|
|
)
|
|
values = dict(
|
|
platform.query(f"select code, value from bronze.eeg_metrics where edf = '{edf}'")
|
|
)
|
|
return tuple(row), values
|
|
|
|
before, values = snapshot()
|
|
local = {"scope": {"mode": "ids", "ids": [study_id]}, "execution": {"mode": "local"}}
|
|
wait_for(api, ok(api.post("/tea/eegs/analyze", json=local))["run_id"])
|
|
after, reanalysed = snapshot()
|
|
|
|
def close(expected):
|
|
return None if expected is None else pytest.approx(expected, rel=1e-12)
|
|
|
|
assert after[:2] == before[:2]
|
|
assert list(after[2:]) == [close(v) for v in before[2:]]
|
|
assert reanalysed == {code: close(v) for code, v in values.items()}
|
|
|
|
unknown = {"scope": {"mode": "ids", "ids": ["N9999|2000-01-01"]}}
|
|
run_id = ok(api.post("/tea/eegs/analyze", json=unknown))["run_id"]
|
|
deadline = time.monotonic() + 900
|
|
while (run := ok(api.get(f"/runs/{run_id}")))["state"] not in (
|
|
"succeeded",
|
|
"failed",
|
|
"cancelled",
|
|
):
|
|
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
|
|
time.sleep(2)
|
|
assert run["state"] == "failed", run
|
|
assert "no EEG" in run["error"]
|
|
|
|
|
|
def _preview_matches_the_analysis_and_leaves_bronze_unchanged(platform, monkeypatch):
|
|
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())
|