feat(tea): import the ADOS-2 association model and serve it as a RiskAssessment in the patient summary

This commit is contained in:
2026-11-21 11:17:58 -06:00
parent 46473bb106
commit 31ab347347
10 changed files with 598 additions and 4 deletions
+140
View File
@@ -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")
+125
View File
@@ -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"}
+137
View File
@@ -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}
+95 -4
View File
@@ -6,7 +6,9 @@ stage the furthest step reached by the cut-off (`type`, with its date as an exte
`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. 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.
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.
@@ -52,6 +54,10 @@ ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_i
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"))
@@ -369,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"]))
@@ -388,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"]),
@@ -402,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)),
@@ -419,4 +505,9 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
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]}
+11
View File
@@ -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"
+10
View File
@@ -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"}]),
+5
View File
@@ -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).
+16
View File
@@ -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