Files
WebApi/tests/test_cama_l3_measures.py
Angel Capetillo Zavala b1bbbc25b4 Integrate CaMa follow-up, descriptive analysis and L3 with dev
Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
2026-11-17 10:44:07 -06:00

311 lines
20 KiB
Python

"""What this module covers: the three CaMa measures of L3, answered on request from dbt's semantic layer over the follow-up
fixture's invented patients (plus three on a period boundary and the diagnosing notes of the cases below): the detection
rate (`CAMA_TASA_DETECCION_HISTOPATOLOGICA`, C1), the time from the mammogram's result to the diagnosis
(`CAMA_DIAS_RESULTADO_DIAGNOSTICO`, C3r) and the histopathological result by BI-RADS (`CAMA_HISTOPATOLOGIA_BIRADS`, C2
stratified by BI-RADS). Every number here is worked out by hand from the cases, not read from the measure.
Fixtures: `base`, the CaMa database loaded from `insertar_l3` through the cycle up to `event_models` (dbt's views, the three
new ones included); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it). Suppression is off (threshold 1).
Cases added to the follow-up fixture's (see `test_cama_follow_up.py`):
- P18 / P19 / P20: biopsies reported on the last day of a semester (06-30), the first day of the next (07-01) and the last
day of the year (12-31): which period each report counts in, and the inclusive event cut-off.
- Notes (a diagnosing note is a CIE-10 of the list written by oncologic surgery): P01 12 days after her report, P07 the
same day, P08 a note between her mammogram and her report (not counted) and one 37 days after it, P09 193 days after
(beyond the horizon), P03 an earlier breast cancer note (leaves her out), P04 a note by a specialty that doesn't
diagnose, P12 the same day, P20 39 days after.
"""
import os
from dataclasses import replace
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import pytest
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, Paciente
from sqlalchemy import text
from sqlmodel import Session, select
from conftest import base_de
from test_cama_follow_up import UNTIL_MODELS, insertar
from webapi.compositions import answer_composition, composition_definitions
from webapi.durations import answer_duration, duration_definitions
from webapi.fhir.measures import measure_report
from webapi.metrics import Question, answer, measure_definitions
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
D = date
TASA = "cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA"
DIAS = "cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO"
HISTO = "cama/CAMA_HISTOPATOLOGIA_BIRADS"
BIRADS_PACIENTE = "cama/CAMA_BIRADS456_PACIENTE"
DIAS_TOMA = "cama/CAMA_DIAS_TOMA_DIAGNOSTICO"
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
NUEVOS = {
"P18": (D(1970, 1, 1), [(D(2025, 6, 20), "B4A", D(2025, 6, 25))]),
"P19": (D(1970, 1, 1), [(D(2025, 6, 25), "B5", D(2025, 6, 28))]),
"P20": (D(1970, 1, 1), [(D(2025, 12, 20), "B5", D(2025, 12, 24))]),
}
# (patient, request date, report date, grade): the mammogram of each of them is its first
BIOPSIAS_NUEVAS = (
("P18", D(2025, 6, 26), D(2025, 6, 30), "BENIGNO"),
("P19", D(2025, 6, 29), D(2025, 7, 1), "CARCINOMA_INVASOR"),
("P20", D(2025, 12, 28), D(2025, 12, 31), "CARCINOMA_IN_SITU"),
)
# (patient, date, CIE-10, specialty)
NOTAS = (
("P01", D(2025, 12, 20), "R92", ONCOLOGIA),
("P07", D(2025, 12, 17), "N60", ONCOLOGIA),
("P08", D(2025, 12, 5), "R92", ONCOLOGIA),
("P08", D(2026, 1, 15), "R92", ONCOLOGIA),
("P09", D(2026, 5, 20), "R92", ONCOLOGIA),
("P03", D(2025, 1, 10), "C50", FAMILIAR),
("P03", D(2025, 12, 1), "R92", ONCOLOGIA),
("P04", D(2025, 11, 10), "R92", FAMILIAR),
("P12", D(2025, 12, 22), "Z123", ONCOLOGIA),
("P20", D(2026, 2, 1), "R92", ONCOLOGIA),
)
CORTE = D(2025, 12, 31)
def insertar_l3(sesion: Session) -> None:
insertar(sesion)
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n) for h, (n, _) in NUEVOS.items()}
sesion.add_all(pacientes.values())
sesion.flush()
mastografias = {}
for hospital, (_, tomas) in NUEVOS.items():
toma, birads, reporte = tomas[0]
mastografias[hospital] = Mastografia(pac_id=pacientes[hospital].pac_id, pac_id_hospital=hospital, mast_fecha_toma=toma,
mast_calidad_imagen="SATISFACTORIO", mast_birads=birads, mast_fecha_reporte=reporte)
sesion.add_all(mastografias.values())
sesion.flush()
for hospital, solicitud, reporte, grado in BIOPSIAS_NUEVAS:
m = mastografias[hospital]
sesion.add(BiopsiaMama(pac_id=m.pac_id, pac_id_hospital=hospital, mast_id=m.mast_id, bx_fecha_solicitud=solicitud,
bx_fecha_reporte=reporte, bx_grado_histologico=grado))
todos = {p.pac_id_hospital: p for p in sesion.exec(select(Paciente))}
sesion.add_all(NotaMedica(pac_id=todos[h].pac_id, pac_id_hospital=h, nm_id_hospital=f"NM-{i:03d}", nm_fecha=fecha,
nm_cie_codigo=cie, nm_especialidad=esp) for i, (h, fecha, cie, esp) in enumerate(NOTAS, start=1))
sesion.commit()
@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):
carpeta = tmp_path_factory.mktemp("cama_l3")
sin_supresion = carpeta / "parametros.toml"
sin_supresion.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
base = base_de("cama", carpeta, datos=insertar_l3)
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, 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 proporcion(base, manifest, periodo, corte=None):
r = answer("cama", measure_definitions(manifest)[TASA], Question(TASA, periodo, corte), **repositories(base))
return r.numerator, r.denominator
def duracion(base, manifest, periodo, corte=None, url=DIAS):
return answer_duration("cama", duration_definitions(manifest)[url], Question(url, periodo, corte), **repositories(base))
def composicion(base, manifest, periodo, corte=None, conocimiento=None, url=HISTO):
return answer_composition("cama", composition_definitions(manifest)[url], Question(url, periodo, corte, conocimiento),
**repositories(base))
def matriz(resultado) -> dict:
return {(b, c): n for b, por in resultado.strata["birads"].items() for c, n in por.items()}
# --- the detection rate -----------------------------------------------------------------------------------------------
def test_the_detection_rate_counts_biopsy_reports_with_a_known_result_by_the_day_of_the_report(base, manifest):
"""Pins down: the rate's units are biopsy reports dated by the report, over those with a known grade. The semester 1 holds
P18's benign report of 06-30 (the last day); the semester 2 holds P19's invasive of 07-01 (the first), P20's in situ of 12-31
(the last), P01's invasive, P04's benign and P06's two (benign and in situ): 6 known and 4 malignant; P05's has no grade, so it
is outside both parts. Fails if a boundary day falls in the wrong period, a report without grade enters the denominator, or
each patient (P06 has two reports) counts once instead of each report."""
assert proporcion(base, manifest, "2025-S1") == (0, 1)
assert proporcion(base, manifest, "2025-S2") == (4, 6)
def test_the_detection_rate_by_month_adds_up_to_the_semesters_and_the_cutoff_is_inclusive(base, manifest):
"""Pins down: the months of a semester hold the same reports as the semester (every report is in exactly one month), and a
cut-off on the day of a report counts it while the day before doesn't. Fails if the monthly and the semester counts drift
or the event cut-off excludes its own day."""
meses = ["2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"]
por_mes = [proporcion(base, manifest, m) for m in meses]
assert (sum(n for n, _ in por_mes), sum(d for _, d in por_mes)) == proporcion(base, manifest, "2025-S2")
assert proporcion(base, manifest, "2025-12") == (2, 2)
assert proporcion(base, manifest, "2025-12", D(2025, 12, 31)) == (2, 2)
assert proporcion(base, manifest, "2025-12", D(2025, 12, 30)) == (1, 1)
def test_the_detection_rate_is_a_proportion_among_biopsies_and_not_the_confirmation_of_suspicious_mammograms(base, manifest):
"""Pins down: the rate and the confirmation proportion answer different questions over the same data. In the semester 2 the
rate counts 6 biopsy reports with a result; the confirmation counts mammograms of suspicion with a biopsy (its denominator
is mammograms, not reports). Fails if the two measures end up with the same counts."""
confirmacion = "cama/CAMA_CONFIRMACION_BIRADS45"
r = answer("cama", measure_definitions(manifest)[confirmacion], Question(confirmacion, "2025-S2"), **repositories(base))
assert (r.numerator, r.denominator) != (4, 6)
assert r.denominator >= 15, "its denominator is the mammograms of suspicion of the period"
def test_the_detection_flags_of_the_view_follow_the_parameters(base):
"""Pins down: the view's flags are the grade lists of dbt's vars, which a test keeps equal to the parameter table's: known
result = the catalog's grades, malignant = `cama.biopsia_cancer`. Fails if the two copies drift apart."""
import tomllib
reglas = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
with base.motor.connect() as c:
flags = {(g, k, m) for g, k, m in c.execute(text("select distinct grado, con_resultado, maligno from cama_deteccion_biopsia"))}
cancer = set(reglas["cama"]["biopsia_cancer"]["valor"])
catalogo = {x["clave"] for x in reglas["cama"]["catalogos"]["biopsia"]["valor"]}
assert flags == {(g, int(g in catalogo), int(g in cancer)) for g in {f[0] for f in flags}}
assert {None, "BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"} == {f[0] for f in flags}
assert (None, 0, 0) in flags
# --- the time from the result to the diagnosis -------------------------------------------------------------------------
def test_the_time_from_result_to_diagnosis_counts_from_the_report_to_the_first_note_on_or_after_it(base, manifest):
"""Pins down, in the semester 2 (16 mammograms with a report, P03's left out by her earlier breast cancer note): five have a
diagnosing note within the horizon: P01 12 days, P07 and P12 the same day (0), P08 37 (her 12-05 note is before her report
and doesn't count) and P20 39; the other eleven are excluded and counted (P09's note is 193 days after, P04's is of a
specialty that doesn't diagnose, the rest have none). Median 12. Fails if a note before the report is used, the horizon
isn't applied, a non-diagnosing specialty counts or an excluded mammogram isn't counted."""
r = duracion(base, manifest, "2025-S2")
assert (r.initial, r.n, r.excluded, r.median) == (16, 5, 11, 12.0)
def test_the_event_cutoff_leaves_out_the_notes_after_it_and_does_not_measure_what_is_still_inside_the_horizon(base, manifest):
"""Pins down, at 2025-12-31: the notes of 2026 don't exist yet (P08's and P20's) and every mammogram of the semester is
still inside its horizon (180 days from its report), so those without a note are neither measured nor excluded: three
observations (0, 0 and 12 days, median 0) are the whole population. The same rule as the mammogram-to-result measure: a
mammogram is excluded only once its horizon has passed without a note. Fails if a note after the cut-off is measured or if
a mammogram that can still get its note is counted as excluded."""
r = duracion(base, manifest, "2025-S2", CORTE)
assert (r.initial, r.n, r.excluded, r.median) == (3, 3, 0, 0.0)
# Once every horizon of the semester has passed (the last report is 2025-12-27) the unmeasured are excluded and counted.
tarde = duracion(base, manifest, "2025-S2", D(2026, 7, 1))
assert (tarde.initial, tarde.n, tarde.excluded) == (16, 5, 11)
def test_the_result_to_diagnosis_days_are_the_mammogram_to_diagnosis_days_minus_the_days_to_the_report(base):
"""Pins down: for a mammogram whose first note is on or after its report, the days from the report equal the days of the
mammogram-to-diagnosis measure minus the days from the mammogram to its report (the same note, another origin): P01 19-7,
P07 7-7, P12 7-7. P08 is the difference by design (that measure takes her 12-05 note, this one her 01-15 note). Fails if the
two measures read different notes where they should read the same."""
with base.motor.connect() as c:
nuevo = {h: d for h, d in c.execute(text(
"select p.pac_id_hospital, r.dias_reporte_diagnostico from cama_resultado_diagnostico r join paciente p on p.pac_id = r.pac_id"))}
viejo = {h: (d, t) for h, d, t in c.execute(text(
"select p.pac_id_hospital, m.dias_toma_diagnostico, m.dias_toma_reporte from cama_tomas_mastografia m "
"join paciente p on p.pac_id = m.pac_id"))}
for h in ("P01", "P07", "P12"):
assert nuevo[h] == viejo[h][0] - viejo[h][1], h
assert (nuevo["P08"], viejo["P08"][0]) == (37, 3)
def test_a_mammogram_without_a_report_is_not_in_the_population_and_the_report_date_gives_the_period(base):
"""Pins down: the model holds one row per mammogram with a report, dated by it: all 24 mammograms of the fixture have one,
and P16's second (reported 2026-01-05) is dated 2026, outside the semester of its mammogram. Fails if the period is read from
the date of the mammogram."""
with base.motor.connect() as c:
filas = c.execute(text("select p.pac_id_hospital, r.fecha_toma, r.fecha_reporte from cama_resultado_diagnostico r "
"join paciente p on p.pac_id = r.pac_id where p.pac_id_hospital = 'P16' order by 2")).all()
assert [tuple(map(str, f[1:])) for f in filas] == [("2025-05-01", "2025-05-08"), ("2025-12-20", "2026-01-05")]
# --- the histopathological result by BI-RADS ---------------------------------------------------------------------------
def test_the_matrix_of_the_semester_2_at_the_cutoff(base, manifest):
"""Pins down, at 2025-12-31, one patient through her most severe mammogram of the semester: BI-RADS 5 (P01 invasive, P02
without biopsy because hers is reported in 2026, P03 and P17 without biopsy, P04 benign, P05 a biopsy without grade, P06 in
situ from her two biopsies, P20 in situ reported that same day), 4A (P07-P11 without biopsy), 6 (P12) and 4 without subcategory
(P14). P15's semester-2 mammogram is a 2 and P16's 5 is reported in 2026: neither enters. P19 (a semester-1 mammogram) is out.
Fails if the chosen mammogram, the biopsy of it, the cut-off or the grouping change."""
r = composicion(base, manifest, "2025-S2", CORTE)
assert matriz(r) == {
("B5", "CARCINOMA_INVASOR"): 1, ("B5", "CARCINOMA_IN_SITU"): 2, ("B5", "BENIGNO"): 1, ("B5", "SIN_DATO"): 1, ("B5", "SIN_BIOPSIA"): 3,
("B4A", "SIN_BIOPSIA"): 5, ("B6", "SIN_BIOPSIA"): 1, ("B4", "SIN_BIOPSIA"): 1,
}
assert sum(r.categories.values()) == 15
def test_without_a_cutoff_the_biopsy_reported_later_and_the_late_report_count(base, manifest):
"""Pins down: with no event cut-off P02's biopsy (reported 2026-01-10, in situ) is hers and P16's BI-RADS 5 (reported
2026-01-05) is her semester's: one more in situ, and one more without biopsy. Fails if a cut-off is applied by default."""
r = composicion(base, manifest, "2025-S2")
assert matriz(r)[("B5", "CARCINOMA_IN_SITU")] == 3 and matriz(r)[("B5", "SIN_BIOPSIA")] == 3
assert sum(r.categories.values()) == 16
def test_the_semester_1_matrix_holds_each_patient_once(base, manifest):
"""Pins down: P13 (BI-RADS 6, no biopsy), P15 (BI-RADS 5 of June, no biopsy), P18 (4A with her benign report of 06-30) and P19
(BI-RADS 5 with her invasive report of 07-01, in the next semester: the biopsy belongs to her mammogram, not to the period of
its report); P16's BI-RADS 1 is not admitted. Fails if a biopsy reported in the next period is lost."""
r = composicion(base, manifest, "2025-S1", CORTE)
assert matriz(r) == {("B6", "SIN_BIOPSIA"): 1, ("B5", "SIN_BIOPSIA"): 1, ("B4A", "BENIGNO"): 1, ("B5", "CARCINOMA_INVASOR"): 1}
@pytest.mark.parametrize("periodo", ["2025-S1", "2025-S2", "2025-06", "2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"])
def test_the_matrix_counts_the_same_patients_as_the_birads_measure_in_every_period(base, manifest, periodo):
"""Pins down: each period's BI-RADS strata equal the patients per category of CAMA_BIRADS456_PACIENTE (same rule: her most
severe mammogram of the period), so Resumen's two cards never count different patients. Fails if the two measures choose
other mammograms."""
histo = composicion(base, manifest, periodo, CORTE)
birads = composicion(base, manifest, periodo, CORTE, url=BIRADS_PACIENTE)
por_birads = {b: sum(cs.values()) for b, cs in histo.strata["birads"].items()}
assert por_birads == {b: n for b, n in birads.categories.items() if n}
assert sum(histo.categories.values()) == sum(birads.categories.values())
def test_a_knowledge_cutoff_later_the_same_day_still_sees_the_biopsies(base, manifest):
"""Pins down the datetime compare of the biopsy's knowledge date: with a knowledge cut-off one second after the last load (the
same day as the loads) every biopsy is known, as with none; with one before the first load nothing is. Fails if the biopsy's
date is compared as text against the cut-off (`...T...` against `... ...`), which hid every biopsy on the day of the load."""
with base.motor.connect() as c:
ultima = c.execute(text("select max(inicio) from carga")).scalar()
primera = c.execute(text("select min(inicio) from carga")).scalar()
ultima = datetime.fromisoformat(str(ultima)).replace(tzinfo=timezone.utc) if isinstance(ultima, str) else ultima.replace(tzinfo=timezone.utc)
primera = datetime.fromisoformat(str(primera)).replace(tzinfo=timezone.utc) if isinstance(primera, str) else primera.replace(tzinfo=timezone.utc)
sin = composicion(base, manifest, "2025-S2", CORTE)
con = composicion(base, manifest, "2025-S2", CORTE, ultima + timedelta(seconds=1))
assert matriz(con) == matriz(sin)
antes = composicion(base, manifest, "2025-S2", CORTE, primera - timedelta(days=1))
assert antes.categories == {}
def test_the_report_publishes_the_cross_of_birads_and_result_as_two_components(base, manifest):
"""Pins down the FHIR report of the matrix: a stratifier coded by BI-RADS and by the biopsy grade whose strata carry the two
components and the patients of each cell; the categories stratifier keeps the totals. Fails if the cross is published as
marginals (the page couldn't rebuild the matrix) or a cell's count is not the matrix's."""
definicion = composition_definitions(manifest)[HISTO]
periodo = base.dominio.dim_periodo_repository.get("2025-S2")
resultado = composicion(base, manifest, "2025-S2", CORTE)
informe = measure_report(definicion, Question(HISTO, "2025-S2", CORTE), resultado, periodo, datetime.now(timezone.utc))
grupo = informe["group"][0]
assert [[c["coding"][0]["code"] for c in s["code"]] for s in grupo["stratifier"]] == [["biopsia_grado"], ["birads", "biopsia_grado"]]
celdas = {tuple(c["value"]["coding"][0]["code"] for c in s["component"]): s["population"][0]["count"]
for s in grupo["stratifier"][1]["stratum"]}
assert celdas == matriz(resultado)
assert sum(celdas.values()) == grupo["population"][0]["count"] == 15