CaMa: the follow-up row carries a provisional status, priority and mammogram-to-diagnosis days; the survival menu names the patient's own scenarios

This commit is contained in:
Roberto Treviño Cervantes
2026-11-22 21:38:43 -06:00
parent 88c9694a46
commit f7f8af8b4c
4 changed files with 62 additions and 9 deletions
+28 -3
View File
@@ -152,13 +152,14 @@ 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): 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 """Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body. date, the clinical scenario, the provisional status and priority of her pathway and the days from the mammogram to
Fails if a column the data doesn't support is added, or the hospital's identifier leaks.""" the diagnosis: no pseudonym, and no source id anywhere in the body. Fails if a field is added or dropped, or the
hospital's identifier leaks."""
respuesta = get(app, page_size=200) respuesta = get(app, page_size=200)
cuerpo = respuesta.get_json() cuerpo = respuesta.get_json()
assert cuerpo["simulado"] is True assert cuerpo["simulado"] is True
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha", assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
"escenario_clinico"} for i in cuerpo["items"]) "escenario_clinico", "estatus", "prioridad", "dias_mastografia_diagnostico"} for i in cuerpo["items"])
assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"} 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 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", "escenario_clinico"] assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
@@ -419,3 +420,27 @@ def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observa
filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico") 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"}, assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"},
{"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}] {"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}]
def test_the_status_priority_and_days_follow_her_pathway():
"""Pins down: a BI-RADS 5 with no biopsy is pending and high priority, a BI-RADS 4A with no biopsy is medium, a benign
biopsy is low, a cancer without treatment is high with the days from the mammogram to its first malignant report, and
one in treatment is low. Fails if a rule changes or the days stop counting from the mammogram."""
from webapi.cama_follow_up.cohort import EN_OBSERVACION, POST_TRATAMIENTO, Fila
from webapi.cama_follow_up.listing import _item
toma = date(2026, 11, 1)
fila = lambda **k: Fila(pac_id=1, mastografia_fecha=toma, grupo_edad="50-59", **{"biopsia": None, "biopsia_fecha": None, **k})
cancer = dict(biopsia="CARCINOMA_INVASOR", biopsia_fecha=date(2026, 11, 21), primer_maligno_fecha=date(2026, 11, 21))
pendiente_alta = _item(fila(birads="BIRADS_5"))
pendiente_media = _item(fila(birads="BIRADS_4A"))
benigna = _item(fila(birads="BIRADS_4A", biopsia="BENIGNO", biopsia_fecha=date(2026, 11, 10)))
sin_tratamiento = _item(fila(birads="BIRADS_6", **cancer, escenario_clinico=EN_OBSERVACION))
en_tratamiento = _item(fila(birads="BIRADS_6", **cancer, escenario_clinico=POST_TRATAMIENTO))
assert (pendiente_alta["estatus"], pendiente_alta["prioridad"]) == ("Pendiente de biopsia", "Alta")
assert pendiente_media["prioridad"] == "Media" and pendiente_media["dias_mastografia_diagnostico"] is None
assert (benigna["estatus"], benigna["prioridad"]) == ("Biopsia benigna", "Baja")
assert (sin_tratamiento["prioridad"], sin_tratamiento["dias_mastografia_diagnostico"]) == ("Alta", 20)
assert (en_tratamiento["estatus"], en_tratamiento["prioridad"]) == ("Diagnóstico confirmado, en tratamiento", "Baja")
+1
View File
@@ -121,6 +121,7 @@ def test_the_menu_offers_the_scenarios_with_a_summary_row_and_enough_patients(li
menu = live_client.get("/cama/modelo/escenarios?paciente=7").get_json() menu = live_client.get("/cama/modelo/escenarios?paciente=7").get_json()
assert menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}] and menu["predeterminado"] == "< 45 años" assert menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}] and menu["predeterminado"] == "< 45 años"
assert menu["de_la_paciente"] == [{"nombre": "< 45 años", "n": 100}]
assert menu["modelo"]["version"] == "3" assert menu["modelo"]["version"] == "3"
assert live_client.get("/cama/modelo/escenarios?paciente=500").status_code == 422 assert live_client.get("/cama/modelo/escenarios?paciente=500").status_code == 422
+24 -1
View File
@@ -115,11 +115,34 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict)
return elegidas, desde return elegidas, desde
# Provisional status and priority of a patient's diagnostic pathway, pending their clinical definition for CaMa.
ESTATUS = {"PENDIENTE_BIOPSIA": "Pendiente de biopsia", "BIOPSIA_SIN_RESULTADO": "Biopsia sin resultado",
"BIOPSIA_BENIGNA": "Biopsia benigna", "CANCER_SIN_TRATAMIENTO": "Diagnóstico confirmado, sin tratamiento registrado",
"CANCER_EN_TRATAMIENTO": "Diagnóstico confirmado, en tratamiento"}
BIRADS_ALTOS = {"BIRADS_5", "BIRADS_6"}
def _estatus(f: Fila) -> str:
if f.primer_maligno_fecha is not None:
return "CANCER_EN_TRATAMIENTO" if f.escenario_clinico == POST_TRATAMIENTO else "CANCER_SIN_TRATAMIENTO"
return {SIN_BIOPSIA: "PENDIENTE_BIOPSIA", SIN_DATO: "BIOPSIA_SIN_RESULTADO"}.get(f.resultado, "BIOPSIA_BENIGNA")
def _prioridad(f: Fila, estatus: str) -> str:
if estatus == "CANCER_SIN_TRATAMIENTO" or (estatus == "PENDIENTE_BIOPSIA" and f.birads in BIRADS_ALTOS):
return "Alta"
return "Media" if estatus in ("PENDIENTE_BIOPSIA", "BIOPSIA_SIN_RESULTADO") else "Baja"
def _item(f: Fila) -> dict: def _item(f: Fila) -> dict:
estatus = _estatus(f)
diagnostico = f.primer_maligno_fecha
return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads, return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads,
"mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia, "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} "escenario_clinico": f.escenario_clinico, "estatus": ESTATUS[estatus], "prioridad": _prioridad(f, estatus),
"dias_mastografia_diagnostico": (diagnostico - f.mastografia_fecha).days
if diagnostico and diagnostico >= f.mastografia_fecha else None}
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]: def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
+9 -5
View File
@@ -99,8 +99,9 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
@blueprint.get("/modelo/escenarios") @blueprint.get("/modelo/escenarios")
def scenarios_menu(): def scenarios_menu():
"""The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data """The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data
ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also names the one she ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also gives the ones she belongs to
belongs to first as the default. 404 while there is no version in production.""" (`de_la_paciente`, the whole cohort when she is in none) and the first of them as the default. 404 while there is no version
in production."""
from models.cama.survival import live from models.cama.survival import live
try: try:
@@ -110,15 +111,18 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
in_summary = {row["escenario"] for row in _summary(domain, scenario, version)} in_summary = {row["escenario"] for row in _summary(domain, scenario, version)}
masks = live.scenario_masks(labelled) masks = live.scenario_masks(labelled)
menu = [{"nombre": name, "n": int(mask.sum())} for name, mask in masks.items() if name in in_summary and live.answerable(labelled, mask)] menu = [{"nombre": name, "n": int(mask.sum())} for name, mask in masks.items() if name in in_summary and live.answerable(labelled, mask)]
default = menu[0]["nombre"] if menu else None default, hers = (menu[0]["nombre"] if menu else None), []
paciente = request.args.get("paciente", "") paciente = request.args.get("paciente", "")
if paciente.isdigit(): if paciente.isdigit():
try: try:
mine = live.patient_scenarios(labelled, int(paciente)) mine = live.patient_scenarios(labelled, int(paciente))
except live.QueryError as error: except live.QueryError as error:
return jsonify({"error": str(error)}), 422 return jsonify({"error": str(error)}), 422
default = next((m["nombre"] for m in menu if m["nombre"] in mine), default) hers = [m for m in menu if m["nombre"] in mine] or (
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu, "predeterminado": default}) [{"nombre": live.WHOLE, "n": len(labelled)}] if mine == [live.WHOLE] else [])
default = hers[0]["nombre"] if hers else default
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu,
"de_la_paciente": hers, "predeterminado": default})
@blueprint.post("/modelo/curvas/consulta") @blueprint.post("/modelo/curvas/consulta")
def live_curves(): def live_curves():