TEA per-child FHIR resources: ADOS-2, EEG report, checks, metrics, Condition, RiskAssessment: routes and the per-child gate

This commit is contained in:
2026-11-30 01:14:13 -06:00
parent 3300ec3048
commit 983680ead3
2 changed files with 305 additions and 28 deletions
+236 -22
View File
@@ -16,6 +16,7 @@ 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
@@ -25,6 +26,7 @@ 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 models.definitions import tea_preview
from persistance import config, previews
@@ -68,6 +70,19 @@ 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
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" # 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
@@ -264,26 +279,13 @@ def _association_gate(api, platform):
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], int(1800 * SLOW))
tables = REFERENCE / "tables"
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",
}
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"])
(BIOMARKERS[row["rel_biomarcador"]], ZONES.get(zone, zone), row["rel_resultado"])
)
pair_keys[row["rel_id"]] = pair
expected_pairs[pair] = row
@@ -337,9 +339,219 @@ def _association_gate(api, platform):
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"))
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)
# The FHIR fixture carries aggregate values. The reference tables carry the same EEGs'
# electrode and zone values, keyed by the metric ID and the child's record number.
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 = {(edf[:12], metric): z for edf, metric, z in platform.query(
"select edf, metric, z from bronze.eeg_scores where part = 'value' and model is not null"
)} # fmt: skip
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"].removeprefix("eeg-"), 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)
reference = json.load(file, parse_float=Decimal)
persons = {
int(number.removeprefix("N")): person
for person, number in platform.query(
@@ -369,15 +581,15 @@ def _follow_up_gate(api, platform):
else:
params.append((params_map[name], values.get(value, value)))
resources = [entry["resource"] for entry in expected["episodes"]["body"].get("entry", [])]
patients = {
f"Patient/{r['id']}": persons[int(next(
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 = {
patients[r["patient"]["reference"]]
persons[records[r["patient"]["reference"]]]
for r in resources if r["resourceType"] == "EpisodeOfCare"
} # fmt: skip
bundles = pages(api, "/tea/fhir/Patient", params)
@@ -402,6 +614,9 @@ def _follow_up_gate(api, platform):
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):
@@ -419,9 +634,8 @@ def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
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 == {
key: count for key, count in expected.items() if key not in ("fhir_eegs", "fhir_metrics")
}
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