From 46473bb106c11c571c412dd39882d479ca0b3e32 Mon Sep 17 00:00:00 2001 From: alberto Date: Sat, 21 Nov 2026 11:17:48 -0600 Subject: [PATCH] feat(tea): each EEG metric's age-norm curve and the age at the EEG in the patient summary --- tests/test_fhir_eeg_curves.py | 291 +++++++++++++++++++++++++++++ tests/test_fhir_tea.py | 2 +- tests/test_tea_eeg_silver.py | 33 ++-- webapi/fhir/__init__.py | 3 +- webapi/fhir/eeg_curves.py | 107 +++++++++++ webapi/fhir/tea.py | 53 ++++-- webapi/orchestration/silver/tea.py | 9 +- 7 files changed, 465 insertions(+), 33 deletions(-) create mode 100644 tests/test_fhir_eeg_curves.py create mode 100644 webapi/fhir/eeg_curves.py diff --git a/tests/test_fhir_eeg_curves.py b/tests/test_fhir_eeg_curves.py new file mode 100644 index 0000000..b4aa19d --- /dev/null +++ b/tests/test_fhir_eeg_curves.py @@ -0,0 +1,291 @@ +"""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-/`, 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-")) diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py index 0ec2291..8096bf6 100644 --- a/tests/test_fhir_tea.py +++ b/tests/test_fhir_tea.py @@ -201,7 +201,7 @@ def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client): from webapi.fhir import tea eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial", - "duracion_min": 25.0, "canales": 19} + "duracion_min": 25.0, "edad_meses": None, "canales": 19} checks = [ {"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None, "bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"}, diff --git a/tests/test_tea_eeg_silver.py b/tests/test_tea_eeg_silver.py index e812736..d7e35d1 100644 --- a/tests/test_tea_eeg_silver.py +++ b/tests/test_tea_eeg_silver.py @@ -4,8 +4,8 @@ Fixtures: `loaded`, a TEA database (`base_de`) loaded up to the event models, with one patient and one analysed EEG `e-1`: valid, triage `completo`; three checks (95 % clean windows against a low limit of 60, the triage level as text, -and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0 and p5/median/p95 5/6/7, and its N2 -spindles' value 2.5 with z -0.4 at Fz. +and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0, p5/median/p95 5/6/7 and the registered +label of the baseline it was compared against, and its N2 spindles' value 2.5 with z -0.4 at Fz. """ import os from datetime import date @@ -34,7 +34,7 @@ def _rows(sesion): ]) sesion.add_all([ EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=1.2, met_fuera=0, - met_p5=5.0, met_mediana=6.0, met_p95=7.0), + met_p5=5.0, met_mediana=6.0, met_p95=7.0, met_modelo="tea-eeg-posterior-rhythm/3"), EegMetrica(met_id="n2", met_eeg_id="e-1", met_codigo="HUSOS_SUENO_N2", met_valor=2.5), EegMetricaElectrodo(mel_id="n2-fz", mel_met_id="n2", mel_electrodo="Fz", mel_valor=1.4, mel_z=-0.4), ]) @@ -92,13 +92,16 @@ def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded): def test_a_metric_carries_its_deviation_from_the_baseline(loaded): - """Pins down: a metric's z, -1/0/+1 and the baseline's p5/median/p95 at the age are results of the recording. + """Pins down: a metric's z, -1/0/+1, the baseline's p5/median/p95 at the age and the baseline's registered label + are results of the recording. - Fails if the silver mapping or the catalog drops one of the deviation's results. + Fails if the silver mapping or the catalog drops one of the deviation's results or the label (the load skips a + result the catalog doesn't have). """ toma = _observations(loaded, "toma") - assert [toma[None, f"eeg.ritmo_posterior{s}"] for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95")] == \ - [6.8, 1.2, 0, 5.0, 6.0, 7.0] + assert [toma[None, f"eeg.ritmo_posterior{s}"] + for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95", "_modelo")] == \ + [6.8, 1.2, 0, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3"] def test_the_quality_view_lists_each_check_with_its_label(loaded): @@ -126,18 +129,20 @@ def test_the_quality_view_lists_each_check_with_its_label(loaded): def test_a_metric_is_scored_by_the_analysis_s_deviation(loaded): - """Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state and the baseline's - p5/median/p95 as the reference; a metric without a z (no baseline in production) can't be evaluated. And the - electrodes view carries each electrode's z next to its value. + """Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state, the baseline's + p5/median/p95 as the reference and the baseline's registered label; a metric without a z (no baseline in + production) can't be evaluated. And the electrodes view carries each electrode's z next to its value. - Fails if dbt goes back to scoring metrics against fixed ranges of its own, or drops the electrode z. + Fails if dbt goes back to scoring metrics against fixed ranges of its own, drops the baseline label, or drops the + electrode z. """ with loaded.motor.connect() as connection: metrics = {r.metrica: r for r in connection.execute(text( - "select metrica, valor, ref_min, ref_mediana, ref_max, valor_z, estado from tea_paciente_eeg_metricas"))} + "select metrica, valor, ref_min, ref_mediana, ref_max, modelo, valor_z, estado " + "from tea_paciente_eeg_metricas"))} (electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all() rhythm = metrics["ritmo_posterior"] - assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.valor_z, rhythm.estado) == \ - (6.8, 5.0, 6.0, 7.0, 1.2, "normal") + assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.modelo, rhythm.valor_z, + rhythm.estado) == (6.8, 5.0, 6.0, 7.0, "tea-eeg-posterior-rhythm/3", 1.2, "normal") assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable") assert tuple(electrode) == (1.4, -0.4) diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index 2ef8efb..cf15b8e 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -354,5 +354,6 @@ def _included(tea, queries, e, simulated: bool) -> list[dict]: tea.care_plan(e, simulated)] resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r] if (eeg := e.study_eeg()) is not None: - resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks) + resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks, + curves=tea.baseline_curves()) return resources diff --git a/webapi/fhir/eeg_curves.py b/webapi/fhir/eeg_curves.py new file mode 100644 index 0000000..a5c51ab --- /dev/null +++ b/webapi/fhir/eeg_curves.py @@ -0,0 +1,107 @@ +"""The age-norm curves behind the EEG metrics' reference ranges, for the FHIR answers. + +Each metric row names the baseline its analysis compared it against: its `modelo` (from `eeg_metrica.met_modelo`, +carried by `tea_paciente_eeg_metricas`) is the registered model's label, `tea-/`, pinned to the +version the analysis used (which may no longer be the one in production). The full centile curve of that exact +version is its registered artifact, loaded the way the analysis loads it (`models.tea.eeg.baselines`). A label that +can't be resolved, or a module that can't be loaded, gives no curve: the answer keeps the reference range it already +had. +""" + +PERCENTILES = ("p5", "p25", "mediana", "p75", "p95") + + +class BaselineCurves: + """Loads and caches the centile curves of the registered baselines the EEG analysis pinned. + + `curve(label, metric)` is the curve the named version draws for the metric — `{"edad_meses": [...], + "p5": [...], "p25": [...], "mediana": [...], "p75": [...], "p95": [...]}` with the ages increasing and each + row's percentiles non-crossing — or None when the label doesn't name the metric's baseline or any step of the + resolution fails (unknown metric, unknown scenario, unreachable registry, unloadable artifact). Modules are + loaded once per label. `registry` and `loader` are injectable so tests run without a model registry. + """ + + def __init__(self, registry=None, loader=None): + self._registry = registry + self._loader = loader + self._modules: dict[str, dict[str, object | None]] = {} + self._curves: dict[tuple[str, str], dict | None] = {} + + def curve(self, label: str, metric: str) -> dict | None: + key = (label, metric) + if key not in self._curves: + self._curves[key] = self._extract(label, metric) + return self._curves[key] + + def _extract(self, label: str, metric: str) -> dict | None: + spec = self._spec_of(metric) + module = self._module(label, spec.scenario) if spec is not None else None + if module is None: + return None + from models.tea.eeg.baselines import _feature_baseline + + baseline = _feature_baseline(module, spec.feature) + curve = getattr(baseline, "curva", None) # a baseline without a curve (age blocks) draws none + if curve is None: + return None + rows = curve.dropna(subset=list(PERCENTILES)) + if len(rows) < 2: + return None + return {"edad_meses": [float(v) for v in rows["edad_meses"]], + **{p: [float(v) for v in rows[p]] for p in PERCENTILES}} + + @staticmethod + def _spec_of(metric: str): + """The analysis's own mapping of the stored metric code to its library feature and baseline scenario.""" + from models.tea.eeg.settings import settings + + return next((m for m in settings().metrics if m.code.lower() == metric), None) + + def _module(self, label: str, scenario: str): + modules = self._modules.setdefault(label, {}) + if scenario not in modules: + modules[scenario] = self._load(label, scenario) + return modules[scenario] + + def _load(self, label: str, scenario: str): + version = self._version(label, scenario) + if version is None: + return None + try: + registry = self._registry if self._registry is not None else _default_registry() + loader = self._loader if self._loader is not None else _default_loader() + return loader(registry.resolve("tea", scenario, version).model_uri) + except Exception: # the registry may be unreachable or the artifact unloadable; the curve is omitted + return None + + @staticmethod + def _version(label: str, scenario: str) -> str | None: + """The version the label pins for the scenario, looked up among its `;`-joined baseline names.""" + for name_version in label.split(";"): + name, _, version = name_version.rpartition("/") + if name.removeprefix("tea-") == scenario and version: + return version + return None + + +def _default_registry(): + from models.io.registry import registry + + return registry + + +def _default_loader(): + from models.tea.eeg.baselines import _load + + return _load + + +_shared: BaselineCurves | None = None + + +def baseline_curves() -> BaselineCurves: + """The process-wide loader: each label's module is loaded once per deployment.""" + global _shared + if _shared is None: + _shared = BaselineCurves() + return _shared diff --git a/webapi/fhir/tea.py b/webapi/fhir/tea.py index 747e744..8c58528 100644 --- a/webapi/fhir/tea.py +++ b/webapi/fhir/tea.py @@ -4,7 +4,9 @@ Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, n at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a `CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not -valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. +valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. The views carry the age the analysis compared +the references at and, per metric, the registered label of the baseline that comparison used, from which the metric +observations draw the baseline's full centile curve. Until the domain expert validates the age baselines, every alteration stays hidden (`alterations_validated`): the alteration filter, the abnormal/normal split, and the metric and electrode observations. @@ -18,6 +20,7 @@ from datetime import date from sqlalchemy import column, select, table from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged +from webapi.fhir.eeg_curves import PERCENTILES, baseline_curves STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"), ("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"), @@ -29,20 +32,21 @@ ICD10 = "http://hl7.org/fhir/sid/icd-10" CATALOG = f"{CODE_SYSTEM}/tea-catalogo" STAGE_DATE = f"{STRUCTURE}/fecha-etapa" AGE_GROUP = f"{STRUCTURE}/grupo-edad" +CURVE = f"{STRUCTURE}/curva-referencia" DEFAULT_SALT = "dev-simulado" FOLLOW_UP = table("tea_seguimiento", *map(column, ( "pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2", "fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg"))) EEGS = table("tea_paciente_eegs", *map(column, ( - "procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "nivel", "fraccion_limpia", - "canales_malos", "ruido_linea_db", "calidad", "valido"))) + "procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "edad_meses", "nivel", + "fraccion_limpia", "canales_malos", "ruido_linea_db", "calidad", "valido"))) CHECKS = table("tea_paciente_eeg_criterios", *map(column, ( "procedimiento_id", "pac_id", "criterio", "electrodo", "valor", "valor_texto", "bajo", "alto", "anormal", "decisivo", "etiqueta", "unidad"))) METRICS = table("tea_paciente_eeg_metricas", *map(column, ( - "procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "valor_z", - "estado"))) + "procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "modelo", + "valor_z", "estado"))) ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo", "valor", "valor_z"))) ADOS2 = table("tea_paciente_ados2", *map(column, ( @@ -263,12 +267,26 @@ def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulate return observations +def curve_extension(label: str, curve: dict) -> dict: + """The reference curve as one nested extension on the metric observation. `fuente` is the baseline's registered + label and `estado` the alterations validation gate (`TEA_ALTERACIONES_VALIDADAS`); each series is a run of + sub-extensions, one per point, read back in order (`edad-meses`, then the five percentiles), because a FHIR + extension holds scalars, not arrays.""" + series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES)) + return {"url": CURVE, "extension": [ + {"url": f"{CURVE}/fuente", "valueString": label}, + {"url": f"{CURVE}/estado", "valueString": "validada" if alterations_validated() else "pendiente"}, + *({"url": f"{CURVE}/{name}", "valueDecimal": float(value)} for name, values in series for value in values)]} + + def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str, - simulated: bool) -> list[dict]: + simulated: bool, curves=None) -> list[dict]: """One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG - as the reference, H/L/N, and the z and the baseline's median as components. A value without a z is a metric the - baseline couldn't score (none in production, or an age it doesn't cover): no interpretation.""" + as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label + (`modelo`) and a loader, the observation also carries the baseline's full centile curve as an extension. A value + without a z is a metric the baseline couldn't score (none in production, or an age it doesn't cover): no + interpretation.""" from webapi.fhir.terminology import TEA_EEG observations = [] @@ -295,6 +313,10 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]}, "high": {"value": float(m["ref_max"]), "unit": spec["unidad"]}, "text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}] + if curves is not None and m.get("modelo"): + curve = curves.curve(m["modelo"], m["metrica"]) + if curve is not None: + resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve)) observations.append(tagged(resource, simulated)) at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"] and x["valor_z"] is not None] @@ -310,11 +332,13 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool, - checks: list[dict] = ()) -> list[dict]: + checks: list[dict] = (), curves=None) -> list[dict]: """The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has - no result beyond its quality, and the alterations stay out until validated.""" + no result beyond its quality, and the alterations stay out until validated. The report carries the recording's + duration, channel count and the age the analysis compared the references at as extensions, and each metric + observation the baseline's full centile curve when its label resolves (`curves`).""" quality = quality_observations(eeg, list(checks), pseudonym, simulated) - altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated) + altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves) if eeg["valido"] == 1 and alterations_validated() else []) procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed", "code": concept(CATALOG, "eeg", "Electroencefalograma"), @@ -329,10 +353,12 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li from tea.validation.fhir import SYSTEM report["conclusionCode"].append(concept(SYSTEM, "valid" if eeg["valido"] == 1 else "not-valid")) - if eeg["duracion_min"] is not None or eeg["canales"] is not None: + if eeg["duracion_min"] is not None or eeg["edad_meses"] is not None or eeg["canales"] is not None: report["extension"] = [e for e in ( {"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])} if eeg["duracion_min"] is not None else None, + {"url": f"{STRUCTURE}/edad-meses", "valueDecimal": float(eeg["edad_meses"])} + if eeg["edad_meses"] is not None else None, {"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None, ) if e] if eeg["calidad"] == "SIN_ANALIZAR": @@ -391,5 +417,6 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict: eeg = e.study_eeg() if eeg is not None: electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id)) - resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks) + resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks, + curves=baseline_curves()) return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]} diff --git a/webapi/orchestration/silver/tea.py b/webapi/orchestration/silver/tea.py index 29347fb..ea28b0f 100644 --- a/webapi/orchestration/silver/tea.py +++ b/webapi/orchestration/silver/tea.py @@ -4,9 +4,9 @@ - the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each hangs from its order when it has one; - what the EEG analysis writes: the EEG's verdict and study-wide quality checks (`eeg_criterio` without an - electrode) and each metric with its deviation from the age baseline are results of the EEG's recording, not - procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an electrode are `parte`s of - the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric. + electrode) and each metric with its deviation from the age baseline and the baseline's registered label are results + of the EEG's recording, not procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an + electrode are `parte`s of the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric. """ from core.tea.enums import ( @@ -140,7 +140,8 @@ DESDE_STAGING = ( DeStaging( EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG, derivadas={"metrica": _metrica}, - resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION}}, + resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION}, + "met_modelo": "eeg.{metrica}_modelo"}, ), DeStaging( EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,