Merge pull request 'CaCu follow-up: CASO status with CIS, per-status probabilities, and a cycle that estimates with every production scenario' (#19) from integration/cacu-197-conciliacion into dev

Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/19
This commit was merged in pull request #19.
This commit is contained in:
2026-11-22 23:25:34 -06:00
12 changed files with 306 additions and 80 deletions
+2
View File
@@ -27,6 +27,7 @@ etiqueta = "Estatus de seguimiento"
expression = "cacu.seguimiento:estrato"
unidad = "paciente"
valores = [
{ valor = "CASO", etiqueta = "Caso (cáncer)" },
{ valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" },
{ valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" },
{ valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" },
@@ -37,6 +38,7 @@ valores = [
seguimiento_marco = "cacu.seguimiento.marco"
seguimiento_referencia = "cacu.seguimiento.referencia"
seguimiento_precedencia = "cacu.seguimiento.precedencia"
seguimiento_grados_caso = "cacu.seguimiento.caso.grados"
seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias"
seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito"
seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito"
+75 -3
View File
@@ -5,7 +5,9 @@ vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada pacient
estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su
grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
de CACU_DIAS_TOMA_DIAGNOSTICO), su última biopsia reportada al corte y su probabilidad vigente de LIEAG+ y de
cáncer en cada horizonte (los lotes confirmados que muestra su ficha). `orden` la ordena por la más reciente o por
una de esas probabilidades a `horizonte`. `prioridad` está reservada y va nula.
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
@@ -26,7 +28,7 @@ from types import SimpleNamespace
from sqlalchemy import func, select
from sqlmodel import Session
from webapi.follow_up.silver import citologias, notas
from webapi.follow_up.silver import biopsias, citologias, notas
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
from webapi.orchestration.tables.cacu import TABLAS
from webapi.follow_up.view import P
@@ -73,6 +75,12 @@ PARAMETROS_DE_LA_LISTA = {
"horizonte_dias": "cacu.horizontes.toma_diagnostico_dias",
}
ESTRATO = "estatus_seguimiento"
# How the list can be ordered: by its most recent study (the default), or by the probability, at `horizonte`, of
# LIEAG+ (CIN2+, the models whose outcome starts with `cin2`), of cancer or of surviving (a case's), highest first.
ORDENES = ("reciente", "lieag", "cancer", "supervivencia")
HORIZONTE_POR_OMISION = 5.0
# The outcomes other than CIN2+ the list shows, by their key in `probabilidades`.
DESENLACES = {"cancer": "cancer", "muerte": "supervivencia"}
class PedidoInvalido(ValueError):
@@ -89,6 +97,8 @@ def seguimiento_de(
corte: date | None = None,
meses: int | None = None,
estatus: str | None = None,
orden: str = "reciente",
horizonte: float | None = None,
page: int = 1,
page_size: int = 50,
hoy: date | None = None,
@@ -113,6 +123,8 @@ def seguimiento_de(
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
if estatus is not None and estatus not in ESTATUS:
raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.")
if orden not in ORDENES:
raise PedidoInvalido(f"orden desconocido {orden!r}; hay {list(ORDENES)}.")
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
@@ -122,6 +134,13 @@ def seguimiento_de(
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
if estatus is not None:
items = [i for i in items if i["estatus"]["codigo"] == estatus]
horizontes = sorted({h["horizonte_anios"] for i in items for p in (i["probabilidades"] or {}).values() for h in p})
horizonte = HORIZONTE_POR_OMISION if horizonte is None else float(horizonte)
if horizontes and horizonte not in horizontes:
raise PedidoInvalido(f"horizonte = {horizonte:g}: los modelos dan {[f'{h:g}' for h in horizontes]} años.")
if orden != "reciente":
# highest first, patients the model doesn't score last; the sort is stable, so ties stay most recent first
items.sort(key=lambda i: (p := _probabilidad(i, orden, horizonte)) is None or -p)
total = len(items)
paginas = -(-total // page_size)
@@ -132,7 +151,8 @@ def seguimiento_de(
"simulado": True,
"corte": corte.isoformat(),
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
"filtros": {"estatus": estatus},
"filtros": {"estatus": estatus, "orden": orden, "horizonte": horizonte},
"horizontes_disponibles": horizontes,
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
@@ -176,6 +196,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
if "vph" in lista["estudios"] and e["vph"] is not None:
de_la_paciente["vph"].append(e)
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
biopsia_de = _ultima_biopsia(sesion, corte, tablas)
riesgos = _probabilidades_por_paciente()
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
notas_de = _notas_por_paciente(sesion, corte)
items = []
@@ -199,6 +221,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
"genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]),
},
"dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista),
"ultima_biopsia": biopsia_de.get(pac_id),
"probabilidades": {k: v[pac_id] for k, v in riesgos.items() if pac_id in v} or None,
"prioridad": None,
"_orden": mas_reciente,
})
@@ -207,6 +231,54 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
return items
def _ultima_biopsia(sesion: Session, corte: date, tablas: TablasKit) -> dict[int, dict]:
"""Each patient's latest biopsy reported by the cut-off: its report date and grade (`GradoCIN`)."""
b = biopsias(tablas)
filas = sesion.execute(select(b.c.pac_id, b.c.fecha_reporte, b.c.grado).where(b.c.fecha_reporte.is_not(None))).all()
found: dict[int, dict] = {}
for pac_id, fecha, grado in filas:
fecha = _fecha(fecha)
if fecha <= corte and (pac_id not in found or fecha > date.fromisoformat(found[pac_id]["fecha"])):
found[pac_id] = {"fecha": fecha.isoformat(), "grado": grado}
return found
def _probabilidades_por_paciente() -> dict[str, dict[int, list[dict]]]:
"""Each patient's current probability of LIEAG+ (`lieag`, the outcomes `cin2*`), of cancer (`cancer`) and of
surviving (`supervivencia`, the complement of the survival model's death) at every horizon, with its interval: the
confirmed batches the patient's record shows (`current_risks_by_patient`)."""
from persistance import cacu
found: dict[str, dict[int, list[dict]]] = {}
for desenlace, por_paciente in cacu.cohort_repository.current_risks_by_patient().items():
clave = "lieag" if (desenlace or "").startswith("cin2") else DESENLACES.get(desenlace)
if clave is None:
continue
destino = found.setdefault(clave, {})
for pac_id, horizontes in por_paciente.items():
filas = [_horizonte(h, complemento=clave == "supervivencia") for h in horizontes]
if clave == "supervivencia" and filas and not any(f["horizonte_anios"] == 0 for f in filas):
# at the index date every patient is alive
filas.insert(0, {"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0})
destino.setdefault(pac_id, filas)
return found
def _horizonte(h, *, complemento: bool) -> dict:
"""A horizon's probability and interval; with `complemento`, of not having the outcome (surviving a death)."""
if not complemento:
return {"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
"ic_alto": h.ic_alto}
return {"horizonte_anios": h.horizonte_anios, "probabilidad": 1 - h.probabilidad,
"ic_bajo": None if h.ic_alto is None else 1 - h.ic_alto,
"ic_alto": None if h.ic_bajo is None else 1 - h.ic_bajo}
def _probabilidad(item: dict, clave: str, horizonte: float) -> float | None:
return next((h["probabilidad"] for h in ((item["probabilidades"] or {}).get(clave) or [])
if h["horizonte_anios"] == horizonte), None)
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
c = citologias()
+7
View File
@@ -66,4 +66,11 @@ def _requested(args) -> dict:
pedido[nombre] = int(texto)
if estatus := args.get("estatus"):
pedido["estatus"] = estatus
if orden := args.get("orden"):
pedido["orden"] = orden
if (horizonte := args.get("horizonte")) not in (None, ""):
try:
pedido["horizonte"] = float(horizonte)
except ValueError:
raise ValueError(f"horizonte debe ser un número de años; llegó {horizonte!r}") from None
return pedido
+14 -3
View File
@@ -6,6 +6,8 @@ reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las
fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo
pasado no cambia cuando la paciente avanza.
CASO una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` (CIS o carcinoma): la
paciente ya tiene cáncer, y lo que se sigue es su supervivencia
POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia
POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si
es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de
@@ -38,7 +40,7 @@ from webapi.follow_up.functions import dias_entre
from webapi.follow_up.view import P, vista
from webapi.orchestration.tables import TablasKit
ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
ESTATUS = ("CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3)
MARCOS = ("estatus", "ronda")
REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte
@@ -81,7 +83,7 @@ def reglas_de(valores: Mapping) -> Reglas:
precedencia = tuple(valores["seguimiento_precedencia"])
if sorted(precedencia) != sorted(ESTATUS):
raise ReglaDesconocida(
f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; "
f"cacu.seguimiento.precedencia debe ordenar los {len(ESTATUS)} estatus, sin repetir: {ESTATUS}; "
f"llegó {precedencia}."
)
exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS)
@@ -186,6 +188,13 @@ def estatus_al(
.group_by(evidencias.c.pac_id)
.cte("seguimiento_colposcopia")
)
# Un caso: una biopsia reportada antes de la referencia con un grado de cáncer.
caso = (
select(reporte.c.pac_id)
.distinct()
.where(antes(reporte.c.fecha_reporte), reporte.c.grado.in_(P("seguimiento_grados_caso", lista=True)))
.cte("seguimiento_caso")
)
tratamiento = (
select(nota.c.pac_id)
.distinct()
@@ -210,6 +219,7 @@ def estatus_al(
)
persona = V_PERSONA
cumple = {
"CASO": caso.c.pac_id.is_not(None),
"POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None),
"POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None),
"INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente),
@@ -219,7 +229,8 @@ def estatus_al(
return (
select(persona.c.pac_id, estatus.label("estatus"))
.select_from(
persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
persona.outerjoin(caso, caso.c.pac_id == persona.c.pac_id)
.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
.outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id)
.outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id)
)
+3
View File
@@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import (
Catalog,
CatalogValue,
FlexDate,
PostalCode,
RequiredDate,
RequiredHospitalId,
@@ -25,6 +26,8 @@ class PacienteImportSchema(ImportSchema):
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
# IND-01: required, since age at each event of interest is derived from it.
pac_fecha_nacimiento: RequiredDate
# Survival's outcome; empty while she is alive or the date is unknown.
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
+12 -11
View File
@@ -224,20 +224,20 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
@config.when(with_cohorts=True)
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[tuple[int, bool]]]:
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da a cada estimador de la cohorte
(`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los
riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no
duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. Confirmar o anular un lote es la orden
`confirm-risks`, no este paso.
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
estimadores = ctx.estimators.get(url) or []
if not estimadores:
continue
def frame(sesion, url=url):
@@ -247,8 +247,9 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
if armado_id is None:
continue
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
lotes[url] = []
for estimador in estimadores:
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[url].append(ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos))
return lotes
+11 -38
View File
@@ -1,5 +1,5 @@
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
its domain has in production.
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with every model version
of its domain in production, one batch per model.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
@@ -11,7 +11,6 @@ unused by design.
from dataclasses import dataclass
from importlib import import_module
from typing import Any
@dataclass(frozen=True)
@@ -61,45 +60,19 @@ class ScenarioEstimator:
return self._provenance
class Cin2LogisticEstimator(ScenarioEstimator):
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`)."""
def __init__(self, domain: str = "cacu", version: str | None = None):
super().__init__(domain, "cin2_logistic", version)
self.desenlace = "cin2_mas"
# The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production
# scores the cohort it names.
LIVE_SCENARIOS = {"cama": ("survival",)}
def _scenario_estimators(domain: str) -> dict[str, Any]:
def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
"""The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the
registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario
definition in `models` is skipped. Empty where none is in production, the same as no estimator being
configured: `estimate` then does nothing."""
from models.dags.training import Scenario
from models.io.registry import registry
found = {}
for name in LIVE_SCENARIOS.get(domain, ()):
scenario = Scenario.load(domain, name)
found: dict[str, list[ScenarioEstimator]] = {}
for name in registry.in_production(domain):
try:
registry.resolve(domain, name)
scenario = Scenario.load(domain, name)
except LookupError:
continue
found[scenario.cohort] = ScenarioEstimator(domain, name)
found.setdefault(scenario.cohort, []).append(ScenarioEstimator(domain, name))
return found
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return _scenario_estimators(domain)
from models.dags.training import Scenario
from models.io.registry import registry
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {scenario.cohort: Cin2LogisticEstimator(domain)}
+10 -3
View File
@@ -203,13 +203,20 @@ estado = "provisional"
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo"
[cacu.seguimiento.precedencia]
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir).
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de "CASO",
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cinco, sin repetir).
# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo).
valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
valor = ["CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
estado = "provisional"
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
[cacu.seguimiento.caso.grados]
# Qué grados de biopsia hacen de la paciente un caso (ya tiene cáncer, invasor o in situ): su estatus es CASO, gane lo
# que gane lo demás, y lo que se le sigue es la supervivencia. Opciones: grados de `GradoCIN`.
valor = ["CIS", "CARCINOMA"]
estado = "provisional"
fuente = "Responsable del proyecto, 2026-11-22: un escenario para las pacientes que ya tienen cáncer, sobre el que se evalúa la supervivencia; falta que clínica la confirme"
[cacu.seguimiento.colposcopia.evidencias]
# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto):
# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos`