Files
WebApi/tests/test_tea_relacion_ados2.py

176 lines
11 KiB
Python

"""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 (an item meaning's algorithm score in that ADOS-2's module, the CSS for `CSS`, null when
the module has no such item or it wasn't scored); and the dbt var the view maps item meanings with
(`tea.ados2_reactivos`) equals `core.tea.models.ADOS2_ITEM_MEANINGS`.
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`. The var test reads
`Transformation/dbt_project.yml` and needs no fixture.
"""
import os
from datetime import date
from pathlib import Path
import pytest
import yaml
from sqlalchemy import text
DBT_PROJECT = Path(__file__).resolve().parents[2] / "Transformation" / "dbt_project.yml"
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),
])
# Module 1 items: sa_b1 2 (item 04), sa_b9 3 (item 11, algorithm score 2), rrb_d1 2 (item 20), rrb_d2 8
# (item 21, algorithm score 0). rrb_d4 (item 22) is not scored. A later ADOS-2 in another module doesn't count.
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=3, ado_rrb_d1=2, ado_rrb_d2=8))
sesion.add(Ados2(ado_id="a-2", ado_pac_id=1, ado_fecha=date(2025, 8, 5), ado_modulo="TODDLER", ado_css=4,
ado_clasificacion="AUTISMO", ado_sa_b9=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="ados2_item_11", 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="CSS", rel_evento=">=8", 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="ados2_item_11", 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="CSS", rel_evento=">=8", 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="ados2_item_22", rel_evento=">=1", rel_or=1.5, rel_ic_inf=0.8, rel_ic_sup=2.9,
rel_q=0.1),
# Item 10 is sa_b9 in the Toddler module only: Module 1's sa_b9 is item 11, not this one.
RelacionAdos2(rel_id="rel-24", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="HUSOS_SUENO_N2", rel_zona="central", rel_tipo="item",
rel_resultado="ados2_item_10", rel_evento=">=1", rel_or=1.3, rel_ic_inf=0.9, rel_ic_sup=2.0,
rel_q=0.2),
RelacionAdos2(rel_id="rel-25", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60,
rel_biomarcador="HUSOS_SUENO_N2", rel_zona="central", rel_tipo="item",
rel_resultado="ados2_item_21", rel_evento=">=1", rel_or=1.2, rel_ic_inf=0.8, rel_ic_sup=1.9,
rel_q=0.3),
# 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="ados2_item_04", 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),
RelacionAdos2Paciente(rap_id="rap-5", rap_rel_id="rel-24", rap_eeg_id="e-1", rap_valor_z=0.2,
rap_probabilidad=0.4, rap_probabilidad_referencia=0.4),
RelacionAdos2Paciente(rap_id="rap-6", rap_rel_id="rel-25", rap_eeg_id="e-1", rap_valor_z=0.3,
rap_probabilidad=0.45, rap_probabilidad_referencia=0.4),
# 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", "CSS", "dominio"), ("1.1.0", "ados2_item_10", "item"),
("1.1.0", "ados2_item_11", "item"), ("1.1.0", "ados2_item_21", "item"),
("1.1.0", "ados2_item_22", "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 == "ados2_item_11"]
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 (Module 1, the one the patient summary shows):
an item meaning's algorithm score through its column code in that module (item 11 is sa_b9 there, 3 counts as
2; item 21 is rrb_d2, 8 counts as 0), null for an item the module doesn't have (item 10, Toddler only, even
though sa_b9 was scored) or that wasn't scored (item 22, rrb_d4), and the ADOS-2's CSS for `CSS` (7). Fails if
the view joins by column code instead of meaning and module, stops applying the algorithm's score mapping,
reads the later ADOS-2, or stores the outcome."""
observados = {f.resultado: f.observado for f in _filas(loaded)}
assert observados == {"ados2_item_11": 2, "ados2_item_21": 0, "ados2_item_10": None, "ados2_item_22": None,
"CSS": 7}
def test_the_dbt_item_map_equals_the_item_meanings():
"""Pins down: `vars.tea.ados2_reactivos` in dbt_project.yml, which the view maps item outcomes with, has the
same meaning codes and per-module column codes as `core.tea.models.ADOS2_ITEM_MEANINGS`, which the import
schema and the FHIR layer use. Fails if one copy gains, loses or remaps an item without the other."""
from core.tea.models import ADOS2_ITEM_MEANINGS
reactivos = yaml.safe_load(DBT_PROJECT.read_text(encoding="utf-8"))["vars"]["tea"]["ados2_reactivos"]
assert reactivos == {codigo: modulos for codigo, (_, _, modulos) in ADOS2_ITEM_MEANINGS.items()}