CaMa: two clinical scenarios, post-treatment and under observation, with the follow-up list's scenario column and filter

This commit is contained in:
rockdrigo
2026-11-21 01:55:04 -06:00
parent d1e06798c9
commit 9b617db9d0
5 changed files with 103 additions and 59 deletions
+55 -4
View File
@@ -8,6 +8,7 @@ invented patients with the cases below; their names (`P01`...) are the source id
Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6):
BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day.
P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it.
No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some.
"""
import json
@@ -151,14 +152,16 @@ def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app):
"""Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data
doesn't support is added, or the hospital's identifier leaks."""
date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body.
Fails if a column the data doesn't support is added, or the hospital's identifier leaks."""
respuesta = get(app, page_size=200)
cuerpo = respuesta.get_json()
assert cuerpo["simulado"] is True
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"])
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
"escenario_clinico"} for i in cuerpo["items"])
assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"}
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"]
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
assert respuesta.headers["Cache-Control"] == "no-store"
@@ -368,3 +371,51 @@ def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_
with Session(base.motor) as sesion:
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")]
@pytest.fixture
def con_postratamiento(tmp_path):
"""The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on
2025-11-01 and P06 on 2026-01-15, after the cut-off."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
from sqlalchemy import text
base = base_de("cama", tmp_path, datos=insertar)
base.run(*UNTIL_MODELS, allow_undecided=True)
hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"}
with base.motor.begin() as c:
for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"):
try:
with c.begin_nested():
c.execute(text(drop))
except Exception:
pass
c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)"))
for hospital, fecha in hechos.items():
c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente "
"where pac_id_hospital = :h"), {"f": fecha, "h": hospital})
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
yield base, flask.test_client()
base.motor.dispose()
def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento):
"""Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the
cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it
and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from
something other than the timeline, or if the filter stops being offered."""
base, app = con_postratamiento
nombres = hospital_de(base)
escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"]
for i in get(app, corte=corte, page_size=200).get_json()["items"]}
al_corte = escenario(CORTE)
assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"}
assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"}
assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO"
filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200)
assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"}
filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico")
assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"},
{"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}]
+19 -49
View File
@@ -1,7 +1,7 @@
"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`,
rules in `cama.escenarios`) and carried by her timeline with the evidence that started it and its level: screening from
her first mammogram before a diagnosis, control from a note with a malignant breast tumour ICD-10, post-treatment from
a discharge note after that diagnosis.
rules in `cama.escenarios`): post-treatment from a discharge note after a malignant breast tumour's diagnosis, carried by
her timeline as an `escenario_postratamiento` fact with the evidence that started it; every other patient is under
observation ("en observación"), which has no fact.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30,
@@ -35,16 +35,15 @@ def base(tmp_path, manifest):
base.motor.dispose()
def scenarios(base) -> dict[str, set[tuple[str, date, str, int]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence, level)."""
def scenarios(base) -> dict[str, set[tuple[str, date, str]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence)."""
with base.motor.connect() as con:
rows = con.execute(text(
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo, l.valor_numerico from cama_linea_de_tiempo l "
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l "
"join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all()
found: dict[str, set[tuple[str, date, str, int]]] = {}
found: dict[str, set[tuple[str, date, str]]] = {}
for r in rows:
found.setdefault(r.pac_id_hospital, set()).add(
(r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo, int(r.valor_numerico)))
found.setdefault(r.pac_id_hospital, set()).add((r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo))
return found
@@ -58,51 +57,22 @@ def discharge(base, hospital_id: str) -> None:
"where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id})
def test_each_patient_s_scenario_follows_the_hierarchy(base):
"""Pins down: a first mammogram starts screening only before a diagnosis; a dated C50 note, whoever wrote it, starts
control; an invasive biopsy alone doesn't (control asks for the ICD-10); an in situ carcinoma (D05) and a note
without a date start nothing; with no discharge note nobody is in post-treatment. Fails if `cama.escenarios`
changes an evidence list or a code, or screening stops ending at the diagnosis."""
assert scenarios(base) == {
"H-001": {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1)},
"H-003": {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1),
("escenario_control", date(2025, 8, 4), "cie", 2)},
"H-101": {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)},
"H-102": {("escenario_tamizaje", date(2025, 2, 20), "mastografia", 1),
("escenario_control", date(2025, 9, 30), "cie", 2)},
"H-103": {("escenario_tamizaje", date(2025, 7, 1), "mastografia", 1),
("escenario_control", date(2025, 7, 20), "cie", 2)},
"H-104": {("escenario_tamizaje", date(2025, 11, 11), "mastografia", 1)},
}
def test_without_a_discharge_every_patient_is_under_observation(base):
"""Pins down: a mammogram, a malignant ICD-10 note (H-003, H-102, H-103) or an invasive biopsy (H-003) alone start
no scenario: with no discharge note nobody is in post-treatment and the timeline has no scenario fact, which reads as
under observation. Fails if screening or a diagnosis go back to being scenarios of their own."""
assert scenarios(base) == {}
def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base):
"""Pins down: a discharge note that carries a malignant tumour's ICD-10 starts post-treatment at its date, at level 3,
above the control the same note starts. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops
reading the note's type."""
"""Pins down: a discharge note that carries a malignant tumour's ICD-10 puts H-003 in post-treatment from its date,
and only her. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops reading the note's type."""
discharge(base, "H-003")
assert scenarios(base)["H-003"] == {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1),
("escenario_control", date(2025, 8, 4), "cie", 2),
("escenario_postratamiento", date(2025, 8, 4), "egreso", 3)}
assert scenarios(base) == {"H-003": {("escenario_postratamiento", date(2025, 8, 4), "egreso")}}
def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base):
"""Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her in
screening: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it."""
"""Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her
under observation: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it."""
discharge(base, "H-101")
assert scenarios(base)["H-101"] == {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)}
def test_a_diagnosis_after_screening_keeps_both_levels(base):
"""Pins down: a patient in screening whose malignant diagnosis comes later keeps both facts, so her timeline reads the
step from screening to control, the event that validates the screening models. Fails if a later diagnosis erases
the screening that preceded it."""
with base.motor.begin() as con:
con.execute(text(
"update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and "
"pac_id = (select pac_id from paciente where pac_id_hospital = 'H-001')"))
con.execute(text(
"update procedimiento set fecha = '2025-06-01' where estudio_id = 'nota_medica' and pac_id = "
"(select pac_id from paciente where pac_id_hospital = 'H-001')"))
assert scenarios(base)["H-001"] == {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1),
("escenario_control", date(2025, 6, 1), "cie", 2)}
assert scenarios(base) == {}