0c69140d2e
The 161-day diagnosis of the fixture is out of the 120-day window, and the sample-to-treatment horizon (180) leaves the August and October samples pending. The comparison with the kit's oracle (180 days to the diagnosis) is marked as an expected divergence until the oracle is regenerated with the project's horizon. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
595 lines
33 KiB
Python
595 lines
33 KiB
Python
"""What this module covers: `webapi.metrics` and `webapi.compositions`, CaCu's measures answered on request from
|
|
dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which
|
|
keeps each answer under its key.
|
|
|
|
Fixtures: `base`, the CaCu fixture database through the cycle up to `event_models` (which creates dbt's event models);
|
|
`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13
|
|
and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
from dataclasses import replace
|
|
from datetime import date, datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from sqlalchemy import text
|
|
from sqlmodel import Session, select
|
|
|
|
from conftest import base_de
|
|
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, Paciente
|
|
from webapi.compositions import answer_composition, composition_definitions, composition_report
|
|
from webapi.metrics import INTERVAL_HIGH, INTERVAL_LOW, Counts, Question, answer, measure_definitions, measure_report
|
|
from webapi.orchestration import run
|
|
|
|
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
|
|
STATUS = "estatus_seguimiento"
|
|
HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
|
PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"]
|
|
SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json"
|
|
|
|
|
|
@pytest.fixture
|
|
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
|
|
def base(tmp_path, sin_supresion, manifest):
|
|
base = base_de("cacu", tmp_path)
|
|
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
|
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
|
base.motor.dispose()
|
|
|
|
|
|
def _con_tratamiento(sesion: Session) -> None:
|
|
"""The fixture data and, for H-004, her colposcopy (August 20) and her treatment (August 28), after the
|
|
valuation visit of August 10: the timeline then holds a treatment to end an interval at."""
|
|
from staging.cacu import COLPOSCOPIA, FAMILIAR, insertar
|
|
|
|
insertar(sesion)
|
|
paciente = sesion.exec(select(Paciente).where(Paciente.pac_id_hospital == "H-004")).one()
|
|
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-004", nm_id_hospital=f"NM-9{n}", nm_fecha=fecha,
|
|
nm_cie_codigo=cie, nm_especialidad=especialidad)
|
|
for n, (fecha, cie, especialidad) in enumerate(
|
|
[(date(2025, 8, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 28), "D06.9", FAMILIAR)], start=1))
|
|
sesion.commit()
|
|
|
|
|
|
def _con_ruta(sesion: Session) -> None:
|
|
"""The fixture data and H-007, who goes the whole route in order: a cytology on July 5 with its result on July 15,
|
|
a valuation note on July 20, her colposcopy and the request of her biopsy on August 5, the biopsy report on
|
|
August 25 and a diagnosis after it on September 10."""
|
|
from staging.cacu import COLPOSCOPIA, ONCOLOGIA, SATISFACTORIO, insertar
|
|
|
|
insertar(sesion)
|
|
paciente = Paciente(pac_id_hospital="H-007", pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1))
|
|
sesion.add(paciente)
|
|
sesion.flush()
|
|
citologia = CitologiaCervical(pac_id=paciente.pac_id, pac_id_hospital="H-007", cit_fecha_toma=date(2025, 7, 5),
|
|
cit_calidad_especimen=SATISFACTORIO, cit_fecha_reporte=date(2025, 7, 15),
|
|
cit_celulas_escamosas="ASC-US", cit_vph_resultado="POSITIVO")
|
|
sesion.add(citologia)
|
|
sesion.flush()
|
|
sesion.add(BiopsiaCervical(pac_id=paciente.pac_id, pac_id_hospital="H-007", cit_id=citologia.cit_id,
|
|
bx_fecha_solicitud=date(2025, 8, 5), bx_fecha_reporte=date(2025, 8, 25), bx_cin_grado="CIN2"))
|
|
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-007", nm_id_hospital=f"NM-8{n}", nm_fecha=fecha,
|
|
nm_cie_codigo=cie, nm_especialidad=especialidad)
|
|
for n, (fecha, cie, especialidad) in enumerate(
|
|
[(date(2025, 7, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 5), "R87.6", COLPOSCOPIA),
|
|
(date(2025, 9, 10), "D06.9", ONCOLOGIA)], start=1))
|
|
sesion.commit()
|
|
|
|
|
|
@pytest.fixture
|
|
def base_con_ruta(tmp_path, sin_supresion, manifest):
|
|
base = base_de("cacu", tmp_path, datos=_con_ruta)
|
|
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
|
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
|
base.motor.dispose()
|
|
|
|
|
|
@pytest.fixture
|
|
def base_con_tratamiento(tmp_path, sin_supresion, manifest):
|
|
base = base_de("cacu", tmp_path, datos=_con_tratamiento)
|
|
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
|
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
|
base.motor.dispose()
|
|
|
|
|
|
@pytest.fixture
|
|
def kit():
|
|
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
|
|
|
|
|
|
@pytest.fixture
|
|
def definition(manifest):
|
|
return measure_definitions(manifest)[IND1]
|
|
|
|
|
|
@pytest.fixture
|
|
def eu13(manifest):
|
|
return measure_definitions(manifest)[EU13]
|
|
|
|
|
|
@pytest.fixture
|
|
def eu7(manifest):
|
|
return composition_definitions(manifest)[EU7]
|
|
|
|
|
|
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 ask(base, definition, period_id, *, event_cutoff=None, knowledge_cutoff=None):
|
|
question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff)
|
|
if definition.url == EU7:
|
|
return answer_composition("cacu", definition, question, **repositories(base))
|
|
return answer("cacu", definition, question, **repositories(base))
|
|
|
|
|
|
def units(base, report_id: int) -> list[list]:
|
|
with base.motor.connect() as connection:
|
|
return sorted(map(list, connection.execute(text(
|
|
"select grupo, resultado_id, unidad_id, pac_id, valor_id from measure_report_unidad where report_id = :r"),
|
|
{"r": report_id}).all()))
|
|
|
|
|
|
def strata_rows(base, report_id: int, stratum: str = "grupo_edad") -> list[list]:
|
|
with base.motor.connect() as connection:
|
|
return sorted(map(list, connection.execute(text(
|
|
"select unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r "
|
|
"and estrato_id = :e"), {"r": report_id, "e": stratum}).all()))
|
|
|
|
|
|
def proportion_cells(result) -> dict:
|
|
"""An answer as the snapshot keeps what `v_c1` published: `{"stratum|value": [numerator, denominator]}`."""
|
|
cells = {"total|total": [result.numerator, result.denominator]}
|
|
for stratum, values in result.strata.items():
|
|
cells |= {f"{stratum}|{v}": [c.numerator, c.denominator] for v, c in values.items()}
|
|
return cells
|
|
|
|
|
|
def composition_cells(result) -> dict:
|
|
"""An answer as the snapshot keeps what `v_c2` published: `{"stratum|value|category": n}`."""
|
|
cells = {f"total|total|{c}": n for c, n in result.categories.items()}
|
|
for stratum, values in result.strata.items():
|
|
cells |= {f"{stratum}|{v}|{c}": n for v, cs in values.items() for c, n in cs.items()}
|
|
return cells
|
|
|
|
|
|
def without(cells: dict, stratum: str) -> dict:
|
|
return {k: v for k, v in cells.items() if not k.startswith(f"{stratum}|")}
|
|
|
|
|
|
def reports(base) -> int:
|
|
with base.motor.connect() as connection:
|
|
return connection.execute(text("select count(*) from measure_report")).scalar_one()
|
|
|
|
|
|
def reload(base, change) -> None:
|
|
"""Changes the staging as the ingestion would and runs `load`: a new load, known later than everything before."""
|
|
time.sleep(0.01)
|
|
with Session(base.motor) as session:
|
|
change(session)
|
|
session.commit()
|
|
run(base.ctx, only=["load"])
|
|
|
|
|
|
def test_ind1_answers_what_the_kit_computed(base, definition, kit):
|
|
"""Pins down: with no cut-off, every period's IND1 has the kit's units and its numbers. Fails if the semantic
|
|
definition (event model, metrics, filter) stops meaning what the kit's IND1 meant."""
|
|
for period_id in PERIODS:
|
|
result, expected = ask(base, definition, period_id), kit[IND1][period_id]
|
|
assert units(base, result.report_id) == expected["units"], period_id
|
|
assert proportion_cells(result)["total|total"] == expected["published"].get("total|total", [0, 0]), period_id
|
|
|
|
|
|
def test_eu13_with_its_age_strata_answers_what_the_kit_computed(base, eu13, kit):
|
|
"""Pins down: EU13 gives the kit's units, each patient's age group at the period's start and the numbers by age
|
|
in every period. Fails if the event model, the report date's condition or the age from `dim_fecha` drift."""
|
|
for period_id in PERIODS:
|
|
result, expected = ask(base, eu13, period_id), kit[EU13][period_id]
|
|
assert units(base, result.report_id) == expected["units"], period_id
|
|
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
|
|
assert without(proportion_cells(result), STATUS) == (expected["published"] or {"total|total": [0, 0]}), period_id
|
|
|
|
|
|
def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7, kit):
|
|
"""Pins down EU7, a composition: each patient in the category of her last valid sample (with a result and a
|
|
satisfactory specimen) or SIN_DATO, with her age group, and the kit's counts by category, total and by age.
|
|
Fails if the ranking (validity, then the latest sample, then the source id) or the validity rule drifts."""
|
|
for period_id in PERIODS:
|
|
result, expected = ask(base, eu7, period_id), kit[EU7][period_id]
|
|
assert units(base, result.report_id) == expected["units"], period_id
|
|
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
|
|
assert without(composition_cells(result), STATUS) == expected["published"], period_id
|
|
|
|
|
|
def test_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7):
|
|
"""Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't
|
|
enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the
|
|
stratum values the catalog lacks."""
|
|
for d in (eu13, eu7):
|
|
ask(base, d, "2025-S1")
|
|
with base.motor.connect() as connection:
|
|
written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar()
|
|
broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all()
|
|
assert written > 0
|
|
assert broken == []
|
|
|
|
|
|
def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7):
|
|
"""Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same
|
|
answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing."""
|
|
for d in (definition, eu13, eu7):
|
|
first = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
|
|
before = reports(base)
|
|
again = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
|
|
assert (again.report_id, again.stored_before, reports(base)) == (first.report_id, True, before)
|
|
if d is eu7:
|
|
assert (again.categories, again.strata) == (first.categories, first.strata)
|
|
else:
|
|
assert proportion_cells(again) == proportion_cells(first)
|
|
|
|
|
|
def test_the_event_cutoff_leaves_out_later_facts(base, definition, kit):
|
|
"""Pins down: S1 cut at March 31 counts the patients of January to March: the union of the kit's monthly units.
|
|
Fails if the cut-off stops filtering the event date."""
|
|
result = ask(base, definition, "2025-S1", event_cutoff=date(2025, 3, 31))
|
|
months = sorted({tuple(u) for m in (1, 2, 3) for u in kit[IND1][f"2025-{m:02d}"]["units"]})
|
|
|
|
assert units(base, result.report_id) == [list(u) for u in months]
|
|
|
|
|
|
def test_a_late_fact_counts_only_under_a_later_knowledge_cutoff(base, definition):
|
|
"""Pins down: a cytology of S1 loaded later doesn't change what was known before its load; asked with a later
|
|
knowledge cut-off, it counts. Fails if `conocida_en` stops being a condition of the question."""
|
|
known = datetime.now(timezone.utc)
|
|
before = ask(base, definition, "2025-S1", knowledge_cutoff=known)
|
|
|
|
def late_cytology(session):
|
|
h005 = session.exec(select(CitologiaCervical).where(CitologiaCervical.pac_id_hospital == "H-005")).first()
|
|
session.add(CitologiaCervical(pac_id=h005.pac_id, pac_id_hospital="H-005", cit_fecha_toma=date(2025, 3, 10),
|
|
cit_calidad_especimen="SATISFACTORIO", cit_fecha_reporte=date(2025, 3, 20),
|
|
cit_celulas_escamosas="LIEAG"))
|
|
reload(base, late_cytology)
|
|
|
|
again = ask(base, definition, "2025-S1", knowledge_cutoff=known)
|
|
fresh_then = ask(base, definition, "2025-S1", knowledge_cutoff=known, event_cutoff=date(2025, 6, 30))
|
|
now = ask(base, definition, "2025-S1", knowledge_cutoff=datetime.now(timezone.utc))
|
|
|
|
assert again.report_id == before.report_id
|
|
assert (fresh_then.numerator, fresh_then.denominator) == (before.numerator, before.denominator)
|
|
assert (now.numerator, now.denominator) == (before.numerator + 1, before.denominator + 1)
|
|
|
|
|
|
def test_a_changed_fact_is_kept_by_the_history_not_by_the_knowledge_cutoff(base, definition):
|
|
"""Pins down the limit of the knowledge cut-off: silver keeps one version of each row, so after H-004's LIEAG of
|
|
July becomes NEGATIVO, recomputing S2 as known before the change can't give the old numerator; only the stored
|
|
answer still does. Fails if silver starts keeping versions (`dbt snapshot`): then expect the old one."""
|
|
known = datetime.now(timezone.utc)
|
|
shown = ask(base, definition, "2025-S2", knowledge_cutoff=known)
|
|
assert shown.numerator == 1
|
|
|
|
def corrected(session):
|
|
row = session.exec(select(CitologiaCervical).where(
|
|
CitologiaCervical.pac_id_hospital == "H-004", CitologiaCervical.cit_fecha_toma == date(2025, 7, 1))).one()
|
|
row.cit_celulas_escamosas = "NEGATIVO"
|
|
reload(base, corrected)
|
|
|
|
stored = ask(base, definition, "2025-S2", knowledge_cutoff=known)
|
|
recomputed_then = ask(base, definition, "2025-S2", knowledge_cutoff=known, event_cutoff=date(2025, 12, 31))
|
|
|
|
assert (stored.report_id, stored.numerator) == (shown.report_id, 1)
|
|
assert recomputed_then.numerator == 0 # the July result now counts as known after `known`: it's left out
|
|
assert ask(base, definition, "2025-S2", knowledge_cutoff=datetime.now(timezone.utc)).numerator == 0
|
|
|
|
|
|
def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base, eu13):
|
|
"""Pins down EU13's numerator, which the fixture leaves at 0: once H-004's biopsy of August 1 (from the July 1
|
|
sample) is LIEAG she counts in 2025-07 and 2025-S2, and an event cut-off before the report leaves her out.
|
|
Fails if the numerator stops following the sample's period, the grade rule, or the report's date."""
|
|
def lieag(session):
|
|
biopsy = session.exec(select(BiopsiaCervical).where(BiopsiaCervical.pac_id_hospital == "H-004")).one()
|
|
biopsy.bx_cin_grado = "LIEAG"
|
|
reload(base, lieag)
|
|
|
|
assert ask(base, eu13, "2025-07").numerator == 1
|
|
assert ask(base, eu13, "2025-S2").numerator == 1
|
|
assert ask(base, eu13, "2025-S2", event_cutoff=date(2025, 7, 31)).numerator == 0
|
|
|
|
|
|
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
|
|
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
|
|
inclusive period end, each population's count, the score with its interval, strata as a `stratifier`, and a
|
|
composition's categories as one more. Fails if a population, the score, a stratum or a category stops matching
|
|
the answer."""
|
|
period = base.dominio.dim_periodo_repository.get("2025-S1")
|
|
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
|
|
|
|
report = measure_report(definition, Question(IND1, "2025-S1"), ask(base, definition, "2025-S1"), period, at)
|
|
(group,) = report["group"]
|
|
assert report["measure"] == "cacu/IND1|0.3.2"
|
|
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
|
|
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
|
"initial-population": 4, "denominator": 4, "numerator": 1}
|
|
assert group["measureScore"]["value"] == 0.25
|
|
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
|
|
|
|
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
|
|
at)["group"][0]["stratifier"]
|
|
assert [s["code"] for s in stratifiers] == [[{"text": "grupo_edad"}], [{"text": STATUS}]]
|
|
|
|
composition = composition_report(eu7, Question(EU7, "2025-S1"), ask(base, eu7, "2025-S1"), period, at)
|
|
by_result = composition["group"][0]["stratifier"][0]
|
|
assert by_result["code"] == [{"text": "resultado"}]
|
|
assert {s["value"]["text"]: s["population"][0]["count"] for s in by_result["stratum"]} == {
|
|
"LIEBG": 1, "NEGATIVO": 2, "SIN_DATO": 1}
|
|
if os.environ.get("MEASURE_REPORT_OUT"):
|
|
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
|
|
|
|
|
|
def test_a_proportion_is_scored_with_its_wilson_interval():
|
|
"""Pins down: `Counts.score` carries the proportion and its 95 % Wilson interval as proportions, in the
|
|
`ic-bajo` and `ic-alto` extensions (1 of 4 is 0.25 within 0.0456 and 0.6994), and publishes no score when the
|
|
denominator is zero. Fails if an interval is dropped, comes out as a percentage, or a zero denominator is scored."""
|
|
score = Counts(1, 4).score
|
|
bounds = {e["url"]: e["valueDecimal"] for e in score["extension"]}
|
|
assert score["value"] == 0.25
|
|
assert bounds[INTERVAL_LOW] == pytest.approx(0.0456, abs=1e-4)
|
|
assert bounds[INTERVAL_HIGH] == pytest.approx(0.6994, abs=1e-4)
|
|
assert Counts(0, 0).score is None
|
|
|
|
|
|
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
|
|
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
|
|
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
|
|
|
|
|
# The oracle is the kit's output at the kit's 180-day horizon from the sample to the diagnosis; the project's is 120 (a
|
|
# parameter it set on purpose), so a sample the kit measures at 161 days is no longer measured. The comparison fails
|
|
# for that period until the oracle is regenerated from the kit with the project's horizon (strict: it then asks for
|
|
# this mark to go).
|
|
SIN_ORACULO_DE_120 = pytest.mark.xfail(strict=True, reason="the kit's oracle uses a 180-day horizon from the sample to the diagnosis; the project's is 120")
|
|
|
|
|
|
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, pytest.param(DIAS_TOMA_DIAGNOSTICO, marks=SIN_ORACULO_DE_120)])
|
|
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
|
|
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
|
|
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
|
|
cut-off (and, to diagnosis, unless a cervical cancer note came before it); the measured ones carry their days
|
|
(`dim_fecha.dia_num` differences); n, the median and the quartiles (inclusive, ANSI) and the excluded are the
|
|
kit's where it didn't suppress them (suppression isn't part of the prototype). Fails if the horizon, the day
|
|
arithmetic, the resolving note, the exclusion or the quartiles' interpolation drift."""
|
|
from webapi.durations import answer_duration, duration_definitions
|
|
|
|
expected = json.loads(ORACLE.read_text(encoding="utf-8"))[url]
|
|
definition = duration_definitions(manifest)[url]
|
|
for period_id, kit_report in expected["periodos"].items():
|
|
result = answer_duration("cacu", definition, Question(url, period_id), **repositories(base))
|
|
assert units_with_numbers(base, result.report_id) == kit_report["units"], period_id
|
|
published = dict(zip(kit_report["published_columns"], next(
|
|
row for row in kit_report["published"] if row[1] == "total")))
|
|
if published["suprimido"]:
|
|
continue
|
|
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
|
|
published["n"], published["mediana"], published["q1"], published["q3"], published["n_excluido"]), period_id
|
|
|
|
|
|
def units_with_numbers(base, report_id: int) -> list[list]:
|
|
with base.motor.connect() as connection:
|
|
return sorted(map(list, connection.execute(text(
|
|
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
|
|
"where report_id = :r"), {"r": report_id}).all()))
|
|
|
|
|
|
def test_the_follow_up_status_is_the_kit_s_in_every_period(base, eu13, eu7):
|
|
"""Pins down: EU13's and EU7's `estatus_seguimiento` gives each unit the kit's status at the period's start, and
|
|
the kit's published numbers by status. Fails if the timeline stratum, the procedures it infers or the order of
|
|
the values drift. The fixture's patients are all PRE_COLPOSCOPIA; the other statuses are pinned down by
|
|
`test_the_follow_up_status_follows_the_timeline`."""
|
|
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))
|
|
for period_id in PERIODS:
|
|
for definition in (eu13, eu7):
|
|
result, expected = ask(base, definition, period_id), oracle[definition.url]["periodos"][period_id]
|
|
assert strata_rows(base, result.report_id, STATUS) == sorted(
|
|
[u, v] for u, s, v in expected["strata"] if s == STATUS), (definition.url, period_id)
|
|
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
|
|
if definition is eu13:
|
|
published = {f"{STATUS}|{r['estrato_valor']}": [r["numerador"], r["denominador"]]
|
|
for r in rows if r["estrato_id"] == STATUS}
|
|
ours = {k: v for k, v in proportion_cells(result).items() if k.startswith(f"{STATUS}|")}
|
|
else:
|
|
published = {f"{STATUS}|{r['estrato_valor']}|{r['categoria']}": r["n"]
|
|
for r in rows if r["estrato_id"] == STATUS and r["n"]}
|
|
ours = {k: v for k, v in composition_cells(result).items() if k.startswith(f"{STATUS}|")}
|
|
assert ours == published, (definition.url, period_id)
|
|
|
|
|
|
def kit_status(base, reference: str) -> dict[str, str]:
|
|
"""What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules."""
|
|
import tomllib
|
|
|
|
from webapi.follow_up.status import estatus_al, reglas_de
|
|
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
|
from webapi.follow_up.listing import leer_estrato
|
|
from sqlalchemy import bindparam
|
|
|
|
rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
|
|
|
|
def rule(key):
|
|
node = rules
|
|
for part in key.split("."):
|
|
node = node[part]
|
|
return node["valor"]
|
|
|
|
values = {name: rule(key) for name, key in leer_estrato("cacu", STATUS).parametros.items()}
|
|
status = estatus_al(bindparam("referencia"), reglas_de(values))
|
|
query = select(status.c.pac_id, status.c.estatus)
|
|
named = set(query.compile().params)
|
|
with base.motor.connect() as connection:
|
|
rows = connection.execute(query, {n: v for n, v in {**values, "referencia": reference}.items() if n in named})
|
|
return {str(pac_id): value for pac_id, value in rows}
|
|
|
|
|
|
def follow_up(session) -> None:
|
|
"""Notes and orders that move three of the fixture's patients along follow-up, in a load of their own.
|
|
|
|
Patient 1 (sampled 2025-02-10): a valuation visit, a colposcopy note by its reason (with an accent) and a biopsy
|
|
order that day, then a treatment note: POST_TRATAMIENTO from then on. Patient 4 (sampled 2025-05-30): a
|
|
valuation visit, then a colposcopy note whose ICD-10 came «S/C» but whose diagnosis text names HPV:
|
|
POST_COLPOSCOPIA. Patient 3 (sampled 2025-01-20): a colposcopy note with no valuation before it, which doesn't
|
|
count, and her first cytology ordered by a specialty outside surveillance: no status holds, INFO_INSUFICIENTE.
|
|
"""
|
|
from core.cacu.indicadores.models import Carga, Observacion, Procedimiento
|
|
|
|
load = Carga(fuente="seguimiento", inicio=datetime.now(timezone.utc))
|
|
session.add(load)
|
|
session.flush()
|
|
|
|
def procedure(pac_id, study, kind, when, key, **observed) -> Procedimiento:
|
|
p = Procedimiento(fuente_tabla="seguimiento", fuente_id=key, carga_id=load.carga_id, pac_id=pac_id,
|
|
estudio_id=study, clase=kind, fecha=date.fromisoformat(when))
|
|
session.add(p)
|
|
session.flush()
|
|
for result, (column_name, value) in observed.items():
|
|
session.add(Observacion(procedimiento_id=p.procedimiento_id, carga_id=load.carga_id, pac_id=pac_id,
|
|
resultado_id=result.replace("__", "."), **{column_name: value}))
|
|
return p
|
|
|
|
def note(pac_id, when, key, *, cie, specialty="CLINICA_MUJER_COLPOSCOPIA", reason=None, text_dx=None):
|
|
observed = {"nota_medica__diagnostico": ("valor_texto", cie),
|
|
"nota_medica__especialidad": ("valor_id", specialty)}
|
|
if reason:
|
|
observed["nota_medica__motivo"] = ("valor_texto", reason)
|
|
if text_dx:
|
|
observed["nota_medica__diagnostico_texto"] = ("valor_texto", text_dx)
|
|
procedure(pac_id, "nota_medica", "encuentro", when, key, **observed)
|
|
|
|
note(1, "2025-02-20", "n1a", cie="R876")
|
|
note(1, "2025-03-03", "n1b", cie="Z000", reason="Acude a colposcopía")
|
|
procedure(1, "biopsia", "orden", "2025-03-03", "o1")
|
|
note(1, "2025-04-01", "n1c", cie="D06", specialty="CIRUGIA_ONCOLOGICA")
|
|
note(4, "2025-06-05", "n4a", cie="R876")
|
|
note(4, "2025-06-10", "n4b", cie="S/C", text_dx="Virus del papiloma humano")
|
|
note(3, "2025-01-25", "n3a", cie="Z000", reason="COLPOSCOPIA")
|
|
order = procedure(3, "citologia", "orden", "2025-01-19", "c3",
|
|
orden__especialidad=("valor_id", "CIRUGIA_ONCOLOGICA"))
|
|
(sample,) = session.exec(select(Procedimiento).where(
|
|
Procedimiento.pac_id == 3, Procedimiento.estudio_id == "citologia", Procedimiento.clase == "toma",
|
|
Procedimiento.fecha == date(2025, 1, 20))).all()
|
|
sample.padre_id = order.procedimiento_id
|
|
|
|
|
|
def test_the_follow_up_status_follows_the_timeline(base, eu13, eu7):
|
|
"""Pins down: with colposcopies and a treatment on the timeline, every unit of EU13 and EU7 in every period gets
|
|
the status the kit's `estatus_al` gives her at the period's start, and all four statuses come out; asked with a
|
|
knowledge cut-off before those facts arrived, they're PRE_COLPOSCOPIA again. Fails if an inferred procedure
|
|
(the valuation requirement, the same-day order, the accent-blind reason, the diagnosis text), the timeline
|
|
stratum or the values' order stops meaning what the kit's rules mean."""
|
|
with base.motor.connect() as connection:
|
|
before_load = connection.execute(text("select max(inicio) from carga")).scalar_one()
|
|
with Session(base.motor) as session:
|
|
follow_up(session)
|
|
session.commit()
|
|
|
|
seen = set()
|
|
for period_id in PERIODS:
|
|
start = base.dominio.dim_periodo_repository.get(period_id).inicio.isoformat()
|
|
expected = kit_status(base, start)
|
|
for definition in (eu13, eu7):
|
|
ours = dict(strata_rows(base, ask(base, definition, period_id).report_id, STATUS))
|
|
assert ours == {unit: expected[unit] for unit in ours}, (definition.url, period_id)
|
|
seen |= set(ours.values())
|
|
assert seen == {"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA", "POST_TRATAMIENTO", "INFO_INSUFICIENTE"}
|
|
|
|
known_then = datetime.fromisoformat(before_load)
|
|
earlier = ask(base, eu13, "2025-10", knowledge_cutoff=known_then)
|
|
assert set(dict(strata_rows(base, earlier.report_id, STATUS)).values()) == {"PRE_COLPOSCOPIA"}
|
|
|
|
|
|
def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_yet(base, manifest):
|
|
"""Pins down the cut-off of the time to diagnosis: in 2025-S2 cut at September 30, the July sample resolved in
|
|
August is measured (40 days); the August sample, resolved only in January, and the September one, with no note,
|
|
are still within 180 days, so they aren't measured yet; the October sample is after the cut. Fails if a note
|
|
after the cut-off counts, or a pending sample enters the initial population."""
|
|
from webapi.durations import answer_duration, duration_definitions
|
|
|
|
definition = duration_definitions(manifest)[DIAS_TOMA_DIAGNOSTICO]
|
|
result = answer_duration("cacu", definition, Question(DIAS_TOMA_DIAGNOSTICO, "2025-S2", date(2025, 9, 30)),
|
|
**repositories(base))
|
|
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
|
|
|
|
|
|
DIAS_TOMA_TRATAMIENTO = "cacu/CACU_DIAS_TOMA_TRATAMIENTO"
|
|
DIAS_DIAGNOSTICO_TRATAMIENTO = "cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"
|
|
|
|
|
|
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (1, 1, 58.0, 0)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
|
|
def test_the_times_to_treatment_are_counted_from_their_start_to_the_first_treatment(base_con_tratamiento, manifest, url, expected):
|
|
"""Pins down the two times to treatment on the fixture with H-004's colposcopy and treatment, 2025-S2 cut at the
|
|
end of the year. From the sample (a 180-day horizon): H-004's July sample reaches her treatment of August 28 in 58
|
|
days; the others of the semester (August 12, September 1 and October 2) have no treatment and their horizon is
|
|
after the cut, so they are pending and not in the initial population. From the diagnosis (60 days): only that
|
|
sample has one in the period, and its diagnosis of August 10 reaches the treatment in 18 days. Fails if the end
|
|
event, the start (sample or diagnosis), the horizon
|
|
rule or the split between not measured yet and without event changes."""
|
|
from webapi.durations import answer_duration, duration_definitions
|
|
|
|
definition = duration_definitions(manifest)[url]
|
|
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)),
|
|
**repositories(base_con_tratamiento))
|
|
assert (result.initial, result.n, result.median, result.excluded) == expected
|
|
|
|
|
|
RUTA = { # url -> (población inicial, n, mediana, excluidas) en 2025-S2, con corte a fin de año
|
|
"cacu/CACU_DIAS_TOMA_COLPOSCOPIA": (5, 1, 31.0, 4),
|
|
"cacu/CACU_DIAS_TOMA_BIOPSIA": (5, 2, 41.0, 3),
|
|
"cacu/CACU_DIAS_RESULTADO_COLPOSCOPIA": (3, 1, 21.0, 2),
|
|
"cacu/CACU_DIAS_COLPOSCOPIA_BIOPSIA": (1, 1, 20.0, 0),
|
|
"cacu/CACU_DIAS_BIOPSIA_DIAGNOSTICO": (2, 2, 12.5, 0),
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("url", sorted(RUTA))
|
|
def test_the_times_along_the_screening_route_count_between_consecutive_events(base_con_ruta, manifest, url):
|
|
"""Pins down the five times of the screening route on the fixture with H-007, 2025-S2 cut at the end of the year.
|
|
From the sample: H-007's colposcopy (31 days) and the biopsy reports of H-004 (31) and H-007 (51); the other
|
|
samples have none and their 60-day horizon has passed, so they are in the initial population and not measured.
|
|
Between events: the colposcopy from the cytology result (21 days), the biopsy report from the colposcopy (20) and
|
|
the diagnosis from the biopsy report (9 and 16 days). Fails if an event, its start, its horizon or the population
|
|
each measure counts over changes."""
|
|
from webapi.durations import answer_duration, duration_definitions
|
|
|
|
definition = duration_definitions(manifest)[url]
|
|
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)), **repositories(base_con_ruta))
|
|
assert (result.initial, result.n, result.median, result.excluded) == RUTA[url]
|
|
|
|
|
|
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
|
|
|
|
|
def test_the_confirmation_by_biopsy_is_the_kit_s_in_every_period(base, manifest):
|
|
"""Pins down the composition that follows the chosen fact: each patient whose last valid sample of the period is
|
|
high grade, in the grade of the most severe biopsy that sample led to by the cut-off (SIN_BIOPSIA without one),
|
|
by that sample's result; units, strata and counts are the kit's in every period. Fails if the two-level ranking,
|
|
the admission on the chosen sample, the severity order or the chosen-row stratum drift."""
|
|
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))[CONFIRMACION]
|
|
definition = composition_definitions(manifest)[CONFIRMACION]
|
|
for period_id, expected in oracle["periodos"].items():
|
|
result = answer_composition("cacu", definition, Question(CONFIRMACION, period_id), **repositories(base))
|
|
assert units(base, result.report_id) == [u[:5] for u in expected["units"]], period_id
|
|
assert strata_rows(base, result.report_id, "citologia_alto_grado") == sorted(
|
|
[u, v] for u, s, v in expected["strata"] if s == "citologia_alto_grado"), period_id
|
|
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
|
|
published = {f"{r['estrato_id']}|{r['estrato_valor']}|{r['categoria']}": r["n"] for r in rows if r["n"]}
|
|
assert {k: v for k, v in composition_cells(result).items() if v} == published, period_id
|