Integration/tea eeg analysis into dev #13
@@ -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-<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-"))
|
||||
@@ -0,0 +1,140 @@
|
||||
"""What this module covers: `$resumen-tea`'s `RiskAssessment`, the ADOS-2 association model as idiomatic FHIR:
|
||||
one resource per patient with a prediction per association row of the latest model version that scored the study's
|
||||
EEG (the clearest cohort association, lowest q, first), the model's metadata on the resource, the outcome as the
|
||||
ADOS-2 item or domain with its label from the code systems, the observed outcome read from the patient's ADOS-2,
|
||||
and the resource omitted entirely when no model row scored the patient's study EEG. Every resource is checked
|
||||
against FHIR's models.
|
||||
|
||||
Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`) over TEA's fixture database (`staging.tea`) plus model and
|
||||
patient rows for child 1's study EEG (`eeg-1b`); needs `DBT_MANIFEST`.
|
||||
"""
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from test_fhir_tea import get, resources
|
||||
|
||||
from conftest import base_de
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
def _rows(sesion):
|
||||
"""The kit's seven children, plus a fitted model: one item row (sa_b2) and one domain row (SA) of version
|
||||
0.2.0, both scored for child 1's study EEG (eeg-1b, 20 May). Child 1's ADOS-2 (ado-1) scores sa_b2 2 and its
|
||||
SA domain total is 6; no other child gets model rows."""
|
||||
from importlib import import_module
|
||||
|
||||
import_module("staging.tea").insertar(sesion)
|
||||
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
|
||||
|
||||
sesion.add_all([
|
||||
RelacionAdos2(rel_id="rel-2a", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
|
||||
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
|
||||
rel_resultado="sa_b2", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7,
|
||||
rel_q=0.02),
|
||||
RelacionAdos2(rel_id="rel-2b", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
|
||||
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio",
|
||||
rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6,
|
||||
rel_q=0.3),
|
||||
])
|
||||
sesion.add_all([
|
||||
RelacionAdos2Paciente(rap_id="rap-2a", rap_rel_id="rel-2a", rap_eeg_id="eeg-1b", rap_valor_z=-4.08,
|
||||
rap_probabilidad=0.81, rap_probabilidad_referencia=0.22),
|
||||
RelacionAdos2Paciente(rap_id="rap-2b", rap_rel_id="rel-2b", rap_eeg_id="eeg-1b", rap_valor_z=-4.08,
|
||||
rap_probabilidad=0.35, rap_probabilidad_referencia=0.4),
|
||||
])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
mp = pytest.MonkeyPatch()
|
||||
mp.setenv("DEV_REVISION", "pruebas")
|
||||
mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea_fhir_relacion"), datos=_rows)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
base.motor.dispose()
|
||||
mp.undo()
|
||||
|
||||
|
||||
def _extension(resource: dict) -> dict:
|
||||
return {e["url"].rsplit("/", 1)[-1]: e for e in resource["extension"]}
|
||||
|
||||
|
||||
def test_the_summary_emits_the_model_as_one_risk_assessment(client):
|
||||
"""Pins down: child 1's summary carries one `RiskAssessment` (tagged simulated) with the model's metadata on
|
||||
the resource (version, expert validation, level, cohort size), dated at the study's EEG (20 May), based on the
|
||||
EEG's DiagnosticReport and the ADOS-2 Observation, and with one prediction per association row, the clearest
|
||||
cohort association (lowest q) first. Fails if the resource loses a metadata extension, changes order, or stops
|
||||
referencing what it was scored from."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
|
||||
(child_1,) = episodes
|
||||
bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea")
|
||||
(riesgo,) = resources(bundle, "RiskAssessment")
|
||||
assert riesgo["id"] == f"relacion-ados2-{child_1['id']}"
|
||||
assert riesgo["occurrenceDateTime"] == "2025-05-20"
|
||||
assert riesgo["meta"]["tag"][0]["code"] == "simulado"
|
||||
extension = _extension(riesgo)
|
||||
assert extension["modelo-version"]["valueString"] == "0.2.0"
|
||||
assert extension["modelo-validado"]["valueBoolean"] is False
|
||||
assert extension["modelo-nivel"]["valueString"] == "item"
|
||||
assert extension["modelo-n-cohorte"]["valueInteger"] == 60
|
||||
(report,) = resources(bundle, "DiagnosticReport")
|
||||
ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-"))
|
||||
assert riesgo["basis"] == [{"reference": f"DiagnosticReport/{report['id']}"},
|
||||
{"reference": f"Observation/{ados2['id']}"}]
|
||||
assert len(riesgo["prediction"]) == 2
|
||||
assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2.sa_b2", "SA"]
|
||||
|
||||
|
||||
def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_outcome(client):
|
||||
"""Pins down: a prediction has the outcome as the ADOS-2 item or domain with its label from the code systems
|
||||
(not from the row), the model's probability for the patient, and as extensions the EEG metric and scalp zone
|
||||
(with labels), the patient's z, the cohort's odds ratio with its interval and q, the event as stored, the
|
||||
reference probability (z = 0) and the outcome observed in the patient's ADOS-2 (the item's score 2, the SA
|
||||
domain's algorithm total 6). Fails if a label starts coming from the stored row, or a value stops reaching the
|
||||
prediction."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
|
||||
(child_1,) = episodes
|
||||
bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea")
|
||||
(riesgo,) = resources(bundle, "RiskAssessment")
|
||||
item, dominio = riesgo["prediction"]
|
||||
assert item["outcome"]["coding"][0] == {
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo", "code": "ados2.sa_b2",
|
||||
"display": "Sonrisa social en respuesta"}
|
||||
assert dominio["outcome"]["coding"][0] == {
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio", "code": "SA",
|
||||
"display": "Afecto social"}
|
||||
assert (item["probabilityDecimal"], dominio["probabilityDecimal"]) == (0.81, 0.35)
|
||||
extension = _extension(item)
|
||||
assert extension["biomarcador"]["valueCoding"] == {
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-metrica", "code": "RITMO_POSTERIOR",
|
||||
"display": "Ritmo posterior"}
|
||||
assert extension["zona"]["valueCoding"] == {
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-zona", "code": "occipital",
|
||||
"display": "Occipital"}
|
||||
assert (extension["tipo"]["valueString"], extension["evento"]["valueString"]) == ("item", ">=1")
|
||||
assert extension["valor-z"]["valueDecimal"] == -4.08
|
||||
assert (extension["odds-ratio"]["valueDecimal"], extension["ic-inf"]["valueDecimal"],
|
||||
extension["ic-sup"]["valueDecimal"], extension["q"]["valueDecimal"]) == (3.5, 1.4, 8.7, 0.02)
|
||||
assert extension["probabilidad-referencia"]["valueDecimal"] == 0.22
|
||||
assert extension["observado"]["valueInteger"] == 2
|
||||
assert _extension(dominio)["observado"]["valueInteger"] == 6
|
||||
|
||||
|
||||
def test_the_summary_omits_the_model_without_rows(client):
|
||||
"""Pins down: a child whose study EEG no model row scored gets no `RiskAssessment` at all (not an empty one):
|
||||
child 2, in neuropediatrics without an EEG. Fails if the emission stops keying on the view's rows."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&etapa=NEUROPEDIATRIA"))
|
||||
(child_2,) = episodes
|
||||
bundle = get(client, f"/tea/fhir/Patient/{child_2['id']}/$resumen-tea")
|
||||
assert not resources(bundle, "RiskAssessment")
|
||||
@@ -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": "%"},
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""What this module covers: the ADOS-2 association model's import targets (`tea.RelacionAdos2` and
|
||||
`tea.RelacionAdos2Paciente`): their registration in `/imports/targets` with the natural keys the tables' unique
|
||||
constraints define, the upsert merge on those keys through the import service (a re-import updates in place
|
||||
instead of duplicating), and the schemas' validations (probabilities and q within [0, 1], the confidence
|
||||
interval's order, the outcome code per level, the cataloged biomarker and level, the bounded key columns).
|
||||
|
||||
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`).
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _json_source(records: list[dict], *, target: str) -> dict:
|
||||
raw = json.dumps(records).encode()
|
||||
return {
|
||||
"source_type": "json",
|
||||
"target": target,
|
||||
"column_mapping": {name: name for name in records[0]},
|
||||
"payload": {"file_base64": base64.b64encode(raw).decode()},
|
||||
}
|
||||
|
||||
|
||||
# One item row and one domain row of a fitted model version, as the `tea` library writes them.
|
||||
_MODELO_ITEM = {
|
||||
"rel_id": "rel-1", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42,
|
||||
"rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "item",
|
||||
"rel_resultado": "sa_b9", "rel_evento": ">=1", "rel_or": 3.5, "rel_ic_inf": 1.4, "rel_ic_sup": 8.7,
|
||||
"rel_q": 0.02,
|
||||
}
|
||||
_MODELO_DOMINIO = {
|
||||
"rel_id": "rel-2", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42,
|
||||
"rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "dominio",
|
||||
"rel_resultado": "SA", "rel_evento": ">=4", "rel_or": 0.8, "rel_ic_inf": 0.4, "rel_ic_sup": 1.6,
|
||||
"rel_q": 0.3,
|
||||
}
|
||||
# The probabilities of one EEG for both association rows, by the model.
|
||||
_PACIENTE_1 = {"rap_id": "rap-1", "rap_rel_id": "rel-1", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
|
||||
"rap_probabilidad": 0.81, "rap_probabilidad_referencia": 0.22}
|
||||
_PACIENTE_2 = {"rap_id": "rap-2", "rap_rel_id": "rel-2", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
|
||||
"rap_probabilidad": 0.35, "rap_probabilidad_referencia": 0.4}
|
||||
|
||||
|
||||
def test_targets_list_the_association_tables_with_their_natural_keys(client):
|
||||
"""Pins down: `/imports/targets` exposes both association tables with the conflict fields of the tables' unique
|
||||
constraints (uq_relacion_ados2, uq_relacion_ados2_paciente), so `on_conflict=upsert` merges on them, and lists
|
||||
them as fields to map. Fails if a target is deregistered or its conflict fields drift from the constraints."""
|
||||
targets = {t["key"]: t for t in client.get("/imports/targets").get_json()["targets"]}
|
||||
modelo, paciente = targets["tea.RelacionAdos2"], targets["tea.RelacionAdos2Paciente"]
|
||||
assert modelo["conflict_fields"] == ["rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"]
|
||||
assert paciente["conflict_fields"] == ["rap_rel_id", "rap_eeg_id"]
|
||||
assert {"rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"} <= {f["name"] for f in modelo["fields"]}
|
||||
assert {"rap_rel_id", "rap_eeg_id"} <= {f["name"] for f in paciente["fields"]}
|
||||
|
||||
|
||||
def test_model_and_patient_rows_import_and_reimport_upserts_on_the_natural_keys(client):
|
||||
"""Pins down: both tables load through the import service and a second import of the same rows updates in
|
||||
place (created 0, nothing duplicated), keeping the value the later import carried. Fails if the conflict
|
||||
fields stop matching the natural key (rows would duplicate) or the upsert stops updating."""
|
||||
fuentes = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
|
||||
_json_source([_PACIENTE_1, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
|
||||
body = client.post("/imports/commit", json={"sources": fuentes, "on_conflict": "upsert"}).get_json()
|
||||
assert [(r["target"], r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [
|
||||
("tea.RelacionAdos2", 2, 0, 0), ("tea.RelacionAdos2Paciente", 2, 0, 0)]
|
||||
|
||||
cambiada = {**_PACIENTE_1, "rap_probabilidad": 0.55}
|
||||
otra_vez = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
|
||||
_json_source([cambiada, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
|
||||
body = client.post("/imports/commit", json={"sources": otra_vez, "on_conflict": "upsert"}).get_json()
|
||||
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 2, 0), (0, 2, 0)]
|
||||
|
||||
filas = client.get("/data/tea.RelacionAdos2Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
assert len(filas) == 2
|
||||
assert next(f for f in filas if f["rap_id"] == "rap-1")["rap_probabilidad"] == 0.55
|
||||
|
||||
|
||||
def test_invalid_model_rows_are_rejected(client):
|
||||
"""Pins down: a model row with an out-of-range q, a non-positive odds ratio, an inverted confidence
|
||||
interval, an unknown level or biomarker, an outcome code that doesn't match its level, or an over-long key
|
||||
is rejected, none of it written. Fails if the schema loses one of those validations (the staging is
|
||||
permissive; without them nothing else catches them)."""
|
||||
casos = [
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m1", "rel_version": "v" * 33},
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m2", "rel_version": "0.9.1", "rel_q": 1.5},
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m3", "rel_version": "0.9.2", "rel_or": 0},
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m4", "rel_version": "0.9.3", "rel_ic_inf": 9.0, "rel_ic_sup": 4.0},
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m5", "rel_version": "0.9.4", "rel_nivel": "itemm"},
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "SA"},
|
||||
{**_MODELO_ITEM, "rel_id": "rel-m7", "rel_version": "0.9.6", "rel_biomarcador": "ritmo posterior"},
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2")],
|
||||
"on_conflict": "upsert"}).get_json()
|
||||
resultado = body["results"][0]
|
||||
assert resultado["created"] == 0 and resultado["rejected"] == len(casos)
|
||||
campos = {e["field"] for e in resultado["errors"]}
|
||||
assert {"rel_version", "rel_q", "rel_or", "rel_nivel", "rel_biomarcador", "<entre campos>"} <= campos
|
||||
filas = client.get("/data/tea.RelacionAdos2", query_string={"limit": 500}).get_json()["rows"]
|
||||
assert not [f for f in filas if f["rel_id"].startswith("rel-m")]
|
||||
|
||||
|
||||
def test_invalid_patient_rows_are_rejected(client):
|
||||
"""Pins down: a probability outside [0, 1] (the model's or the reference's) is rejected. Fails if the
|
||||
Bounded validation loosens, since a probability over 1 would silently skew what the screen shows."""
|
||||
buena = {**_PACIENTE_1, "rap_id": "rap-ok", "rap_rel_id": "rel-9"}
|
||||
casos = [buena,
|
||||
{**buena, "rap_id": "rap-m1", "rap_probabilidad": 1.2},
|
||||
{**buena, "rap_id": "rap-m2", "rap_probabilidad_referencia": -0.1}]
|
||||
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2Paciente")],
|
||||
"on_conflict": "upsert"}).get_json()
|
||||
resultado = body["results"][0]
|
||||
assert (resultado["created"], resultado["rejected"]) == (1, 2)
|
||||
assert {e["field"] for e in resultado["errors"]} == {"rap_probabilidad", "rap_probabilidad_referencia"}
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""What this module covers: `tea_paciente_relacion_ados2`, the gold view of the ADOS-2 association model: per
|
||||
patient it keeps only the latest model version that scored the study's EEG, it takes the probabilities of the
|
||||
study's EEG alone (not later EEGs, not model rows without a probability for it), and it computes `observado` from
|
||||
the first ADOS-2 by date (the item's score, the domain's algorithm total, null when the outcome wasn't scored).
|
||||
|
||||
Fixtures: `loaded`, a TEA database (`base_de`) with one child in the cohort (M-CHAT, ADOS-2 with items), two good
|
||||
EEGs (`e-1` the study's, `e-2` a later one), a second child without model rows, and a fitted model in two
|
||||
versions whose patient rows point at both EEGs and both versions; needs `DBT_MANIFEST`.
|
||||
"""
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
def _rows(sesion):
|
||||
from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
Mchat,
|
||||
Pacientes,
|
||||
RelacionAdos2,
|
||||
RelacionAdos2Paciente,
|
||||
)
|
||||
|
||||
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
|
||||
sesion.add(Pacientes(pac_id=2, pac_id_hospital="H-2", pac_fecha_nacimiento=date(2023, 6, 1)))
|
||||
sesion.add_all([
|
||||
Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12),
|
||||
Mchat(mch_id="m-2", mch_pac_id=2, mch_fecha=date(2025, 1, 10), mch_puntaje=8),
|
||||
])
|
||||
# Items: sa_b1 2, sa_b9 1 (SA algorithm total 3), rrb_d1 2, rrb_d2 1 (RRB total 3). rrb_d4 is not scored.
|
||||
sesion.add(Ados2(ado_id="a-1", ado_pac_id=1, ado_fecha=date(2025, 2, 5), ado_modulo="MODULO_1", ado_css=7,
|
||||
ado_clasificacion="AUTISMO", ado_sa_b1=2, ado_sa_b9=1, ado_rrb_d1=2, ado_rrb_d2=1))
|
||||
sesion.add_all([
|
||||
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1),
|
||||
Eeg(eeg_id="e-2", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 6, 1), eeg_valido=1),
|
||||
Eeg(eeg_id="e-3", eeg_pac_id=2, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1),
|
||||
])
|
||||
sesion.add_all([
|
||||
RelacionAdos2(rel_id="rel-10", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42,
|
||||
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
|
||||
rel_resultado="sa_b9", rel_evento=">=1", rel_or=2.0, rel_ic_inf=1.0, rel_ic_sup=4.0,
|
||||
rel_q=0.05),
|
||||
RelacionAdos2(rel_id="rel-11", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42,
|
||||
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio",
|
||||
rel_resultado="SA", rel_evento=">=4", rel_or=0.6, rel_ic_inf=0.3, rel_ic_sup=1.2,
|
||||
rel_q=0.4),
|
||||
RelacionAdos2(rel_id="rel-20", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
|
||||
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item",
|
||||
rel_resultado="sa_b9", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7,
|
||||
rel_q=0.02),
|
||||
RelacionAdos2(rel_id="rel-21", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
|
||||
rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio",
|
||||
rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6,
|
||||
rel_q=0.3),
|
||||
# A row of the latest version no probability was computed for: it can't reach the patient.
|
||||
RelacionAdos2(rel_id="rel-22", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
|
||||
rel_biomarcador="PICOS_PAROXISTICOS", rel_zona="frontal_izq", rel_tipo="item",
|
||||
rel_resultado="rrb_d4", rel_evento=">=1", rel_or=1.5, rel_ic_inf=0.8, rel_ic_sup=2.9,
|
||||
rel_q=0.1),
|
||||
# The same, without even a patient row anywhere: nothing to join on.
|
||||
RelacionAdos2(rel_id="rel-23", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
|
||||
rel_biomarcador="PICOS_PAROXISTICOS", rel_zona="frontal_izq", rel_tipo="item",
|
||||
rel_resultado="sa_b1", rel_evento=">=1", rel_or=1.1, rel_ic_inf=0.7, rel_ic_sup=1.8,
|
||||
rel_q=0.2),
|
||||
])
|
||||
sesion.add_all([
|
||||
# The stale version's probability: the latest version wins.
|
||||
RelacionAdos2Paciente(rap_id="rap-0", rap_rel_id="rel-10", rap_eeg_id="e-1", rap_valor_z=-2.5,
|
||||
rap_probabilidad=0.6, rap_probabilidad_referencia=0.25),
|
||||
RelacionAdos2Paciente(rap_id="rap-1", rap_rel_id="rel-20", rap_eeg_id="e-1", rap_valor_z=-2.5,
|
||||
rap_probabilidad=0.81, rap_probabilidad_referencia=0.22),
|
||||
RelacionAdos2Paciente(rap_id="rap-2", rap_rel_id="rel-21", rap_eeg_id="e-1", rap_valor_z=-2.5,
|
||||
rap_probabilidad=0.35, rap_probabilidad_referencia=0.4),
|
||||
RelacionAdos2Paciente(rap_id="rap-3", rap_rel_id="rel-22", rap_eeg_id="e-1", rap_valor_z=1.1,
|
||||
rap_probabilidad=0.5, rap_probabilidad_referencia=0.45),
|
||||
# A probability for the later EEG: not the study's, it doesn't count.
|
||||
RelacionAdos2Paciente(rap_id="rap-4", rap_rel_id="rel-20", rap_eeg_id="e-2", rap_valor_z=0.4,
|
||||
rap_probabilidad=0.3, rap_probabilidad_referencia=0.25),
|
||||
])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def loaded(tmp_path_factory):
|
||||
"""The database after the cycle's load and event models, with the view under test created."""
|
||||
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_relacion"), datos=_rows)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def _filas(loaded):
|
||||
with loaded.motor.connect() as connection:
|
||||
return connection.execute(text(
|
||||
"select pac_id, procedimiento_id, version, validado, nivel, n_cohorte, biomarcador, zona, tipo,"
|
||||
" resultado, evento, odds_ratio, ic_inf, ic_sup, q, valor_z, probabilidad,"
|
||||
" probabilidad_referencia, observado from tea_paciente_relacion_ados2")).all()
|
||||
|
||||
|
||||
def test_the_view_keeps_the_latest_version_of_the_study_eeg_only(loaded):
|
||||
"""Pins down: one row per association row of the greatest model version that scored the study's EEG (1.1.0).
|
||||
The stale version's probability (1.0.0), the probability for the later EEG (e-2), the model rows of 1.1.0
|
||||
without a probability for the study's EEG (rel-23) or scored only on the other EEG don't appear, and a child
|
||||
without model rows (patient 2) doesn't either. Fails if the view stops filtering by the study's EEG or by the
|
||||
latest version."""
|
||||
filas = _filas(loaded)
|
||||
claves = sorted((f.version, f.resultado, f.tipo) for f in filas)
|
||||
assert claves == [("1.1.0", "SA", "dominio"), ("1.1.0", "rrb_d4", "item"), ("1.1.0", "sa_b9", "item")]
|
||||
assert {f.pac_id for f in filas} == {1}
|
||||
|
||||
|
||||
def test_a_row_carries_the_model_metadata_and_the_patient_values(loaded):
|
||||
"""Pins down: each row carries the model row as it arrived (version, validation, level, cohort size, metric,
|
||||
zone, event, odds ratio with its interval and q) and the patient's values for the study's EEG. Fails if a
|
||||
column stops being selected or gets renamed without the FHIR layer changing with it."""
|
||||
(item,) = [f for f in _filas(loaded) if f.resultado == "sa_b9"]
|
||||
assert (item.version, item.validado, item.nivel, item.n_cohorte) == ("1.1.0", 0, "item", 60)
|
||||
assert (item.biomarcador, item.zona, item.evento) == ("RITMO_POSTERIOR", "occipital", ">=1")
|
||||
assert (item.odds_ratio, item.ic_inf, item.ic_sup, item.q) == (3.5, 1.4, 8.7, 0.02)
|
||||
assert (item.valor_z, item.probabilidad, item.probabilidad_referencia) == (-2.5, 0.81, 0.22)
|
||||
|
||||
|
||||
def test_observado_is_the_outcome_score_of_the_first_ados2(loaded):
|
||||
"""Pins down: `observado` is read from the first ADOS-2 by date (the one the patient summary shows): the
|
||||
item's score for an item (sa_b9 1), the domain's algorithm total for a domain (SA: sa_b1 2 + sa_b9 1 = 3), and
|
||||
null when the outcome wasn't scored (rrb_d4). It is never stored in the association tables. Fails if the view
|
||||
starts reading another ADOS-2, sums the raw scores, or stores the outcome."""
|
||||
observados = {f.resultado: f.observado for f in _filas(loaded)}
|
||||
assert observados == {"sa_b9": 1, "SA": 3, "rrb_d4": None}
|
||||
@@ -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
|
||||
|
||||
@@ -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-<scenario>/<version>`, 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
|
||||
+134
-16
@@ -4,7 +4,11 @@ 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. The ADOS-2 association model reaches the summary as one
|
||||
`RiskAssessment` per patient (a prediction per association row of `tea_paciente_relacion_ados2`), and stays out
|
||||
while no model row scored the patient's study EEG.
|
||||
|
||||
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 +22,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,25 +34,30 @@ 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, (
|
||||
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
|
||||
"etiqueta", "puntaje", "puntaje_algoritmo")))
|
||||
RELACION = table("tea_paciente_relacion_ados2", *map(column, (
|
||||
"pac_id", "procedimiento_id", "version", "validado", "nivel", "n_cohorte", "biomarcador", "zona", "tipo",
|
||||
"resultado", "evento", "odds_ratio", "ic_inf", "ic_sup", "q", "valor_z", "probabilidad",
|
||||
"probabilidad_referencia", "observado")))
|
||||
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
|
||||
|
||||
|
||||
@@ -263,12 +273,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 +319,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 +338,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 +359,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":
|
||||
@@ -343,9 +375,85 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
|
||||
return [procedure, tagged(report, simulated), *quality, *altered]
|
||||
|
||||
|
||||
def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_id: int | None,
|
||||
simulated: bool) -> dict | None:
|
||||
"""The association model as one `RiskAssessment`: a prediction per association row that scored the study's EEG,
|
||||
the clearest cohort association (lowest q) first. The model's version, expert validation, level and cohort size
|
||||
sit on the resource; each prediction carries the outcome (the ADOS-2 item or domain) and the probability the
|
||||
model gives the patient, and as extensions the EEG metric and scalp zone, the patient's z, the cohort's odds
|
||||
ratio with its confidence interval and q, the reference probability (z = 0) and the outcome observed in the
|
||||
patient's ADOS-2. Zone and outcome labels come from the code systems, not from the row. Without rows there is
|
||||
no resource."""
|
||||
if not rows:
|
||||
return None
|
||||
from webapi.fhir.terminology import DOMINIOS_ADOS2, TEA_EEG, ados2_resultados
|
||||
|
||||
resultados, metricas, zonas = ados2_resultados(), TEA_EEG["metricas"], TEA_EEG["zonas"]
|
||||
|
||||
def prediction(f: dict) -> dict:
|
||||
if f["tipo"] == "item":
|
||||
code = f"ados2.{f['resultado']}"
|
||||
outcome = concept(CATALOG, code, resultados.get(code, f["resultado"]))
|
||||
else:
|
||||
outcome = concept(f"{CODE_SYSTEM}/ados2-dominio", f["resultado"],
|
||||
DOMINIOS_ADOS2.get(f["resultado"], f["resultado"]))
|
||||
return {
|
||||
"outcome": outcome,
|
||||
"probabilityDecimal": float(f["probabilidad"]),
|
||||
"extension": [
|
||||
{"url": f"{STRUCTURE}/biomarcador",
|
||||
"valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-metrica", f["biomarcador"],
|
||||
metricas.get((f["biomarcador"] or "").lower(), {}).get("etiqueta"))},
|
||||
{"url": f"{STRUCTURE}/zona", "valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-zona", f["zona"],
|
||||
zonas.get(f["zona"], f["zona"]))},
|
||||
*([{"url": f"{STRUCTURE}/tipo", "valueString": f["tipo"]}] if f["tipo"] else []),
|
||||
*([{"url": f"{STRUCTURE}/evento", "valueString": f["evento"]}] if f["evento"] else []),
|
||||
*([{"url": f"{STRUCTURE}/valor-z", "valueDecimal": float(f["valor_z"])}]
|
||||
if f["valor_z"] is not None else []),
|
||||
*([{"url": f"{STRUCTURE}/odds-ratio", "valueDecimal": float(f["odds_ratio"])}]
|
||||
if f["odds_ratio"] is not None else []),
|
||||
*([{"url": f"{STRUCTURE}/ic-inf", "valueDecimal": float(f["ic_inf"])}]
|
||||
if f["ic_inf"] is not None else []),
|
||||
*([{"url": f"{STRUCTURE}/ic-sup", "valueDecimal": float(f["ic_sup"])}]
|
||||
if f["ic_sup"] is not None else []),
|
||||
*([{"url": f"{STRUCTURE}/q", "valueDecimal": float(f["q"])}] if f["q"] is not None else []),
|
||||
*([{"url": f"{STRUCTURE}/probabilidad-referencia", "valueDecimal":
|
||||
float(f["probabilidad_referencia"])}] if f["probabilidad_referencia"] is not None else []),
|
||||
*([{"url": f"{STRUCTURE}/observado", "valueInteger": int(f["observado"])}]
|
||||
if f["observado"] is not None else []),
|
||||
],
|
||||
}
|
||||
|
||||
primero = rows[0]
|
||||
resource = {
|
||||
"resourceType": "RiskAssessment", "id": f"relacion-ados2-{pseudonym}", "status": "final",
|
||||
"subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"code": {"coding": [coding(f"{CODE_SYSTEM}/tea-relacion-ados2", "modelo",
|
||||
"Modelo de asociación de alteraciones del EEG con el ADOS-2")],
|
||||
"text": "Asociación de alteraciones del EEG con el ADOS-2"},
|
||||
"extension": [
|
||||
{"url": f"{STRUCTURE}/modelo-version", "valueString": primero["version"]},
|
||||
{"url": f"{STRUCTURE}/modelo-validado", "valueBoolean": primero["validado"] == 1},
|
||||
*([{"url": f"{STRUCTURE}/modelo-nivel", "valueString": primero["nivel"]}]
|
||||
if primero["nivel"] else []),
|
||||
*([{"url": f"{STRUCTURE}/modelo-n-cohorte", "valueInteger": int(primero["n_cohorte"])}]
|
||||
if primero["n_cohorte"] is not None else []),
|
||||
],
|
||||
"prediction": [prediction(f) for f in sorted(
|
||||
rows, key=lambda f: (f["q"] is None, f["q"] or 0, f["biomarcador"] or "", f["resultado"] or ""))],
|
||||
"basis": [{"reference": f"DiagnosticReport/eeg-{primero['procedimiento_id']}"},
|
||||
*([{"reference": f"Observation/ados2-{ados2_id}"}] if ados2_id is not None else [])],
|
||||
}
|
||||
if fecha is not None:
|
||||
resource["occurrenceDateTime"] = _date(fecha).isoformat()
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
|
||||
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
|
||||
items, each item with its algorithm score."""
|
||||
from webapi.fhir.terminology import DOMINIOS_ADOS2
|
||||
|
||||
if not rows:
|
||||
return None
|
||||
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
|
||||
@@ -362,7 +470,7 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
|
||||
if first["clasificacion"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
|
||||
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
|
||||
for domain, label in DOMINIOS_ADOS2.items():
|
||||
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
|
||||
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
|
||||
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
|
||||
@@ -376,12 +484,16 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
|
||||
|
||||
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
|
||||
"""The `$resumen-tea` collection: the patient, its screening episode (with its age group), its first ADOS-2 and
|
||||
the EEG the study uses, as of today."""
|
||||
the EEG the study uses, as of today, and the ADOS-2 association model as one `RiskAssessment` when model rows
|
||||
scored the study's EEG."""
|
||||
pseudonym = seudonimo(pac_id, salt())
|
||||
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
|
||||
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
|
||||
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
|
||||
ados2_rows = _rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id))
|
||||
ados2 = ados2_observation(ados2_rows, pseudonym, simulated)
|
||||
resources += [ados2] if ados2 else []
|
||||
first_ados2 = min((r for r in ados2_rows if r["fecha_ados2"] is not None),
|
||||
key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]), default=None)
|
||||
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
|
||||
if child is not None:
|
||||
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
|
||||
@@ -391,5 +503,11 @@ 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())
|
||||
riesgo = relacion_ados2(_rows(queries, select(RELACION).where(RELACION.c.pac_id == pac_id)), pseudonym,
|
||||
eeg["fecha_eeg"] if eeg is not None else None,
|
||||
first_ados2["procedimiento_id"] if first_ados2 is not None else None, simulated)
|
||||
if riesgo:
|
||||
resources.append(riesgo)
|
||||
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
|
||||
|
||||
@@ -56,3 +56,14 @@ P4 = [0.33, -0.4]
|
||||
T6 = [0.65, -0.47]
|
||||
O1 = [-0.25, -0.77]
|
||||
O2 = [0.25, -0.77]
|
||||
|
||||
# The scalp zones the association model relates an EEG alteration in with an ADOS-2 outcome, as the `tea` library
|
||||
# codes them: what each zone is called on screen. A code outside this list shows as written.
|
||||
[zonas]
|
||||
frontal_izq = "Frontal izquierda"
|
||||
frontal_der = "Frontal derecha"
|
||||
central = "Central"
|
||||
temporal_izq = "Temporal izquierda"
|
||||
temporal_der = "Temporal derecha"
|
||||
parietal = "Parietal"
|
||||
occipital = "Occipital"
|
||||
|
||||
@@ -14,6 +14,14 @@ STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psico
|
||||
("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG"))
|
||||
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
|
||||
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
|
||||
DOMINIOS_ADOS2 = {"SA": "Afecto social", "RRB": "Comportamiento restringido y repetitivo"}
|
||||
|
||||
|
||||
def ados2_resultados() -> dict[str, str]:
|
||||
"""The ADOS-2 results' labels from the domain catalog, by their catalog code (`ados2.sa_b9`): what an
|
||||
association row's outcome shows as."""
|
||||
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["ados2"]["resultados"]
|
||||
return {f"ados2.{name}": spec["etiqueta"] for name, spec in results.items()}
|
||||
|
||||
|
||||
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
|
||||
@@ -66,6 +74,8 @@ def tea_code_systems() -> dict[str, dict]:
|
||||
eeg_checks(),
|
||||
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
|
||||
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
|
||||
_code_system("tea-eeg-zona", "Zonas del cuero cabelludo",
|
||||
[{"code": z, "display": e} for z, e in TEA_EEG["zonas"].items()]),
|
||||
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
|
||||
{"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"},
|
||||
{"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]),
|
||||
|
||||
@@ -138,6 +138,11 @@ def coerce_postal_code(v: Any) -> Any:
|
||||
# SQLite and is not in the migrations, so the format is enforced here.
|
||||
CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
|
||||
|
||||
# A short code of a natural key made of bounded VARCHAR(32) columns (`relacion_ados2`): an over-long value is a
|
||||
# validation error here rather than a `Data too long` failure at insert on MySQL/Postgres. Optional, like every
|
||||
# TEA field (see `tea/pacientes.py`).
|
||||
ShortKey = Annotated[Optional[Annotated[str, StringConstraints(max_length=32)]], BeforeValidator(optional_str)]
|
||||
|
||||
|
||||
def edf_file(v: Any) -> Any:
|
||||
"""`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment).
|
||||
|
||||
@@ -30,6 +30,8 @@ from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluac
|
||||
from persistance.tea import mchat_repository as tea_mchat_repository
|
||||
from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository
|
||||
from persistance.tea import pacientes_repository as tea_pacientes_repository
|
||||
from persistance.tea import relacion_ados2_paciente_repository as tea_relacion_ados2_paciente_repository
|
||||
from persistance.tea import relacion_ados2_repository as tea_relacion_ados2_repository
|
||||
from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema,
|
||||
)
|
||||
@@ -64,6 +66,8 @@ from webapi.imports.schemas.tea.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
from webapi.imports.schemas.tea.relacion_ados2 import RelacionAdos2ImportSchema
|
||||
from webapi.imports.schemas.tea.relacion_ados2_paciente import RelacionAdos2PacienteImportSchema
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -183,4 +187,16 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
# one row.
|
||||
conflict_fields=("eeg_id_registro_laboratorio",),
|
||||
),
|
||||
"tea.RelacionAdos2": EntitySpec(
|
||||
schema=RelacionAdos2ImportSchema,
|
||||
repository=tea_relacion_ados2_repository,
|
||||
# The natural key the import and the `tea` library merge model rows on (the table's unique constraint).
|
||||
conflict_fields=("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"),
|
||||
),
|
||||
"tea.RelacionAdos2Paciente": EntitySpec(
|
||||
schema=RelacionAdos2PacienteImportSchema,
|
||||
repository=tea_relacion_ados2_paciente_repository,
|
||||
# One probability per EEG and association row (the table's unique constraint).
|
||||
conflict_fields=("rap_rel_id", "rap_eeg_id"),
|
||||
),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Import schema for `core.tea.models.RelacionAdos2`: one association of an EEG alteration in a scalp zone with an
|
||||
ADOS-2 item or domain outcome, per fitted model version. `rel_evento` is the outcome event as a threshold on its
|
||||
score, machine-readable (`>=2`); it is shown as written, never parsed."""
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from core.tea.enums import MetricaEeg, NivelRelacionAdos2
|
||||
from core.tea.models import ADOS2_ITEMS
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, OptionalStr, ShortKey, SourceId
|
||||
|
||||
_NIVEL_CATALOG = Catalog(NivelRelacionAdos2)
|
||||
_BIOMARCADOR_CATALOG = Catalog(MetricaEeg)
|
||||
_DOMINIOS_ADOS2 = {"SA", "RRB"}
|
||||
|
||||
|
||||
class RelacionAdos2ImportSchema(ImportSchema):
|
||||
rel_id: SourceId = None
|
||||
# The natural key the import merges model rows on: rel_version, rel_biomarcador, rel_zona, rel_resultado.
|
||||
rel_version: ShortKey = None
|
||||
rel_nivel: CatalogValue(_NIVEL_CATALOG) = None
|
||||
rel_validado: Bounded(int, 0, 1) = None
|
||||
rel_n_cohorte: Bounded(int, 1, None) = None
|
||||
rel_biomarcador: CatalogValue(_BIOMARCADOR_CATALOG) = None
|
||||
rel_zona: ShortKey = None
|
||||
rel_tipo: CatalogValue(_NIVEL_CATALOG) = None
|
||||
rel_resultado: ShortKey = None
|
||||
rel_evento: OptionalStr = None
|
||||
rel_or: Optional[Annotated[float, Field(gt=0)]] = None
|
||||
rel_ic_inf: Bounded(float, 0, None) = None
|
||||
rel_ic_sup: Bounded(float, 0, None) = None
|
||||
rel_q: Bounded(float, 0, 1) = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _outcome_code_and_interval_checks(self):
|
||||
if self.rel_ic_inf is not None and self.rel_ic_sup is not None and self.rel_ic_inf > self.rel_ic_sup:
|
||||
raise ValueError("rel_ic_inf no puede ser mayor que rel_ic_sup")
|
||||
if self.rel_tipo is not None and self.rel_resultado is not None:
|
||||
validos = set(ADOS2_ITEMS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value else _DOMINIOS_ADOS2
|
||||
if self.rel_resultado not in validos:
|
||||
raise ValueError(f"'{self.rel_resultado}' no es un código de {self.rel_tipo} del ADOS-2")
|
||||
return self
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Import schema for `core.tea.models.RelacionAdos2Paciente`: one patient's z and model probability for an
|
||||
association row, per EEG. The observed outcome stays in `ados2`, never here."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, SourceId
|
||||
|
||||
|
||||
class RelacionAdos2PacienteImportSchema(ImportSchema):
|
||||
rap_id: SourceId = None
|
||||
# The natural key the import merges patient rows on: rap_rel_id, rap_eeg_id.
|
||||
rap_rel_id: SourceId = None
|
||||
rap_eeg_id: SourceId = None
|
||||
rap_valor_z: Optional[float] = None
|
||||
rap_probabilidad: Bounded(float, 0, 1) = None
|
||||
rap_probabilidad_referencia: Bounded(float, 0, 1) = None
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user