Tests: CaMa's clinical scenarios as a hierarchy, with discharge notes starting post-treatment

This commit is contained in:
rockdrigo
2026-11-18 20:46:09 -06:00
parent ca0f02aa0c
commit 028f774400
+58 -38
View File
@@ -1,12 +1,13 @@
"""What this module covers: the group each CaMa patient's predicted risks are read in, inferred by dbt
(`cama_procedimientos_inferidos`, rules in `cama.escenarios`) and carried by her timeline with the kind of evidence
that started it: follow-up from a benign biopsy with no malignant diagnosis before, post-diagnosis from a note with a
malignant breast tumour ICD-10 or an invasive biopsy, post-treatment from a later such note by a treating specialty.
"""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.
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: H-003 an invasive biopsy (2025-07-28) and a C50.4 note by
oncological surgery (08-04); H-103 (C50.9, 07-20) and H-102 (C50.9, 09-30) one such note each; H-001 an in situ
carcinoma note (D05.1, by family medicine, 03-01) and a benign biopsy (04-05); H-104 a C50 note without a date.
(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30,
H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30),
H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a
type: the tests that need a discharge write `nota_medica.tipo_nota` themselves.
"""
import os
@@ -34,49 +35,68 @@ def base(tmp_path, manifest):
base.motor.dispose()
def scenarios(base) -> dict[str, set[tuple[str, date, str]]]:
"""Patient (hospital id) -> the group facts of her timeline, (tipo, fecha, evidence)."""
def scenarios(base) -> dict[str, set[tuple[str, date, str, int]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence, level)."""
with base.motor.connect() as con:
rows = con.execute(text(
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l "
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo, l.valor_numerico 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]]] = {}
found: dict[str, set[tuple[str, date, str, int]]] = {}
for r in rows:
found.setdefault(r.pac_id_hospital, set()).add(
(r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo))
(r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo, int(r.valor_numerico)))
return found
def test_each_patient_s_group_starts_at_its_first_evidence(base):
"""Pins down: an invasive biopsy or a dated C50 note, whoever wrote it, starts post-diagnosis; a C50 note by oncological
surgery after that diagnosis starts post-treatment, one on the diagnosis' own day doesn't (H-103, H-102); an in
situ carcinoma (D05) is no diagnosis, so H-001's benign biopsy starts her follow-up; a note without a date starts
nothing. Fails if `cama.escenarios` changes an evidence list, a grade or a code, or treatment stops requiring a
later date than the diagnosis."""
def discharge(base, hospital_id: str) -> None:
"""Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would."""
with base.motor.begin() as con:
con.execute(text(
"insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) "
"select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' "
"from procedimiento p join paciente x on x.pac_id = p.pac_id "
"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-003": {("escenario_postdiagnostico", date(2025, 7, 28), "biopsia"),
("escenario_postratamiento", date(2025, 8, 4), "nota")},
"H-103": {("escenario_postdiagnostico", date(2025, 7, 20), "cie")},
"H-102": {("escenario_postdiagnostico", date(2025, 9, 30), "cie")},
"H-001": {("escenario_seguimiento", date(2025, 4, 5), "biopsia")},
"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_a_benign_biopsy_after_a_malignant_diagnosis_starts_no_follow_up(base):
"""Pins down: a benign biopsy reported after a malignant diagnosis doesn't start a follow-up, and a C50 note by a
specialty that doesn't treat (family medicine) is a diagnosis, not a treatment. Fails if the follow-up rule stops
looking at earlier diagnoses or `tratamiento_especialidades` stops filtering."""
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')"))
assert scenarios(base)["H-001"] == {("escenario_postdiagnostico", date(2025, 3, 1), "cie")}
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."""
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)}
def test_a_diagnosis_after_a_follow_up_keeps_both_groups(base):
"""Pins down: a patient in follow-up whose malignant diagnosis comes later keeps both facts, so her timeline reads
the progression: follow-up from the benign biopsy, post-diagnosis from the later note. Fails if a later diagnosis
erases the follow-up that preceded it."""
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."""
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 "
@@ -84,5 +104,5 @@ def test_a_diagnosis_after_a_follow_up_keeps_both_groups(base):
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_seguimiento", date(2025, 4, 5), "biopsia"),
("escenario_postdiagnostico", date(2025, 6, 1), "cie")}
assert scenarios(base)["H-001"] == {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1),
("escenario_control", date(2025, 6, 1), "cie", 2)}