Follow-up list: each patient's latest biopsy and probabilities, ordered by one of them
Each row carries the patient's latest biopsy reported by the cut-off and her current probability of LIEAG+, of cancer and, for a case, of surviving (the complement of the survival model's death, interval swapped) at every horizon, from the confirmed batches her record shows. `orden` sorts the whole list, not a page, by the most recent study or by one of those probabilities at `horizonte`; `horizontes_disponibles` names the horizons the models give.
This commit is contained in:
@@ -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,50 @@ 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():
|
||||
destino.setdefault(pac_id, [_horizonte(h, complemento=clave == "supervivencia") for h in horizontes])
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user