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) == {}
+21 -3
View File
@@ -6,12 +6,14 @@ date taken, then the greatest source id, then the latest report date, then the g
always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one
(`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy
shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to.
Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on
or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise.
Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off.
"""
from dataclasses import dataclass
from datetime import date
from datetime import date, timedelta
from sqlalchemy import Date, Integer, String, column, func, inspect, select, table
from sqlmodel import Session
@@ -25,6 +27,8 @@ ESCENARIO = "diagnostico"
VERSION = "0.1.0"
SIN_DATO = "SIN_DATO"
SIN_BIOPSIA = "SIN_BIOPSIA"
POST_TRATAMIENTO = "POST_TRATAMIENTO"
EN_OBSERVACION = "EN_OBSERVACION"
# Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest.
GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
@@ -35,14 +39,17 @@ CANDIDATOS = table(
column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String),
column("biopsia_fecha_reporte", Date), column("biopsia_grado", String),
)
LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date))
class CohorteNoDisponible(RuntimeError):
"""The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503)."""
"""The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't
run (503)."""
def disponible(sesion: Session) -> bool:
return inspect(sesion.get_bind()).has_table(CANDIDATOS.name)
inspector = inspect(sesion.get_bind())
return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO))
@dataclass(frozen=True)
@@ -58,6 +65,7 @@ class Fila:
# The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`).
primera_biopsia_fecha: date | None = None
primer_maligno_fecha: date | None = None
escenario_clinico: str = EN_OBSERVACION
@property
def resultado(self) -> str:
@@ -93,8 +101,17 @@ def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
return SIN_DATO
def en_postratamiento(sesion: Session, corte: date) -> set[int]:
"""The patients whose timeline puts them in post-treatment on or before `corte`."""
linea = LINEA_DE_TIEMPO.c
# Before the next day, so a date stored with a time still counts on its own day.
return set(sesion.execute(select(linea.pac_id).distinct().where(
linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars())
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
postratamiento = en_postratamiento(sesion, corte)
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS)
@@ -133,6 +150,7 @@ def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None,
primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None),
primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None),
escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION,
))
return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id))
+7 -2
View File
@@ -14,7 +14,7 @@ from datetime import date, timedelta
from sqlmodel import Session
from webapi.cama_follow_up.cohort import (
COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
COHORTE, EN_OBSERVACION, ESCENARIO, POST_TRATAMIENTO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
disponible, grupos_de_edad,
)
from webapi.orchestration.reference.rules import valor_de
@@ -25,11 +25,13 @@ VENTANA_POR_OMISION = 3
PAGINA_MAXIMA = 200
EXPORTACION_MAXIMA = 5000
GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"}
ESCENARIOS_CLINICOS = {POST_TRATAMIENTO: "Post-tratamiento", EN_OBSERVACION: "En observación"}
COLUMNAS = [
{"clave": "pac_id", "etiqueta": "Identificador de paciente"},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad"},
{"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]},
{"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico"},
]
@@ -80,6 +82,8 @@ def filtros_disponibles(sesion: Session) -> list[dict]:
*({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()),
{"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"},
{"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico", "opciones": [
{"codigo": c, "etiqueta": e} for c, e in ESCENARIOS_CLINICOS.items()]},
]
@@ -114,7 +118,8 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict)
def _item(f: Fila) -> dict:
return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads,
"mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia,
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None}
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None,
"escenario_clinico": f.escenario_clinico}
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
+1 -1
View File
@@ -15,7 +15,7 @@ from webapi.cama_follow_up.listing import (
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia")
FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")