274 lines
16 KiB
Python
274 lines
16 KiB
Python
"""What this module covers: TEA's ten measures answered on request from dbt's semantic layer, on hand-written
|
|
expectations for the synthetic children of `staging.tea`, period by period: who each period counts (the children in
|
|
the screening during it, at their stage at its end, leaving after the period of their good EEG), the day counts, the
|
|
EEGs by quality and the alterations of each child's first good EEG.
|
|
|
|
Fixtures: `base`, TEA's fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
|
|
`manifest.json` (`DBT_MANIFEST`; skipped without it). The expectations are worked out by hand from the children's
|
|
dates in `staging/tea.py`; each test says which child makes each number.
|
|
"""
|
|
|
|
import os
|
|
from dataclasses import replace
|
|
from datetime import date, datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from sqlalchemy import text
|
|
from sqlmodel import select
|
|
|
|
import staging.tea as fixture
|
|
from conftest import base_de
|
|
from core.tea.models import Ados2, Eeg, EegMetrica, Mchat
|
|
from webapi.compositions import answer_composition, composition_definitions
|
|
from webapi.durations import answer_duration, duration_definitions
|
|
from webapi.metrics import Question, answer, measure_definitions
|
|
|
|
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def manifest():
|
|
path = os.environ.get("DBT_MANIFEST")
|
|
if not path:
|
|
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
|
return Path(path)
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def base(tmp_path_factory, manifest):
|
|
"""The seven children of `staging.tea`, loaded once, with dbt's TEA views created."""
|
|
base = base_de("tea", tmp_path_factory.mktemp("tea"))
|
|
base.run(*UNTIL_MODELS, allow_undecided=True)
|
|
yield replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
|
base.motor.dispose()
|
|
|
|
|
|
def repositories(base) -> dict:
|
|
d = base.dominio
|
|
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
|
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
|
|
|
|
|
def composition(base, manifest, measure_id, period, **question):
|
|
url = f"tea/{measure_id}"
|
|
result = answer_composition("tea", composition_definitions(manifest)[url], Question(url, period, **question),
|
|
**repositories(base))
|
|
return {k: v for k, v in result.categories.items() if v}
|
|
|
|
|
|
def proportion(base, manifest, measure_id, period, **question):
|
|
url = f"tea/{measure_id}"
|
|
return answer("tea", measure_definitions(manifest)[url], Question(url, period, **question), **repositories(base))
|
|
|
|
|
|
def duration(base, manifest, measure_id, period):
|
|
url = f"tea/{measure_id}"
|
|
return answer_duration("tea", duration_definitions(manifest)[url], Question(url, period), **repositories(base))
|
|
|
|
|
|
STAGES = {
|
|
"2025-01": {"SOLO_MCHAT": 2},
|
|
"2025-02": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2},
|
|
"2025-03": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 1},
|
|
"2025-04": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 2},
|
|
"2025-05": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 1, "EEG": 1},
|
|
"2025-06": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 1},
|
|
"2025-07": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
|
"2025-12": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
|
"2025-S1": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2},
|
|
"2025-S2": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("period", sorted(STAGES))
|
|
def test_m28_counts_every_child_in_the_screening_at_its_stage_at_the_period_s_end(base, manifest, period):
|
|
"""Pins down M28: a period counts every cohort child who entered by its end and hadn't finished before its start,
|
|
at the furthest step reached by its end, whether or not anything of theirs happened in it. Child 1 is at
|
|
psychology in February and March's stage moves with its note; it reaches EEG in May and is gone from June. Child 2
|
|
stays at neuropediatrics all year; child 5 stays at M-CHAT (no ADOS-2); child 6 reaches EEG on its note's day,
|
|
2 June; child 4 (39 months) never counts; child 7 (no birth date) counts from May.
|
|
|
|
Fails if the population goes back to the children with a fact in the period, if a child stops leaving after the
|
|
period of its good EEG, or if a step stops needing the previous one."""
|
|
assert composition(base, manifest, "M28_casos_por_estado", period) == STAGES[period]
|
|
|
|
|
|
def test_m28_an_event_cut_off_leaves_out_what_came_after_it(base, manifest):
|
|
"""Pins down: facts dated after the event cut-off don't count. With a cut-off of 10 May, child 1's good EEG of
|
|
20 May isn't there, so May counts it at neuropediatrics. Fails if the status rows stop applying the cut-off."""
|
|
assert composition(base, manifest, "M28_casos_por_estado", "2025-05", event_cutoff=date(2025, 5, 10)) == {
|
|
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
|
|
|
|
|
RESULTS = {
|
|
"2025-01": {"EN_PROCESO": 2},
|
|
"2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
|
"2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
|
"2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3},
|
|
"2025-07": {"EN_PROCESO": 3},
|
|
"2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3},
|
|
"2025-S2": {"EN_PROCESO": 3},
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("period", sorted(RESULTS))
|
|
def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period):
|
|
"""Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's
|
|
note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note
|
|
of July doesn't confirm it without the ADOS-2: it stays in process. Fails if F84 counts as a confirmation, if a
|
|
note without F84.0 counts as in process, or if a note counts before the psychology step."""
|
|
assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period]
|
|
|
|
|
|
@pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [
|
|
("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 0, 3, 1), ("2025-S1", 2, 5, 1),
|
|
])
|
|
def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator,
|
|
excluded):
|
|
"""Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion
|
|
from April. In July child 5's F84.0 note, without the ADOS-2, leaves it in process. Fails if the denominator takes
|
|
the children without TEA, the exclusion stops being counted, or a note confirms without the psychology step."""
|
|
result = proportion(base, manifest, "M24_confirmacion_diagnostico", period)
|
|
assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded)
|
|
|
|
|
|
def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest):
|
|
"""Pins down: the age group is the child's at its first M-CHAT, one per child, the page's windows. In March, child
|
|
1 (19 months) is confirmed, child 2 (26) and child 3 (35) are in process. Fails if the stratum goes back to the age
|
|
at the period's start or loses a window."""
|
|
result = proportion(base, manifest, "M24_confirmacion_diagnostico", "2025-03")
|
|
strata = {v: (c.numerator, c.denominator) for v, c in result.strata["grupo_edad"].items()}
|
|
assert strata == {"16_23": (1, 1), "24_29": (0, 1), "30_36": (0, 1)}
|
|
|
|
|
|
@pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [
|
|
("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 0, 0),
|
|
("2025-S1", 2, 0, 2), ("2025-S2", 0, 0, 0),
|
|
])
|
|
def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg,
|
|
without_eeg, confirmed):
|
|
"""Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG
|
|
by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5 has a F84.0 note and
|
|
a good EEG in July but no ADOS-2, so it isn't confirmed and July has nobody. Fails if the EEG is read beyond the
|
|
period's end, or the note or the EEG count outside the chain."""
|
|
m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period)
|
|
m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period)
|
|
assert (m21.numerator, m21.denominator) == (with_eeg, confirmed)
|
|
assert (m22.numerator, m22.denominator) == (without_eeg, confirmed)
|
|
|
|
|
|
@pytest.mark.parametrize(("measure_id", "period", "initial", "n", "median"), [
|
|
("M26_dias_mchat_ados2", "2025-01", 2, 0, None),
|
|
("M26_dias_mchat_ados2", "2025-02", 3, 2, 20.0),
|
|
("M26_dias_mchat_ados2", "2025-03", 3, 3, 26.0),
|
|
("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5),
|
|
("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0),
|
|
("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5),
|
|
("M25_dias_mchat_diagnostico", "2025-S2", 4, 0, None),
|
|
])
|
|
def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period,
|
|
initial, n, median):
|
|
"""Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval
|
|
ended by the period's end have days (repeated in each period that counts them), the rest count as without event.
|
|
In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of
|
|
1 July gives no days without the ADOS-2. Fails if the value is read beyond the period's end or the
|
|
population goes back to the facts in the period."""
|
|
result = duration(base, manifest, measure_id, period)
|
|
assert (result.initial, result.n, result.median) == (initial, n, median)
|
|
|
|
|
|
@pytest.mark.parametrize(("period", "expected"), [
|
|
("2025-04", {"MALO": 1}), ("2025-05", {"BUENO": 1}), ("2025-09", {"BUENO": 1}),
|
|
("2025-S1", {"BUENO": 2, "MALO": 1}), ("2025-S2", {"BUENO": 2}),
|
|
])
|
|
def test_m29_counts_the_period_s_eegs_good_or_bad(base, manifest, period, expected):
|
|
"""Pins down M29: the EEGs of the cohort's children dated in the period, by exam, good or bad. Child 1's bad EEG of
|
|
April and its second good one of September count; so does child 5's, though its chain never reaches it. Fails if
|
|
M29 stops counting exams, or a bad EEG stops showing."""
|
|
assert composition(base, manifest, "M29_calidad_eeg", period) == expected
|
|
|
|
|
|
@pytest.mark.parametrize(("period", "total", "ritmo_posterior"), [
|
|
("2025-05", (1, 1), (1, 1)), ("2025-06", (0, 1), (0, 1)), ("2025-S1", (1, 2), (1, 2)), ("2025-S2", (0, 1), (0, 1)),
|
|
])
|
|
def test_m30_reads_the_alterations_of_each_child_s_first_good_eeg(base, manifest, period, total, ritmo_posterior):
|
|
"""Pins down M30: of the children whose first good EEG falls in the period, those with an alteration in it, in
|
|
total and in one group per alteration. Child 1's EEG of 20 May has a slow posterior rhythm (3.2 Hz at 23 months,
|
|
against 4.5 to 7.0); its second good EEG of September doesn't count. Fails if a later EEG counts, or the groups
|
|
stop being answered one by one."""
|
|
result = proportion(base, manifest, "M30_resultado_eeg", period)
|
|
assert (result.numerator, result.denominator) == total
|
|
assert (result.groups["ritmo_posterior"].numerator, result.groups["ritmo_posterior"].denominator) == ritmo_posterior
|
|
assert result.groups["husos_sueno_n2"].numerator == 0
|
|
|
|
|
|
def test_m30_read_back_from_the_history_keeps_its_groups(base, manifest):
|
|
"""Pins down: asking again reads the stored answer, groups included. Fails if a stored answer loses its groups or
|
|
counts every group's units in the total."""
|
|
first = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
|
again = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
|
assert again.stored_before and (again.numerator, again.denominator) == (first.numerator, first.denominator)
|
|
assert again.groups == first.groups
|
|
|
|
|
|
def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
|
|
"""Pins down: a step known after the knowledge cut-off doesn't move the child. Child 1's good EEG and its metrics
|
|
arrive in a second load; asked as of the first load, May still counts child 1 at neuropediatrics and it hasn't
|
|
left in June. Fails if the status rows stop applying the knowledge cut-off to the steps or to the exit."""
|
|
def without_the_good_eeg(session):
|
|
fixture.insertar(session)
|
|
session.flush()
|
|
for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")):
|
|
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
|
|
session.delete(row)
|
|
|
|
base = base_de("tea", tmp_path, without_the_good_eeg)
|
|
try:
|
|
base.run(*UNTIL_MODELS, allow_undecided=True)
|
|
with base.motor.begin() as connection:
|
|
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
|
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
|
with base.staging() as session:
|
|
session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1,
|
|
eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0,
|
|
eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0,
|
|
eeg_ruido_linea_db=3.5))
|
|
session.commit()
|
|
base.run("load", allow_undecided=True)
|
|
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
|
assert composition(later, manifest, "M28_casos_por_estado", "2025-05", knowledge_cutoff=known) == {
|
|
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
|
assert composition(later, manifest, "M28_casos_por_estado", "2025-06", knowledge_cutoff=known)[
|
|
"NEUROPEDIATRIA"] == 2
|
|
assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1
|
|
finally:
|
|
base.motor.dispose()
|
|
|
|
|
|
def test_a_knowledge_cut_off_keeps_what_was_known_when_an_earlier_fact_arrives_later(tmp_path, manifest):
|
|
"""Pins down: an answer as of a load doesn't change when a later load brings an earlier-dated fact. A second load
|
|
adds an ADOS-2 of 20 Feb for child 3 (its known one is of 28 Feb) and an M-CHAT of 1 Apr for child 7 (its known
|
|
one is of 1 May). Asked as of the first load, March still counts child 3 at psychology and May still counts
|
|
child 7; asked as of now, child 7 is in the screening from April. Fails if a child's first fact is chosen among
|
|
every load's facts and then dropped for being known after the cut-off."""
|
|
base = base_de("tea", tmp_path)
|
|
try:
|
|
base.run(*UNTIL_MODELS, allow_undecided=True)
|
|
with base.motor.begin() as connection:
|
|
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
|
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
|
with base.staging() as session:
|
|
session.add(Ados2(ado_id="ado-3-earlier", ado_pac_id=3, ado_fecha=date(2025, 2, 20), ado_modulo="MODULO_2",
|
|
ado_css=2))
|
|
session.add(Mchat(mch_id="mch-7-earlier", mch_pac_id=7, mch_fecha=date(2025, 4, 1), mch_puntaje=7))
|
|
session.commit()
|
|
base.run("load", allow_undecided=True)
|
|
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
|
for period in ("2025-03", "2025-05"):
|
|
assert composition(later, manifest, "M28_casos_por_estado", period, knowledge_cutoff=known) == STAGES[period]
|
|
assert composition(later, manifest, "M28_casos_por_estado", "2025-04") == {
|
|
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
|
finally:
|
|
base.motor.dispose()
|