From 0f9433949fb0e109c4445bcdbdd9c816092e266e Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 12 Nov 2026 19:47:19 -0600 Subject: [PATCH] TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too --- tests/staging/tea.py | 2 +- tests/test_fhir_tea.py | 10 +++++++ tests/test_tea_measures.py | 56 ++++++++++++++++++++++++++++---------- webapi/fhir/__init__.py | 8 +----- webapi/kpis.py | 23 +++++++++++++--- webapi/metrics.py | 20 ++++++++++++++ 6 files changed, 93 insertions(+), 26 deletions(-) diff --git a/tests/staging/tea.py b/tests/staging/tea.py index 8bb82ce..531b13e 100644 --- a/tests/staging/tea.py +++ b/tests/staging/tea.py @@ -12,7 +12,7 @@ with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first stays at psychology. - 4, H-T04, 39 months: out of the cohort, never counted. - 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in - order, so it stays at M-CHAT. + order, so it stays at M-CHAT and in process. - 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG step is dated by the note, so it reaches EEG on 2 Jun and leaves after June. - 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else. diff --git a/tests/test_fhir_tea.py b/tests/test_fhir_tea.py index 03b8789..61533db 100644 --- a/tests/test_fhir_tea.py +++ b/tests/test_fhir_tea.py @@ -82,6 +82,16 @@ def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monke assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} +def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch): + """Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both + with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation.""" + assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()} + assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404 + monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") + assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()} + assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200 + + def test_a_measure_carries_what_the_page_needs(client): """Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category labels. Fails if the page's catalog fields stop reaching the Measure.""" diff --git a/tests/test_tea_measures.py b/tests/test_tea_measures.py index 6139462..3f1f890 100644 --- a/tests/test_tea_measures.py +++ b/tests/test_tea_measures.py @@ -19,7 +19,7 @@ from sqlmodel import select import staging.tea as fixture from conftest import base_de -from core.tea.models import Eeg, EegMetrica +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 @@ -106,9 +106,9 @@ RESULTS = { "2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2}, "2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2}, "2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3}, - "2025-07": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-07": {"EN_PROCESO": 3}, "2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3}, - "2025-S2": {"CONFIRMADO": 1, "EN_PROCESO": 2}, + "2025-S2": {"EN_PROCESO": 3}, } @@ -116,18 +116,19 @@ 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 - confirms it in July even without the ADOS-2. Fails if F84 counts as a confirmation or a note without F84.0 counts - as in process.""" + 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", 1, 3, 1), ("2025-S1", 2, 5, 1), + ("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. Fails if the denominator takes the children without TEA or the exclusion stops being counted.""" + 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) @@ -142,15 +143,15 @@ def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest): @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, 1, 1), - ("2025-S1", 2, 0, 2), ("2025-S2", 0, 1, 1), + ("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, confirmed in July, - has a good EEG but no ADOS-2, so its chain never reaches it. Fails if the EEG is read beyond the period's end or - outside the chain.""" + 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) @@ -164,14 +165,14 @@ def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, ("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, 1, 16.0), + ("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 16 days in the second semester only. Fails if the value is read beyond the period's end or the + 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) @@ -243,3 +244,30 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest): 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() diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index c039626..eaeb72f 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -39,13 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: def definitions() -> dict: """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" - every = {fhir_id(d): d for d in definitions_of(project, manifest).values()} - if project == "tea": - from webapi.fhir.tea import alterations_validated - - if not alterations_validated(): - every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")} - return every + return {fhir_id(d): d for d in definitions_of(project, manifest).values()} def definition_of(measure_id: str): return definitions().get(measure_id.replace("_", "-")) diff --git a/webapi/kpis.py b/webapi/kpis.py index abf497e..61941e8 100644 --- a/webapi/kpis.py +++ b/webapi/kpis.py @@ -10,6 +10,7 @@ durations (`webapi.durations`; without `corte_evento`, the day of the last load) import json from collections.abc import Callable from datetime import date, datetime, timezone +from functools import lru_cache from pathlib import Path from core.indicadores.tipos import FechaHoraUTC @@ -24,28 +25,42 @@ LOADS = table("carga", column("inicio", FechaHoraUTC)) def definitions_of(project: str, manifest: Path) -> dict: - """Every measure the manifest defines for the domain, by its id (the end of its url).""" + """Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for + a validation (`meta.requiere_validacion`) is left out until it's given.""" + return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)} + + +@lru_cache +def _defined(project: str, manifest: Path) -> dict: every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)} return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")} +def _awaits_validation(definition) -> bool: + """TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them.""" + if not definition.meta.get("requiere_validacion"): + return False + from webapi.fhir.tea import alterations_validated + + return not alterations_validated() + + def kpis_blueprint(project: str, repositories, manifest: Path, *, now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint: """The blueprint of a domain, to register with `url_prefix="/"`. `repositories` is the domain's `persistance.` module.""" blueprint = Blueprint(f"{project}_kpis", __name__) - definitions = definitions_of(project, manifest) @blueprint.get("/indicadores") def list_kpis(): """The measures answered on request: id, url, version and scoring.""" return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)} - for i, d in sorted(definitions.items())]) + for i, d in sorted(definitions_of(project, manifest).items())]) @blueprint.get("/indicadores/") def get_kpi(measure_id: str): """A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history.""" - definition = definitions.get(measure_id) + definition = definitions_of(project, manifest).get(measure_id) if definition is None: return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404 try: diff --git a/webapi/metrics.py b/webapi/metrics.py index 7baf63c..efb8c65 100644 --- a/webapi/metrics.py +++ b/webapi/metrics.py @@ -49,6 +49,7 @@ TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo" OF_THE_CHOSEN = "del_elegido" COLUMN = "columna" STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo" +KNOWN_VERSION = "version_conocida" class UndecidedRule(ValueError): @@ -283,10 +284,15 @@ class MeasureQueries: if self.status is not None: names |= {definition.dimensions[n] for n in self.status.columns()} known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n} + version = (getattr(definition, "meta", None) or {}).get(KNOWN_VERSION) + if version is not None: + known.add(definition.dimensions[version]) self.events = table(definition.relation, *( column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names) if name.isidentifier())) self.periods = period_table + if version is not None: + self.events = self._known_version(definition.dimensions[version]) if self.status is not None: self.events = self._status_rows() self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento") @@ -329,6 +335,20 @@ class MeasureQueries: conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff] return and_(*conditions) + def _known_version(self, version: str): + """Each unit's rows as they were known at the knowledge cut-off, for a model with one set of rows per unit + and knowledge version (`meta.version_conocida`, the column that dates each version): the unit's latest + version by the cut-off, or its latest of all without one. A subquery with the model's name, read as the + model is.""" + base = self.events + latest = func.rank().over(partition_by=base.c[self.d.numerator.measure_expr], order_by=desc(base.c[version])) + versions = select(*base.c, latest.label("lugar_de_version")) + if self.q.knowledge_cutoff is not None: + versions = versions.where(base.c[version] <= self.q.knowledge_cutoff) + versions = versions.subquery("versiones") + return (select(*(c for c in versions.c if c.name != "lugar_de_version")) + .where(versions.c.lugar_de_version == 1).subquery(self.d.relation)) + def _status_rows(self): """Each unit the period counts, with its row of highest order: a subquery with the model's name, so the rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds.