Files
WebApi/tests/test_fhir_eeg_curves.py

292 lines
16 KiB
Python

"""What this module covers: the EEG metrics' age-norm curves in TEA's FHIR answers — how `BaselineCurves`
(`webapi.fhir.eeg_curves`) resolves the baseline label the analysis pinned (`eeg_metrica.met_modelo`,
`tea-<scenario>/<version>`, carried by `tea_paciente_eeg_metricas` as `modelo`) to its registered artifact's centile
curve, caching per label and omitting the curve on any failure; and how `webapi.fhir.tea` serves it: the curve as a
nested extension on each metric observation (`fuente`, `estado` tied to `TEA_ALTERACIONES_VALIDADAS`, then the
series) and the analysis's age (`eeg.eeg_edad_meses`) as an extension on the EEG's `DiagnosticReport`.
Fixtures: fakes for the registry, the module loader and the curve loader (no model registry is touched); `loaded`,
a TEA database (`base_de`) with one child and one analysed EEG whose posterior rhythm names a baseline, loaded
through the cycle up to `event_models`; needs `DBT_MANIFEST`.
"""
import os
from datetime import date
from types import SimpleNamespace
import pandas as pd
import pytest
from fhir.resources.R4B import get_fhir_model_class
from webapi.fhir import tea
from webapi.fhir.eeg_curves import BaselineCurves
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
CURVE = {"edad_meses": [16.0, 24.0, 36.0], "p5": [4.0, 5.0, 6.0], "p25": [4.5, 5.5, 6.5],
"mediana": [5.0, 6.0, 7.0], "p75": [5.5, 6.5, 7.5], "p95": [6.0, 7.0, 8.0]}
LABEL = "tea-eeg-posterior-rhythm/3"
class FakeRegistry:
"""Stands in for `models.io.registry.registry`: records the resolutions and answers or fails them."""
def __init__(self, error: Exception | None = None):
self.calls: list[tuple[str, str, str]] = []
self._error = error
def resolve(self, domain: str, scenario: str, version: str):
self.calls.append((domain, scenario, version))
if self._error is not None:
raise self._error
return SimpleNamespace(model_uri=f"models:/{domain}-{scenario}/{version}")
def module_with(curva: pd.DataFrame | None):
"""A loaded biomarker module as `models.tea.eeg.baselines` reads it: one baseline, maybe with a curve."""
return SimpleNamespace(baseline=SimpleNamespace(curva=curva))
class FakeCurves:
"""Stands in for `BaselineCurves` at the FHIR layer: answers per (label, metric), records what was asked."""
def __init__(self, curves: dict):
self._curves = curves
self.calls: list[tuple[str, str]] = []
def curve(self, label: str, metric: str):
self.calls.append((label, metric))
return self._curves.get((label, metric))
def test_the_label_resolves_to_the_pinned_version_s_curve():
"""Pins down: `curve(label, metric)` resolves the label to (domain, scenario, version), loads that version's
module and returns its baseline's centiles with the ages and the five percentiles. Fails if the label parsing,
the resolution arguments or the series extraction drift from `eeg_metrica.met_modelo`'s shape."""
registry = FakeRegistry()
loads: list[str] = []
curves = BaselineCurves(registry=registry, loader=lambda uri: loads.append(uri) or module_with(pd.DataFrame({
"edad_meses": CURVE["edad_meses"], "n_efectivo": [50.0, 60.0, 40.0],
**{p: CURVE[p] for p in ("p5", "p25", "mediana", "p75", "p95")}})))
assert curves.curve(LABEL, "ritmo_posterior") == CURVE
assert registry.calls == [("tea", "eeg-posterior-rhythm", "3")]
assert loads == ["models:/tea-eeg-posterior-rhythm/3"]
def test_the_module_loads_once_per_label():
"""Pins down: repeated asks of one curve reuse the module loaded for its label instead of reloading it, and a
second label loads its own. Fails if the caching moves from per label to per call."""
registry = FakeRegistry()
loads: list[str] = []
frame = pd.DataFrame(CURVE)
curves = BaselineCurves(registry=registry, loader=lambda uri: loads.append(uri) or module_with(frame))
n2 = "tea-eeg-spindles-n2/2"
first = curves.curve(n2, "husos_sueno_n2")
assert curves.curve(n2, "husos_sueno_n2") is first
assert curves.curve("tea-eeg-spindles-n3/1", "husos_sueno_n3") == CURVE
assert loads == ["models:/tea-eeg-spindles-n2/2", "models:/tea-eeg-spindles-n3/1"]
assert registry.calls == [("tea", "eeg-spindles-n2", "2"), ("tea", "eeg-spindles-n3", "1")]
def test_a_multi_scenario_label_uses_the_metric_s_own_scenario():
"""Pins down: a label that joined the electrode baseline's name (`;`-separated, as the analysis writes when it
also scored electrodes) resolves the metric's own scenario. Fails if the split or the scenario match breaks."""
registry = FakeRegistry()
curves = BaselineCurves(registry=registry, loader=lambda uri: module_with(pd.DataFrame(CURVE)))
label = "tea-eeg-spindles-n2/2;tea-eeg-spindle-topography-n2/5"
assert curves.curve(label, "husos_sueno_n2") == CURVE
assert registry.calls == [("tea", "eeg-spindles-n2", "2")]
def test_a_label_that_doesnt_name_the_metric_s_baseline_draws_no_curve():
"""Pins down: a label without the metric's scenario (another metric's baseline) and a metric the analysis
doesn't map both give None without touching the registry. Fails if the lookup starts resolving the wrong
scenario."""
registry = FakeRegistry()
curves = BaselineCurves(registry=registry, loader=lambda uri: module_with(pd.DataFrame(CURVE)))
assert curves.curve(LABEL, "husos_sueno_n2") is None
assert curves.curve(LABEL, "ritmo_inexistente") is None
assert registry.calls == []
def test_an_unresolvable_label_or_an_unloadable_module_omits_the_curve():
"""Pins down: a registry that can't resolve the version, and a loader that fails, both give None, so answers
keep working without a reachable registry. Fails if a failure starts propagating instead of omitting."""
failing = BaselineCurves(registry=FakeRegistry(LookupError("no version 3")), loader=lambda uri: None)
assert failing.curve(LABEL, "ritmo_posterior") is None
broken = BaselineCurves(registry=FakeRegistry(), loader=lambda uri: (_ for _ in ()).throw(RuntimeError("x")))
assert broken.curve(LABEL, "ritmo_posterior") is None
def test_a_baseline_without_a_curve_or_with_too_few_points_draws_none():
"""Pins down: age-block baselines (no `curva`) and curves with fewer than two complete points give None, and
rows missing a percentile are dropped. Fails if an undrawable curve starts being served."""
registry = FakeRegistry()
no_curve = BaselineCurves(registry=registry, loader=lambda uri: module_with(None))
assert no_curve.curve(LABEL, "ritmo_posterior") is None
sparse = pd.DataFrame({"edad_meses": [16.0, 24.0], "p5": [4.0, None], "p25": [4.5, None], "mediana": [5.0, None],
"p75": [5.5, None], "p95": [6.0, None]})
one_point = BaselineCurves(registry=registry, loader=lambda uri: module_with(sparse))
assert one_point.curve(LABEL, "ritmo_posterior") is None
partial = pd.DataFrame({"edad_meses": [16.0, 24.0, 36.0], "p5": [4.0, None, 6.0], "p25": [4.5, None, 6.5],
"mediana": [5.0, None, 7.0], "p75": [5.5, None, 7.5], "p95": [6.0, None, 8.0]})
dropped = BaselineCurves(registry=registry, loader=lambda uri: module_with(partial))
assert dropped.curve(LABEL, "ritmo_posterior") == {"edad_meses": [16.0, 36.0], "p5": [4.0, 6.0],
"p25": [4.5, 6.5], "mediana": [5.0, 7.0],
"p75": [5.5, 7.5], "p95": [6.0, 8.0]}
def metric_row(**cambios) -> dict:
"""One `tea_paciente_eeg_metricas` row of a scored posterior rhythm, with the analysis's baseline label."""
row = {"procedimiento_id": 7, "pac_id": 1, "metrica": "ritmo_posterior", "valor": 6.8, "valor_z": -4.08,
"grupo_edad_eeg": "16_23", "ref_min": 4.5, "ref_mediana": 5.75, "ref_max": 8.0,
"estado": "disminuido", "modelo": LABEL}
return {**row, **cambios}
def eeg_row(**cambios) -> dict:
"""One `tea_paciente_eegs` row: the study's valid EEG, with the age its analysis compared references at."""
row = {"procedimiento_id": 7, "pac_id": 1, "fecha_eeg": date(2025, 5, 20), "con_sueno": 1, "canales": 19,
"duracion_min": 25.0, "edad_meses": 23.6, "nivel": "completo", "fraccion_limpia": 0.95,
"canales_malos": 0, "ruido_linea_db": -30.0, "calidad": "BUENO", "valido": 1}
return {**row, **cambios}
def sub_series(extension: dict) -> dict:
"""A curve extension's sub-extensions back as series: each name's values in order."""
out: dict[str, list] = {}
for e in extension["extension"]:
out.setdefault(e["url"].rsplit("/", 1)[1], []).append(e.get("valueDecimal", e.get("valueString")))
return out
def test_a_metric_observation_carries_its_curve_as_a_nested_extension(monkeypatch):
"""Pins down: with the alterations validated, a metric row with a baseline label gets one `curva-referencia`
extension whose `fuente` is the label, whose `estado` reads `validada`, and whose series come back as ordered
sub-extensions (`edad-meses`, then p5 to p95). Fails if the extension's shape or the gate tie changes."""
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False,
curves=FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
(curve,) = observation["extension"]
assert curve["url"] == f"{tea.STRUCTURE}/curva-referencia"
series = sub_series(curve)
assert series["fuente"] == [LABEL] and series["estado"] == ["validada"]
expected = {"edad-meses": CURVE["edad_meses"], **{p: CURVE[p] for p in ("p5", "p25", "mediana", "p75", "p95")}}
for name, values in expected.items():
assert series[name] == values
get_fhir_model_class("Observation").model_validate(observation)
def test_the_curve_estado_follows_the_validation_gate(monkeypatch):
"""Pins down: without `TEA_ALTERACIONES_VALIDADAS` the same observation's `estado` reads `pendiente`, the
state the summary's other endpoints report while the references await validation. Fails if `estado` stops
reflecting the gate."""
monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False,
curves=FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
(curve,) = observation["extension"]
assert sub_series(curve)["estado"] == ["pendiente"]
def test_an_undrawable_curve_is_omitted():
"""Pins down: a loader that can't resolve the label, and a metric row without a label, both give an
observation with no extension, and the loader isn't even asked without a label. Fails if a failed resolution
starts leaking an empty or partial curve."""
loader = FakeCurves({})
(observation,) = tea.metric_observations(eeg_row(), [metric_row()], [], "P-X", False, curves=loader)
assert "extension" not in observation and loader.calls == [(LABEL, "ritmo_posterior")]
(unlabeled,) = tea.metric_observations(eeg_row(), [metric_row(modelo=None)], [], "P-X", False, curves=loader)
assert "extension" not in unlabeled and loader.calls == [(LABEL, "ritmo_posterior")]
def test_the_eeg_report_carries_the_analysis_age_as_an_extension():
"""Pins down: the `DiagnosticReport` carries `edad-meses` next to `duracion-min` and `canales`, and drops it
with them when null. Fails if the age stops reaching the report or leaves the extension block the others share."""
(procedure, report, *_) = tea.eeg_resources(eeg_row(), "P-X", [], [], False)
extensions = {e["url"].rsplit("/", 1)[-1]: e for e in report["extension"]}
assert extensions["edad-meses"]["valueDecimal"] == 23.6
assert extensions["duracion-min"]["valueDecimal"] == 25.0 and extensions["canales"]["valueInteger"] == 19
(_, bare, *_) = tea.eeg_resources(eeg_row(edad_meses=None, duracion_min=None, canales=None), "P-X", [], [],
False)
assert "extension" not in bare
for resource in (procedure, report):
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
def _rows(sesion):
from core.tea.models import Eeg, EegMetrica, Mchat, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1,
eeg_nivel="completo", eeg_fraccion_limpia=0.95, eeg_edad_meses=23.6, eeg_con_sueno=1,
eeg_canales=19, eeg_duracion_min=25.0))
sesion.add(EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=-4.08,
met_fuera=-1, met_p5=4.5, met_mediana=5.75, met_p95=8.0, met_modelo=LABEL))
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models: one child whose analysed EEG's rhythm names a baseline."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_curvas"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
@pytest.fixture()
def queries():
"""The domain's dbt query repository, aimed at the `loaded` database by `base_de`'s `point_to`."""
from persistance import tea as dominio
return dominio.dbt_query_repository
def test_the_analysis_age_reaches_the_eegs_view(loaded, queries):
"""Pins down: `eeg.eeg_edad_meses` flows through the silver mapping and `tea_paciente_eegs` as `edad_meses`.
Fails if the silver mapping or the views drop the age again."""
from sqlalchemy import select
from webapi.fhir.tea import EEGS
(row,) = tea._rows(queries, select(EEGS.c.edad_meses))
assert row["edad_meses"] == 23.6
def test_the_metric_view_carries_the_baseline_label(loaded, queries):
"""Pins down: `eeg_metrica.met_modelo` flows through the silver mapping and `tea_paciente_eeg_metricas` as
`modelo`, the only label the FHIR layer reads. Fails if the silver mapping or the views drop the label again."""
from sqlalchemy import select
from webapi.fhir.tea import METRICS
(row,) = tea._rows(queries, select(METRICS).where(METRICS.c.metrica == "ritmo_posterior"))
assert row["modelo"] == LABEL
def test_the_patient_summary_draws_the_curve_and_the_age(loaded, queries, monkeypatch):
"""Pins down `$resumen-tea`: with the alterations validated and a resolvable baseline, the metric observation
carries the curve (`fuente` the stored label) and the report the `edad-meses` extension; with an unresolvable
baseline the same summary answers with no curve. Fails if the summary stops wiring the label, the loader or
the age."""
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
monkeypatch.setattr("webapi.fhir.tea.baseline_curves",
lambda: FakeCurves({(LABEL, "ritmo_posterior"): CURVE}))
bundle = tea.patient_summary(queries, 1, date(2025, 12, 31), False)
resources = [e["resource"] for e in bundle["entry"]]
(observation,) = [r for r in resources if r["id"].startswith("ritmo-posterior-")]
(curve,) = observation["extension"]
assert sub_series(curve)["fuente"] == [LABEL]
(report,) = [r for r in resources if r["resourceType"] == "DiagnosticReport"]
assert any(e["url"].endswith("/edad-meses") and e["valueDecimal"] == 23.6 for e in report["extension"])
for resource in resources:
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
monkeypatch.setattr("webapi.fhir.tea.baseline_curves",
lambda: BaselineCurves(registry=FakeRegistry(LookupError("sin registry"))))
bare = tea.patient_summary(queries, 1, date(2025, 12, 31), False)
assert all("extension" not in e["resource"] for e in bare["entry"]
if e["resource"]["resourceType"] == "Observation"
and e["resource"]["id"].startswith("ritmo-posterior-"))