245 lines
13 KiB
Python
245 lines
13 KiB
Python
"""The follow-up list and its file: the cohort at a cut-off, narrowed by a window and filters, in pages.
|
|
|
|
A selection of fewer patients than `comun.umbral_supresion` is never served: not as a page, not as a file, and not
|
|
through any combination of window and filters, which is what lets a small group be isolated. The whole cohort, with no
|
|
window and no filter, is the one selection that can be empty. The revision names the cohort, its version, the data it
|
|
stands on and the cut-off; a client that quotes another one is refused, so a page or a file always comes from the
|
|
cohort that was counted.
|
|
"""
|
|
|
|
import calendar
|
|
import hashlib
|
|
import json
|
|
from collections import OrderedDict
|
|
from datetime import date, timedelta
|
|
from threading import Lock
|
|
|
|
from sqlmodel import Session
|
|
|
|
from webapi.cama_follow_up.cohort import (
|
|
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
|
|
from webapi.orchestration.tables.cama import TABLAS
|
|
|
|
VENTANAS = (0, 1, 3, 6, 12)
|
|
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"},
|
|
]
|
|
|
|
|
|
class PedidoInvalido(ValueError):
|
|
"""A parameter outside what the contract admits (400)."""
|
|
|
|
|
|
class RevisionDistinta(ValueError):
|
|
"""The cohort, scenario or revision quoted is not the one the server holds (409)."""
|
|
|
|
|
|
class GrupoPequeno(ValueError):
|
|
"""The selection has too few patients to be published (403)."""
|
|
|
|
|
|
class PaginaFuera(LookupError):
|
|
"""A page past the last one, with patients (404)."""
|
|
|
|
|
|
class ExportacionGrande(ValueError):
|
|
"""More patients than a file may hold (413)."""
|
|
|
|
|
|
def _desde(corte: date, meses: int) -> date:
|
|
indice = corte.year * 12 + corte.month - 1 - meses
|
|
anio, mes = divmod(indice, 12)
|
|
if anio < 1:
|
|
raise PedidoInvalido("la ventana excede el rango de fechas admitido")
|
|
anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1]))
|
|
return anterior + timedelta(days=1)
|
|
|
|
|
|
def revision_de(construido: str, corte: date) -> str:
|
|
"""The digest of the cohort, its version, its data and the cut-off."""
|
|
return hashlib.sha256(f"{COHORTE}|{VERSION}|{construido}|{corte.isoformat()}".encode()).hexdigest()
|
|
|
|
|
|
def filtros_disponibles(sesion: Session) -> list[dict]:
|
|
"""The filters the list offers, with every value it accepts."""
|
|
edades = [*grupos_de_edad(sesion), SIN_DATO]
|
|
return [
|
|
{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [
|
|
{"codigo": codigo_birads(b), "etiqueta": "BI-RADS " + b[1:]}
|
|
for b in valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS)]},
|
|
{"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [
|
|
{"codigo": e, "etiqueta": "Sin dato" if e == SIN_DATO else e} for e in edades]},
|
|
{"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [
|
|
*({"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()]},
|
|
]
|
|
|
|
|
|
def _validar(sesion: Session, *, corte: date | None, meses: int | None, filtros: dict, hoy: date, page: int,
|
|
page_size: int) -> tuple[date, int, dict, list[dict]]:
|
|
meses = VENTANA_POR_OMISION if meses is None else meses
|
|
if meses not in VENTANAS:
|
|
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
|
|
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}.")
|
|
corte = hoy if corte is None else corte
|
|
if corte > hoy:
|
|
raise PedidoInvalido(f"corte {corte.isoformat()} es posterior a hoy ({hoy.isoformat()}).")
|
|
disponibles = filtros_disponibles(sesion)
|
|
permitidos = {f["clave"]: {o["codigo"] for o in f["opciones"]} for f in disponibles}
|
|
for clave, valor in filtros.items():
|
|
if clave not in permitidos:
|
|
raise PedidoInvalido(f"filtro desconocido {clave!r}; hay {sorted(permitidos)}.")
|
|
if valor not in permitidos[clave]:
|
|
raise PedidoInvalido(f"{clave} desconocido: {valor!r}.")
|
|
return corte, meses, {c: filtros.get(c) for c in permitidos}, disponibles
|
|
|
|
|
|
def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict) -> tuple[list[Fila], date]:
|
|
desde = min((f.mastografia_fecha for f in cohorte), default=corte) if meses == 0 else _desde(corte, meses)
|
|
elegidas = [f for f in cohorte if desde <= f.mastografia_fecha <= corte
|
|
and all(valor is None or getattr(f, "resultado" if clave == "biopsia" else clave) == valor
|
|
for clave, valor in filtros.items())]
|
|
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:
|
|
estatus = _estatus(f)
|
|
diagnostico = f.primer_maligno_fecha
|
|
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,
|
|
"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}
|
|
|
|
|
|
# The cohorts already read, by database, revision and the parameters the cohort reads: the same data and cut-off give the same
|
|
# cohort, so only a new load, another cut-off or a changed parameter reads the views again.
|
|
_COHORTES: OrderedDict = OrderedDict()
|
|
_COHORTES_LOCK = Lock()
|
|
COHORTES_EN_MEMORIA = 4
|
|
PARAMETROS_DE_LA_COHORTE = ("cama.birads_4_a_6", "cama.biopsia_cancer", "cama.grupos_edad", "cama.birads_gravedad")
|
|
|
|
|
|
def _cohorte(sesion: Session, corte: date, revision: str) -> list[Fila]:
|
|
parametros = json.dumps([valor_de(sesion, k, tablas=TABLAS) for k in PARAMETROS_DE_LA_COHORTE], default=str)
|
|
clave = (str(sesion.get_bind().url), revision, parametros)
|
|
with _COHORTES_LOCK:
|
|
if clave in _COHORTES:
|
|
_COHORTES.move_to_end(clave)
|
|
return _COHORTES[clave]
|
|
filas = cohorte_al(sesion, corte)
|
|
with _COHORTES_LOCK:
|
|
_COHORTES[clave] = filas
|
|
while len(_COHORTES) > COHORTES_EN_MEMORIA:
|
|
_COHORTES.popitem(last=False)
|
|
return filas
|
|
|
|
|
|
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
|
|
if not disponible(sesion):
|
|
raise CohorteNoDisponible("la cohorte aún no está disponible: falta correr el ciclo de indicadores de CaMa")
|
|
corte, meses, filtros, disponibles = _validar(sesion, corte=corte, meses=meses, filtros=filtros,
|
|
hoy=hoy or date.today(), page=page, page_size=page_size)
|
|
actual = revision_de(construccion(sesion), corte)
|
|
if any(contexto) and not all(contexto):
|
|
raise PedidoInvalido("el contexto de la cohorte lleva cohorte, escenario y revisión juntos.")
|
|
if any(contexto) and contexto != (COHORTE, ESCENARIO, actual):
|
|
raise RevisionDistinta("la cohorte, el escenario o la revisión no son los que sirve el servidor para este corte")
|
|
elegidas, desde = _selecciona(_cohorte(sesion, corte, actual), corte=corte, meses=meses, filtros=filtros)
|
|
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
|
|
acotada = meses != 0 or any(v is not None for v in filtros.values())
|
|
if (elegidas and len(elegidas) < umbral) or (acotada and not elegidas):
|
|
raise GrupoPequeno(f"la selección tiene menos de {umbral} pacientes: su lista no se publica.")
|
|
cabecera = {
|
|
"simulado": True, "cohorte": COHORTE, "escenario": ESCENARIO, "revision": actual, "corte": corte.isoformat(),
|
|
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
|
"filtros": filtros, "filtros_disponibles": disponibles, "columnas": COLUMNAS,
|
|
}
|
|
return cabecera, elegidas
|
|
|
|
|
|
def seguimiento_de(sesion: Session, *, corte: date | None = None, meses: int | None = None, filtros: dict | None = None,
|
|
cohorte: str | None = None, escenario: str | None = None, revision: str | None = None,
|
|
page: int = 1, page_size: int = 50, hoy: date | None = None) -> dict:
|
|
"""A page of the list, ready for `json.dumps`.
|
|
|
|
Raises:
|
|
PedidoInvalido: a parameter out of range or unknown.
|
|
RevisionDistinta: the context quoted is not the server's.
|
|
GrupoPequeno: the selection has fewer patients than the suppression threshold.
|
|
PaginaFuera: `page` past the last page, with patients.
|
|
"""
|
|
cabecera, elegidas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {}, hoy=hoy, page=page,
|
|
page_size=page_size, contexto=(cohorte, escenario, revision))
|
|
total = len(elegidas)
|
|
paginas = -(-total // page_size)
|
|
if total and page > paginas:
|
|
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
|
|
cabecera["paginacion"] = {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas}
|
|
cabecera["items"] = [_item(f) for f in elegidas[(page - 1) * page_size: page * page_size]]
|
|
return cabecera
|
|
|
|
|
|
def paciente_de(sesion: Session, pac_id: str, *, corte=None, meses=None, filtros=None,
|
|
cohorte=None, escenario=None, revision=None, page=1, page_size=50) -> dict:
|
|
"""dev's individual route, after the same full-selection suppression and revision checks."""
|
|
cabecera, filas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {},
|
|
contexto=(cohorte, escenario, revision), hoy=None, page=page, page_size=page_size)
|
|
fila = next((f for f in filas if str(f.pac_id) == pac_id), None)
|
|
if fila is None:
|
|
raise PaginaFuera('Paciente no encontrado en la selección')
|
|
return {**cabecera, 'item': _item(fila)}
|
|
|
|
|
|
def exportacion_de(sesion: Session, *, corte: date | None = None, meses: int | None = None, filtros: dict | None = None,
|
|
cohorte: str | None = None, escenario: str | None = None, revision: str | None = None,
|
|
hoy: date | None = None) -> dict:
|
|
"""Every row of the selection, with the same header, selection rules and context as the list.
|
|
|
|
Raises:
|
|
ExportacionGrande: more than `EXPORTACION_MAXIMA` patients.
|
|
"""
|
|
cabecera, elegidas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {}, hoy=hoy, page=1,
|
|
page_size=1, contexto=(cohorte, escenario, revision))
|
|
if len(elegidas) > EXPORTACION_MAXIMA:
|
|
raise ExportacionGrande(f"la exportación admite hasta {EXPORTACION_MAXIMA} pacientes; la selección tiene {len(elegidas)}.")
|
|
cabecera["total_items"] = len(elegidas)
|
|
cabecera["items"] = [_item(f) for f in elegidas]
|
|
return cabecera
|