141 lines
7.5 KiB
Python
141 lines
7.5 KiB
Python
"""What this module covers: the ADOS-2 association against the TEA database (`models.ados2_relation`): the cohort
|
|
it builds from bronze (first valid EEG and first ADOS-2 per child), the rows it writes to `relacion_ados2` and
|
|
`relacion_ados2_paciente`, and versions (a new cohort is a later version, the same cohort writes nothing).
|
|
|
|
Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, the invented cohort of `ados2_cohort` without item
|
|
scores (60 children, spindles in central lowering the CSS) written to bronze: each child with an ADOS-2 and a valid
|
|
analysed EEG `e-NNN` whose metric z and zone z are the cohort's, plus a later valid EEG `e-000-b` of child 1, an
|
|
invalid EEG of child 2 and a child 99 with an EEG and no ADOS-2.
|
|
"""
|
|
from datetime import date, datetime
|
|
|
|
import pytest
|
|
from ados2_cohort import ITEM_CODES, cohort
|
|
from sqlmodel import Session, select
|
|
|
|
from core.tea.models import Ados2, Eeg, EegMetrica, EegMetricaZona, Pacientes, RelacionAdos2, RelacionAdos2Paciente
|
|
from models import ados2_relation as rel
|
|
from tea.contracts import ZONES
|
|
|
|
CODES = {"spikes": "PICOS_PAROXISTICOS", "spindles": "HUSOS_SUENO_N2", "posterior_rhythm": "RITMO_POSTERIOR",
|
|
"gradient": "GRADIENTE_ANTEROPOSTERIOR"}
|
|
|
|
|
|
def _eeg(session, eeg_id, pac_id, row, *, studied=date(2025, 6, 1), valid=1):
|
|
session.add(Eeg(eeg_id=eeg_id, eeg_pac_id=pac_id, eeg_fecha_estudio=studied, eeg_valido=valid,
|
|
eeg_edad_meses=float(row.age_months)))
|
|
for biomarker, code in CODES.items():
|
|
met_id = f"{eeg_id}/{code}"
|
|
zoned = biomarker in rel.ZONED
|
|
session.add(EegMetrica(met_id=met_id, met_eeg_id=eeg_id, met_codigo=code,
|
|
met_z=None if zoned else float(row[f"z_{biomarker}"])))
|
|
if zoned:
|
|
session.add_all([EegMetricaZona(mez_id=f"{met_id}/{z}", mez_met_id=met_id, mez_zona=z,
|
|
mez_z=float(row[f"z_{biomarker}_{z}"])) for z in ZONES])
|
|
|
|
|
|
def _engine():
|
|
from persistance.db import get_tea_engine
|
|
|
|
return get_tea_engine()
|
|
|
|
|
|
@pytest.fixture
|
|
def stored(tea_db):
|
|
"""The CSS-only invented cohort in bronze, with the extra EEGs and child the module docstring lists."""
|
|
t = cohort().drop(columns=ITEM_CODES)
|
|
with Session(_engine()) as s:
|
|
for i, row in t.iterrows():
|
|
pac_id = i + 1
|
|
s.add(Pacientes(pac_id=pac_id, pac_id_hospital=f"H-{pac_id}"))
|
|
s.add(Ados2(ado_id=f"a-{pac_id}", ado_pac_id=pac_id, ado_fecha=date(2025, 5, 1),
|
|
ado_modulo=row.ados_module, ado_css=int(row.css)))
|
|
_eeg(s, row.key, pac_id, row)
|
|
_eeg(s, "e-000-b", 1, t.iloc[0], studied=date(2025, 9, 1))
|
|
_eeg(s, "e-001-x", 2, t.iloc[1], studied=date(2025, 3, 1), valid=0)
|
|
s.add(Pacientes(pac_id=99, pac_id_hospital="H-99"))
|
|
_eeg(s, "e-099", 99, t.iloc[2])
|
|
s.commit()
|
|
return t
|
|
|
|
|
|
def _read():
|
|
with Session(_engine()) as s:
|
|
return s.exec(select(RelacionAdos2)).all(), s.exec(select(RelacionAdos2Paciente)).all()
|
|
|
|
|
|
def test_a_fit_writes_one_version_of_estimated_rows_on_the_platform_codes(stored):
|
|
"""Pins down: one fit writes a `tea-<time>-<fingerprint>` version, unvalidated, over the 60 children with a
|
|
valid EEG and an ADOS-2, with the metric codes, `CSS` outcomes and an `>=8` event, and finds the planted
|
|
spindle effect in central. Fails if the cohort takes the child without ADOS-2 or the invalid EEG, the
|
|
biomarker codes stop following `model.toml`, or the written estimates stop being the library's."""
|
|
summary = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
|
models, patients = _read()
|
|
assert summary.children == 60 and summary.level == "domain"
|
|
assert summary.version.startswith("tea-20261121T120000-") and len(summary.version) <= 32
|
|
assert {m.rel_version for m in models} == {summary.version} and len(models) == summary.associations
|
|
assert {m.rel_validado for m in models} == {0} and {m.rel_n_cohorte for m in models} == {60}
|
|
assert {m.rel_resultado for m in models} == {"CSS"} and {m.rel_evento for m in models} == {">=8"}
|
|
assert {m.rel_biomarcador for m in models} <= set(CODES.values())
|
|
central = next(m for m in models if m.rel_biomarcador == "HUSOS_SUENO_N2" and m.rel_zona == "central")
|
|
assert central.rel_or < 1 and central.rel_q < .05
|
|
assert len(patients) == summary.scored
|
|
|
|
|
|
def test_every_valid_eeg_of_the_cohort_is_scored_and_no_other(stored):
|
|
"""Pins down: child 1's later valid EEG gets probabilities too (the gold view shows the study's EEG, whichever
|
|
it is), while the invalid EEG and the EEG of the child without ADOS-2 get none. Fails if scoring stops at the
|
|
fit's EEGs or starts scoring outside the cohort."""
|
|
rel.relate()
|
|
_, patients = _read()
|
|
eegs = {p.rap_eeg_id for p in patients}
|
|
assert {"e-000", "e-000-b"} <= eegs
|
|
assert not {"e-001-x", "e-099"} & eegs
|
|
assert all(0 <= p.rap_probabilidad <= 1 and 0 <= p.rap_probabilidad_referencia <= 1 for p in patients)
|
|
|
|
|
|
def test_the_same_cohort_writes_nothing_and_a_new_one_is_a_later_version(stored):
|
|
"""Pins down: fitting the same cohort again writes nothing and names the latest version; a changed z is a new
|
|
version that sorts after the first, so the gold view's greatest version is the newest fit. Fails if reruns
|
|
duplicate versions, or the version stops sorting by time."""
|
|
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
|
again = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
|
assert again.unchanged and again.version == first.version
|
|
assert len({m.rel_version for m in _read()[0]}) == 1
|
|
with Session(_engine()) as s:
|
|
zone = s.get(EegMetricaZona, "e-000/HUSOS_SUENO_N2/central")
|
|
zone.mez_z = 3.0
|
|
s.add(zone)
|
|
s.commit()
|
|
later = rel.relate(at=datetime(2026, 11, 23, 12, 0, 0))
|
|
assert not later.unchanged and later.version > first.version
|
|
assert {m.rel_version for m in _read()[0]} == {first.version, later.version}
|
|
|
|
|
|
def test_an_open_interval_is_stored_as_null():
|
|
"""Pins down: an infinite interval limit (the profile never crossed the threshold) is stored as NULL, which every
|
|
engine accepts. Fails if `inf` reaches the database (MySQL and SQL Server reject it)."""
|
|
assert rel._finite(float("inf")) is None and rel._finite(None) is None and rel._finite(2.5) == 2.5
|
|
|
|
|
|
def test_the_fit_uses_the_first_eeg_with_predictors_and_a_new_eeg_is_a_new_version(stored):
|
|
"""Pins down: a child whose earliest valid EEG has no metric rows is fitted on its next EEG, and a valid EEG
|
|
added for a child already in the fit (so the fit table is the same) is still a new version that scores it.
|
|
Fails if the fit takes an EEG without predictors (the child would drop out of every model), or the fingerprint
|
|
covers only the fit table (the new EEG would stay unscored)."""
|
|
with Session(_engine()) as s:
|
|
s.add(Eeg(eeg_id="e-000-a", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 1, 1), eeg_valido=1,
|
|
eeg_edad_meses=20.0))
|
|
s.commit()
|
|
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
|
|
assert first.children == 60
|
|
assert "e-000-a" not in {p.rap_eeg_id for p in _read()[1]}
|
|
with Session(_engine()) as s:
|
|
_eeg(s, "e-000-c", 1, stored.iloc[0], studied=date(2025, 12, 1))
|
|
s.commit()
|
|
later = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
|
|
assert not later.unchanged and later.version > first.version
|
|
models, patients = _read()
|
|
latest = {m.rel_id for m in models if m.rel_version == later.version}
|
|
assert "e-000-c" in {p.rap_eeg_id for p in patients if p.rap_rel_id in latest}
|