144 lines
7.9 KiB
Python
144 lines
7.9 KiB
Python
"""What this module covers: what the EEG analysis writes to TEA's bronze, carried into silver
|
|
(`webapi.orchestration.silver.tea`) and into dbt's views of the EEG's quality checks, metrics and electrodes
|
|
(`tea_paciente_eeg_criterios`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`).
|
|
|
|
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.
|
|
"""
|
|
import os
|
|
from datetime import date
|
|
|
|
import pytest
|
|
from sqlalchemy import text
|
|
from sqlmodel import Session, select
|
|
|
|
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
|
|
|
|
|
def _rows(sesion):
|
|
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, 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_canales_malos=1, eeg_edad_meses=23.6, eeg_con_sueno=1))
|
|
sesion.add_all([
|
|
EegCriterio(cri_id="c-1", cri_eeg_id="e-1", cri_codigo="clean-windows", cri_valor=95.0, cri_unidad="%",
|
|
cri_bajo=60.0, cri_decisivo=1, cri_anormal=0),
|
|
EegCriterio(cri_id="c-2", cri_eeg_id="e-1", cri_codigo="triage-level", cri_valor_texto="completo",
|
|
cri_decisivo=1, cri_anormal=0),
|
|
EegCriterio(cri_id="c-3", cri_eeg_id="e-1", cri_codigo="dead-channel", cri_electrodo="T3",
|
|
cri_valor_texto="dead channel", cri_decisivo=0, cri_anormal=1),
|
|
])
|
|
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),
|
|
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),
|
|
])
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def loaded(tmp_path_factory):
|
|
"""The database after the cycle's load and event models, with dbt's views 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_eeg"), datos=_rows)
|
|
base.run(*UNTIL_MODELS, allow_undecided=True)
|
|
yield base
|
|
base.motor.dispose()
|
|
|
|
|
|
def _observations(base, clase: str) -> dict:
|
|
from core.tea.indicadores.models import Observacion, Procedimiento
|
|
|
|
with Session(base.motor) as sesion:
|
|
rows = sesion.exec(select(Procedimiento.codigo_fuente, Observacion).join(
|
|
Observacion, Observacion.procedimiento_id == Procedimiento.procedimiento_id).where(
|
|
Procedimiento.estudio_id == "eeg", Procedimiento.clase == clase)).all()
|
|
return {(fuente, o.resultado_id): o.valor_numerico if o.valor_texto is None else o.valor_texto
|
|
for fuente, o in rows}
|
|
|
|
|
|
def test_the_verdict_and_study_checks_are_results_of_the_recording(loaded):
|
|
"""Pins down: the EEG's verdict, triage level and each study-wide check (value, limit, out of range or not) are
|
|
observations of its recording, under `eeg.calidad_<check>` in snake case; a check without a limit of that side
|
|
gives none.
|
|
|
|
Fails if the silver mapping drops the verdict, stops turning check codes into catalog results, or the catalog
|
|
loses one of them (the load skips a result the catalog doesn't have).
|
|
"""
|
|
toma = _observations(loaded, "toma")
|
|
assert toma[None, "eeg.valido"] == 1 and toma[None, "eeg.nivel"] == "completo"
|
|
assert (toma[None, "eeg.calidad_clean_windows"], toma[None, "eeg.calidad_clean_windows_bajo"],
|
|
toma[None, "eeg.calidad_clean_windows_anormal"]) == (95.0, 60.0, 0)
|
|
assert toma[None, "eeg.calidad_triage_level"] == "completo"
|
|
assert (None, "eeg.calidad_clean_windows_alto") not in toma
|
|
|
|
|
|
def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded):
|
|
"""Pins down: a bad channel is a part of its EEG at its electrode with the analysis's reason; a metric's value at
|
|
an electrode is a part with the value and its z.
|
|
|
|
Fails if the channel checks stop being parts, or the electrode z stops reaching silver.
|
|
"""
|
|
partes = _observations(loaded, "parte")
|
|
assert partes["T3", "eeg.calidad_dead_channel"] == "dead channel"
|
|
assert (partes["Fz", "eeg.husos_sueno_n2"], partes["Fz", "eeg.husos_sueno_n2_z"]) == (1.4, -0.4)
|
|
|
|
|
|
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.
|
|
|
|
Fails if the silver mapping or the catalog drops one of the deviation's results.
|
|
"""
|
|
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]
|
|
|
|
|
|
def test_the_quality_view_lists_each_check_with_its_label(loaded):
|
|
"""Pins down: `tea_paciente_eeg_criterios` has one row per check of the EEG, study-wide ones without an electrode
|
|
and with their limit and decisive flag, the bad channel at its electrode as out of range and not decisive, each with the catalog's label; and the
|
|
electrodes view keeps only metric values, not channel checks.
|
|
|
|
Fails if the view stops pivoting a check's observations, misses the channel parts, or the electrodes view starts
|
|
reading the checks' parts as metrics.
|
|
"""
|
|
with loaded.motor.connect() as connection:
|
|
rows = connection.execute(text(
|
|
"select criterio, electrodo, valor, valor_texto, bajo, anormal, decisivo, etiqueta "
|
|
"from tea_paciente_eeg_criterios "
|
|
"order by criterio")).all()
|
|
electrodes = connection.execute(text("select metrica, electrodo from tea_paciente_eeg_electrodos")).all()
|
|
by_check = {r.criterio: r for r in rows}
|
|
assert set(by_check) == {"clean_windows", "triage_level", "dead_channel"}
|
|
assert (by_check["clean_windows"].valor, by_check["clean_windows"].bajo, by_check["clean_windows"].anormal,
|
|
by_check["clean_windows"].decisivo) == (95.0, 60.0, 0, 1)
|
|
assert (by_check["dead_channel"].electrodo, by_check["dead_channel"].anormal, by_check["dead_channel"].decisivo) == \
|
|
("T3", 1, 0)
|
|
assert by_check["clean_windows"].etiqueta == "Ventanas limpias"
|
|
assert [tuple(e) for e in electrodes] == [("husos_sueno_n2", "Fz")]
|
|
|
|
|
|
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.
|
|
|
|
Fails if dbt goes back to scoring metrics against fixed ranges of its own, 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"))}
|
|
(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 (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
|
|
assert tuple(electrode) == (1.4, -0.4)
|