diff --git a/tests/test_tea.py b/tests/test_tea.py index ac014b1..bf54177 100644 --- a/tests/test_tea.py +++ b/tests/test_tea.py @@ -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 diff --git a/webapi/fhir.py b/webapi/fhir.py index 6677624..ea88003 100644 --- a/webapi/fhir.py +++ b/webapi/fhir.py @@ -3,6 +3,7 @@ uses, paging, and a CapabilityStatement built from these routes themselves. Reso built by Core's mappers from the rows Persistance reads; nothing is computed here beyond counting a few thousand rows (measures) and ordering the follow-up list.""" +from collections import defaultdict from datetime import date, datetime from typing import Annotated, Any from urllib.parse import urlencode @@ -22,6 +23,7 @@ from core import measures as m from core.domains import Domain, measures, part from core.follow_up import window_start from core.pipeline import ID_PATTERN +from core.tea import fhir as tea_fhir from persistance import config_log, readers from persistance import fhir as reads from persistance import measures as measure_reads @@ -209,7 +211,8 @@ def search_patient( return outcome(422, str(exc)) persons = [r["person_id"] for r in rows] risks: dict[str, list[dict]] = {} - if listed and sort != "-recent" or "RiskAssessment:subject" in revinclude: + if domain != Domain.TEA and (listed and sort != "-recent" or + "RiskAssessment:subject" in revinclude): # fmt: skip for r in reads.rows(domain.value, "risk", persons=persons): risks.setdefault(r["person_id"], []).append(r) if listed: @@ -281,7 +284,8 @@ def _patient_rows( def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str], at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip - unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"} + allowed = _revincludes(domain) + unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"} if unknown: raise HTTPException(422, f"cannot include {sorted(unknown)}") found: list[Resource] = [] @@ -294,11 +298,21 @@ def _included(domain: Domain, revinclude: list[str], include: list[str], persons kind = r.get_resource_type() if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations): found.append(r) + if "Condition:subject" in revinclude: + found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons, + cutoff=at.isoformat())] # fmt: skip if "RiskAssessment:subject" in revinclude: - found += _risk_assessments([r for p in persons for r in risks.get(p, [])]) + if domain == Domain.TEA: + found += _tea_risks(persons, at.isoformat()) + else: + found += _risk_assessments([r for p in persons for r in risks.get(p, [])]) return found +def _revincludes(domain: Domain) -> tuple[str, ...]: + return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES + + # --- clinical searches: by subject ---------------------------------------------------------- @@ -313,6 +327,11 @@ def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]: by `at`: its DiagnosticReport (or Encounter) and Observations, in date order.""" found: list[Resource] = [] report_facts = _clinical(domain).REPORT_FACTS + if domain == Domain.TEA: + births = { + r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None + for r in reads.rows(domain.value, "births", persons=persons) + } for study in catalog.of_domain(domain.value): spec = catalog.studies()[study] facts = {} @@ -324,10 +343,51 @@ def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]: for row in reads.instances(study, persons, at): days = facts.get((row["person_id"], str(row[first])[:10])) extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))] - found += f.instance(study, f.known(study, row, at), extra) + known = f.known(study, row, at) + found += f.instance(study, known, extra) + if domain == Domain.TEA and study == "ados2": + known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"])) + found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"]))) + if domain == Domain.TEA: + found += _tea_eeg_studies(persons, at) return found +def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]: + def rows(kind): + return reads.rows("tea", kind, persons=persons, cutoff=at) + + def key(row): + return row["person_id"], row["study_date"], row["edf"] + + regions, results = defaultdict(list), defaultdict(list) + for row in rows("regions"): + regions[(*key(row), row["code"])].append(row) + for row in rows("checks"): + results[key(row)].append(tea_fhir.eeg_check(row)) + for row in rows("metrics"): + results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])])) + found = [] + for row in rows("eegs"): + observations = results[key(row)] + found.extend((tea_fhir.eeg_report(row, observations), *observations)) + return found + + +def _tea_risks(persons: list[str], at: str) -> list[Resource]: + groups = defaultdict(list) + for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at): + group = groups[row["person_id"]] + # The earliest scored EEG supplies the one set of predictions for this child. + if ( + not group + or row["edf"] == group[0]["edf"] + and row["study_date"] == group[0]["study_date"] + ): + group.append(row) + return [tea_fhir.association_risk(group) for group in groups.values()] + + def _risk_assessments(rows: list[dict]) -> list[Resource]: groups: dict[tuple, list[dict]] = {} for r in rows: @@ -344,7 +404,10 @@ def _clinical_search(kind: str, build, request, domain, subject, count, offset): params["cutoff"] = _cutoff(domain, None).isoformat() if kind == "procedure": params["types"] = list(fu.PROCEDURES) - found = build(reads.rows(domain.value, kind, **params)) + if kind == "risk" and domain == Domain.TEA: + found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat()) + else: + found = build(reads.rows(domain.value, kind, **params)) return bundle(request, _sliced(found, count, offset), len(found), count, offset) @@ -543,7 +606,7 @@ def metadata(request: Request, domain: Domain) -> Response: entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []}) if kind == "Patient" and not rest: entry |= {"searchInclude": ["DiagnosticReport:result"], - "searchRevInclude": list(REVINCLUDES)} # fmt: skip + "searchRevInclude": list(_revincludes(domain))} # fmt: skip entry["searchParam"] += [ {"name": name, "type": spec[0]} for name, spec in getattr(fu, "FILTERS", {}).items() ]