Integrate CaMa follow-up, descriptive analysis and L3 with dev
Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
This commit is contained in:
+5
-8
@@ -10,6 +10,8 @@ from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.reports import reports_bp
|
||||
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
|
||||
from webapi.follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
@@ -93,20 +95,15 @@ def create_app() -> Flask:
|
||||
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
|
||||
# an access rule still to be defined, not an environment variable.
|
||||
from persistance import cacu as cacu_repositories
|
||||
from persistance.db import get_cacu_session
|
||||
from persistance.db import get_cacu_session, get_cama_session
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
from webapi.risk_batches import risk_batches_blueprint
|
||||
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
||||
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
# CaMa's follow-up list and analysis selection, over the breast screening cohort `configure_cama_cohort` reads.
|
||||
from webapi.cama_analysis import analysis as cama_analysis_bp
|
||||
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||
|
||||
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama")
|
||||
app.register_blueprint(cama_analysis_bp, url_prefix="/cama")
|
||||
|
||||
return app
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"""CaMa's descriptive analysis (`/cama/analisis`): counts and proportions of the BI-RADS cohort, never survival or risk.
|
||||
|
||||
stats.py Wilson intervals, the chi-square test of homogeneity, quantiles
|
||||
suppression.py the rule for small groups, with the complementary suppression that keeps a difference from giving them away
|
||||
calculations.py the cohort's figures, pure functions over its rows
|
||||
service.py the selection, the calculation and the common header of every answer
|
||||
routes.py the routes
|
||||
"""
|
||||
|
||||
# Compatibility for callers that explicitly mount the previous blueprints.
|
||||
# create_app registers only the L1-L3 routes.
|
||||
from webapi.cama_analysis_legacy import analysis, revision_of, SelectionError, selection_response
|
||||
@@ -0,0 +1,187 @@
|
||||
"""The descriptive analysis of the BI-RADS cohort: pure functions over the cohort's rows.
|
||||
|
||||
Every figure is a count or a proportion of patients of the selection, with the denominator it is a proportion of named in
|
||||
the answer. Nothing here is an incidence, a survival or a risk: the cohort is the patients whose latest reported
|
||||
mammogram is BI-RADS 4 to 6, not a population at risk followed over time.
|
||||
|
||||
Definitions (working conventions, for review):
|
||||
result the grade of the biopsy the list shows (the latest report at the cut-off); `SIN_BIOPSIA` when none,
|
||||
`SIN_DATO` for a report without a grade.
|
||||
known a result that is one of the catalog's grades (benign, in situ, invasive).
|
||||
malignant a grade in `cama.biopsia_cancer` (in situ or invasive); invasive is `CARCINOMA_INVASOR`.
|
||||
horizon `h` days from the mammogram's date. A mammogram counts for a horizon only when `h` days have passed by the
|
||||
cut-off, so a recent mammogram isn't read as one without a biopsy.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from webapi.cama_analysis.stats import cuantil, chi2_homogeneidad, wilson
|
||||
from webapi.cama_analysis.suppression import proporcion_publicable, suprimir_categorias, suprimir_tabla
|
||||
from webapi.cama_follow_up.cohort import SIN_BIOPSIA, SIN_DATO, Fila
|
||||
|
||||
GRADOS_CONOCIDOS = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
|
||||
INVASOR = "CARCINOMA_INVASOR"
|
||||
HORIZONTES = (30, 90, 180, 365)
|
||||
MEDIDAS = ("maligno", "invasor")
|
||||
|
||||
|
||||
def pct(x: float) -> float:
|
||||
return round(100 * x, 2)
|
||||
|
||||
|
||||
def valor_de(f: Fila, dimension: str) -> str:
|
||||
return f.resultado if dimension == "biopsia" else getattr(f, dimension)
|
||||
|
||||
|
||||
def es_conocido(f: Fila) -> bool:
|
||||
return f.biopsia in GRADOS_CONOCIDOS
|
||||
|
||||
|
||||
def es_caso(f: Fila, medida: str, malignos: set[str]) -> bool:
|
||||
return f.biopsia == INVASOR if medida == "invasor" else f.biopsia in malignos
|
||||
|
||||
|
||||
def proporcion(casos: int, total: int, umbral: int) -> dict:
|
||||
"""A proportion with its Wilson interval, or the reason it isn't published."""
|
||||
if total == 0:
|
||||
return {"estado": "sin_datos", "casos": None, "total": 0, "valor": None, "ic_bajo": None, "ic_alto": None}
|
||||
if not proporcion_publicable(casos, total, umbral):
|
||||
return {"estado": "suprimido", "casos": None, "total": None, "valor": None, "ic_bajo": None, "ic_alto": None}
|
||||
bajo, alto = wilson(casos, total)
|
||||
return {"estado": "disponible", "casos": casos, "total": total, "valor": pct(casos / total),
|
||||
"ic_bajo": pct(bajo), "ic_alto": pct(alto)}
|
||||
|
||||
|
||||
def distribucion(filas: list[Fila], por: str, categorias: list[tuple[str, str]], umbral: int) -> dict:
|
||||
"""Patients of the selection by one dimension: count, share and its Wilson interval, and the key to open them."""
|
||||
conteos = {c: 0 for c, _ in categorias}
|
||||
for f in filas:
|
||||
conteos[valor_de(f, por)] = conteos.get(valor_de(f, por), 0) + 1
|
||||
ocultas = suprimir_categorias(conteos, umbral)
|
||||
total = len(filas)
|
||||
items = []
|
||||
for codigo, etiqueta in categorias:
|
||||
n = conteos[codigo]
|
||||
item = {"codigo": codigo, "etiqueta": etiqueta, "suprimido": codigo in ocultas, "n": None, "porcentaje": None,
|
||||
"ic_bajo": None, "ic_alto": None, "seleccion": {por: codigo}}
|
||||
if codigo not in ocultas:
|
||||
item["n"] = n
|
||||
if total:
|
||||
bajo, alto = wilson(n, total)
|
||||
item.update(porcentaje=pct(n / total), ic_bajo=pct(bajo), ic_alto=pct(alto))
|
||||
items.append(item)
|
||||
return {"por": por, "total": total, "items": items}
|
||||
|
||||
|
||||
def comparacion(filas: list[Fila], por: str, categorias: list[tuple[str, str]], medida: str, malignos: set[str],
|
||||
umbral: int) -> dict:
|
||||
"""The share of cases among the patients with a known biopsy result, by group, and the test that groups differ."""
|
||||
grupos, publicados = [], []
|
||||
for codigo, etiqueta in categorias:
|
||||
del_grupo = [f for f in filas if valor_de(f, por) == codigo]
|
||||
conocidos = [f for f in del_grupo if es_conocido(f)]
|
||||
casos = sum(es_caso(f, medida, malignos) for f in conocidos)
|
||||
resultado = proporcion(casos, len(conocidos), umbral)
|
||||
resultado.update(codigo=codigo, etiqueta=etiqueta, seleccion={por: codigo})
|
||||
grupos.append(resultado)
|
||||
if resultado["estado"] == "disponible":
|
||||
publicados.append((casos, len(conocidos)))
|
||||
prueba = chi2_homogeneidad(publicados)
|
||||
prueba["nombre"] = "Chi cuadrada de homogeneidad"
|
||||
return {"por": por, "medida": medida, "denominador": "pacientes con resultado de biopsia conocido", "grupos": grupos,
|
||||
"prueba": prueba}
|
||||
|
||||
|
||||
def mapa(filas: list[Fila], por_filas: str, por_columnas: str, cats_f: list[tuple[str, str]], cats_c: list[tuple[str, str]],
|
||||
medida: str, malignos: set[str], umbral: int) -> dict:
|
||||
"""Two dimensions crossed: patients per cell and, among those with a known result, the share of cases."""
|
||||
conteos = {(f, c): 0 for f, _ in cats_f for c, _ in cats_c}
|
||||
for f in filas:
|
||||
llave = (valor_de(f, por_filas), valor_de(f, por_columnas))
|
||||
if llave in conteos:
|
||||
conteos[llave] += 1
|
||||
ocultas = suprimir_tabla(conteos, umbral)
|
||||
celdas = []
|
||||
for (fc, fe), (cc, ce) in ((f, c) for f in cats_f for c in cats_c):
|
||||
del_grupo = [f for f in filas if valor_de(f, por_filas) == fc and valor_de(f, por_columnas) == cc]
|
||||
conocidos = [f for f in del_grupo if es_conocido(f)]
|
||||
n = conteos[(fc, cc)]
|
||||
celda = {"fila": fc, "columna": cc, "suprimido": (fc, cc) in ocultas, "n": None if (fc, cc) in ocultas else n,
|
||||
"seleccion": {por_filas: fc, por_columnas: cc}}
|
||||
celda["resultado"] = (proporcion(sum(es_caso(f, medida, malignos) for f in conocidos), len(conocidos), umbral)
|
||||
if (fc, cc) not in ocultas else {"estado": "suprimido", "casos": None, "total": None, "valor": None,
|
||||
"ic_bajo": None, "ic_alto": None})
|
||||
celdas.append(celda)
|
||||
return {"filas": {"por": por_filas, "categorias": [{"codigo": c, "etiqueta": e} for c, e in cats_f]},
|
||||
"columnas": {"por": por_columnas, "categorias": [{"codigo": c, "etiqueta": e} for c, e in cats_c]},
|
||||
"medida": medida, "celdas": celdas}
|
||||
|
||||
|
||||
def resumen(filas: list[Fila], corte: date, horizonte: int, malignos: set[str], umbral: int) -> list[dict]:
|
||||
"""The indicator cards of the selection, each with its numerator, denominator, interval and state."""
|
||||
def tarjeta(clave, titulo, descripcion, unidad="%", **datos):
|
||||
return {"clave": clave, "titulo": titulo, "descripcion": descripcion, "unidad": unidad, "estado": "disponible",
|
||||
"valor": None, "ic_bajo": None, "ic_alto": None, "n": None, "denominador": None, "q1": None, "q3": None,
|
||||
"motivo": None, **datos}
|
||||
|
||||
def de_proporcion(clave, titulo, descripcion, casos, total):
|
||||
p = proporcion(casos, total, umbral)
|
||||
return tarjeta(clave, titulo, descripcion, estado=p["estado"], valor=p["valor"], ic_bajo=p["ic_bajo"],
|
||||
ic_alto=p["ic_alto"], n=p["casos"], denominador=p["total"])
|
||||
|
||||
total = len(filas)
|
||||
con_biopsia = [f for f in filas if f.primera_biopsia_fecha is not None]
|
||||
conocidos = [f for f in filas if es_conocido(f)]
|
||||
tarjetas = [
|
||||
tarjeta("cohorte", "Pacientes en la cohorte BI-RADS 4 a 6",
|
||||
"Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "pacientes",
|
||||
valor=total, n=total),
|
||||
de_proporcion("con_biopsia", "Con biopsia reportada",
|
||||
"Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.",
|
||||
len(con_biopsia), total),
|
||||
de_proporcion("maligno_conocido", "Resultado maligno entre las biopsias con resultado",
|
||||
"Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. "
|
||||
"No es incidencia: el denominador son pacientes ya biopsiadas.",
|
||||
sum(es_caso(f, "maligno", malignos) for f in conocidos), len(conocidos)),
|
||||
de_proporcion("invasor_conocido", "Carcinoma invasor entre las biopsias con resultado",
|
||||
"Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.",
|
||||
sum(es_caso(f, "invasor", malignos) for f in conocidos), len(conocidos)),
|
||||
]
|
||||
maduras = [f for f in filas if (corte - f.mastografia_fecha).days >= horizonte]
|
||||
en = lambda fecha_, f: fecha_ is not None and (fecha_ - f.mastografia_fecha).days <= horizonte # noqa: E731
|
||||
tarjetas += [
|
||||
de_proporcion(f"biopsia_{horizonte}d", f"Biopsia reportada en {horizonte} días",
|
||||
f"Pacientes cuya biopsia se reportó dentro de {horizonte} días de la mastografía, entre las que ya "
|
||||
f"cumplieron {horizonte} días al corte.", sum(en(f.primera_biopsia_fecha, f) for f in maduras), len(maduras)),
|
||||
de_proporcion(f"maligno_{horizonte}d", f"Cáncer confirmado en {horizonte} días",
|
||||
f"Pacientes con un reporte de biopsia maligna dentro de {horizonte} días de la mastografía, entre las que "
|
||||
f"ya cumplieron {horizonte} días al corte. No es incidencia acumulada: no hay seguimiento de quien no "
|
||||
"tuvo biopsia.", sum(en(f.primer_maligno_fecha, f) for f in maduras), len(maduras)),
|
||||
]
|
||||
dias = [(f.primera_biopsia_fecha - f.mastografia_fecha).days for f in con_biopsia]
|
||||
if len(dias) >= umbral:
|
||||
tarjetas.append(tarjeta("dias_a_biopsia", "Días de la mastografía al reporte de biopsia",
|
||||
"Mediana y cuartiles entre las pacientes con biopsia reportada.", "días",
|
||||
valor=cuantil(dias, .5), q1=cuantil(dias, .25), q3=cuantil(dias, .75), n=len(dias)))
|
||||
else:
|
||||
tarjetas.append(tarjeta("dias_a_biopsia", "Días de la mastografía al reporte de biopsia",
|
||||
"Mediana y cuartiles entre las pacientes con biopsia reportada.", "días",
|
||||
estado="suprimido" if dias else "sin_datos"))
|
||||
return tarjetas
|
||||
|
||||
|
||||
NO_DISPONIBLES = [
|
||||
{"clave": "supervivencia", "titulo": "Supervivencia",
|
||||
"motivo": "No hay estado vital ni fecha de defunción en las fuentes."},
|
||||
{"clave": "recaida", "titulo": "Recaída",
|
||||
"motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."},
|
||||
{"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento",
|
||||
"motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."},
|
||||
{"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia",
|
||||
"motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero "
|
||||
"común, y la muerte como riesgo competitivo no existe."},
|
||||
{"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido",
|
||||
"motivo": "Dependen de las curvas anteriores."},
|
||||
{"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral",
|
||||
"motivo": "No hay registros de estas variables en las fuentes."},
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""The routes of CaMa's descriptive analysis, under `/cama/analisis`.
|
||||
|
||||
GET /cama/analisis what the analysis offers: dimensions, measures, horizons and what isn't available
|
||||
GET /cama/analisis/resumen the indicator cards of the selection
|
||||
GET /cama/analisis/distribucion patients by BI-RADS, age group or biopsy result
|
||||
GET /cama/analisis/comparacion the share of cases among biopsied patients, by BI-RADS or age group, and its test
|
||||
GET /cama/analisis/mapa BI-RADS by age group
|
||||
GET /cama/analisis/tendencia reports of mammogram and biopsy per month or semester (activity; takes only the cut-off)
|
||||
GET /cama/analisis/indicadores patients of the cohort by BI-RADS category (the aggregate the tab has always read)
|
||||
|
||||
The selection (cut-off, window, filters) is the follow-up list's, with its suppression, its revision and its errors.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, current_app, jsonify, request
|
||||
from sqlmodel import Session
|
||||
from werkzeug.datastructures import MultiDict
|
||||
|
||||
from webapi.cama_analysis import service
|
||||
from webapi.cama_follow_up.access import configured_access
|
||||
from webapi.cama_follow_up.cohort import CohorteNoDisponible
|
||||
from webapi.cama_follow_up.listing import GrupoPequeno, PedidoInvalido, RevisionDistinta
|
||||
from webapi.cama_follow_up.routes import CONTEXTO, FILTROS, _requested
|
||||
|
||||
COMUNES = ("corte", "meses", *CONTEXTO, *FILTROS)
|
||||
ENTEROS = {"horizonte": "horizonte", "periodos": "periodos"}
|
||||
TEXTOS = {"por": "por", "medida": "medida", "tipo": "tipo", "filas": "filas_por", "columnas": "columnas_por"}
|
||||
|
||||
|
||||
def analysis_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""The blueprint of the analysis, to register with `url_prefix="/cama/analisis"`."""
|
||||
blueprint = Blueprint("cama_analisis", __name__)
|
||||
blueprint.before_request(configured_access)
|
||||
|
||||
@blueprint.after_request
|
||||
def no_store(response):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
def answer(build, propios: tuple[str, ...], comunes: tuple[str, ...]):
|
||||
reader = current_app.config.get('CAMA_COHORT_READER')
|
||||
if build is service.indicadores and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
|
||||
from webapi.cama_analysis_legacy import indicators
|
||||
return indicators()
|
||||
try:
|
||||
pedido = _pedido(request.args, propios, comunes)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = build(sesion, **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except GrupoPequeno as error:
|
||||
return jsonify({"error": str(error), "motivo": "supresion"}), 403
|
||||
except RevisionDistinta as error:
|
||||
return jsonify({"error": str(error), "motivo": "revision"}), 409
|
||||
except CohorteNoDisponible as error:
|
||||
return jsonify({"error": str(error), "motivo": "cohorte"}), 503
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
routes = {
|
||||
"": (service.catalogo, ()), "/resumen": (service.resumen, ("horizonte",)),
|
||||
"/distribucion": (service.distribucion, ("por",)), "/comparacion": (service.comparacion, ("por", "medida")),
|
||||
"/mapa": (service.mapa, ("filas", "columnas", "medida")), "/tendencia": (service.tendencia, ("tipo", "periodos"), ("corte",)),
|
||||
"/indicadores": (service.indicadores, ()),
|
||||
}
|
||||
for ruta, (construye, propios, *resto) in routes.items():
|
||||
comunes = resto[0] if resto else COMUNES
|
||||
blueprint.add_url_rule(ruta, endpoint=ruta.strip("/") or "catalogo",
|
||||
view_func=(lambda c=construye, p=propios, k=comunes: answer(c, p, k)), methods=["GET"])
|
||||
return blueprint
|
||||
|
||||
|
||||
def _pedido(args, propios: tuple[str, ...], admitidos: tuple[str, ...] = COMUNES) -> dict:
|
||||
"""The request's parameters: the selection's (typed by the follow-up's own parser) and this route's.
|
||||
|
||||
A route that isn't about the cohort (the trend) admits only the cut-off: window, filters and context are refused.
|
||||
"""
|
||||
for nombre in args:
|
||||
if nombre not in (*admitidos, *propios):
|
||||
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos + propios)}.")
|
||||
comunes = MultiDict((k, v) for k, v in args.items(multi=True) if k in admitidos)
|
||||
base = _requested(comunes, admitidos)
|
||||
if admitidos == COMUNES:
|
||||
pedido = {"corte": base.get("corte"), "meses": base.get("meses"), "filtros": base.get("filtros", {}),
|
||||
"contexto": tuple(base.get(k) for k in CONTEXTO), "hoy": None}
|
||||
else:
|
||||
pedido = {"corte": base.get("corte"), "hoy": None}
|
||||
for nombre in propios:
|
||||
if len(args.getlist(nombre)) > 1:
|
||||
raise ValueError(f"parámetro repetido {nombre!r}.")
|
||||
if nombre in args:
|
||||
valor = args[nombre]
|
||||
if nombre in ENTEROS:
|
||||
if not re.fullmatch(r"\d{1,6}", valor):
|
||||
raise ValueError(f"{nombre} debe ser un entero; llegó {valor!r}")
|
||||
pedido[ENTEROS[nombre]] = int(valor)
|
||||
else:
|
||||
if not valor:
|
||||
raise ValueError(f"{nombre} no puede ir vacío.")
|
||||
pedido[TEXTOS[nombre]] = valor
|
||||
return pedido
|
||||
@@ -0,0 +1,202 @@
|
||||
"""The answers of the descriptive analysis: the selection of L1's cohort, the calculation and the common header.
|
||||
|
||||
Every answer names the cohort, scenario, revision and cut-off of the selection it describes, so a figure can open its
|
||||
patients in the follow-up list, and applies the same window, filters and suppression as that list.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.cama_analysis import calculations as calc
|
||||
from webapi.cama_analysis.suppression import suprimir_categorias
|
||||
from webapi.cama_follow_up.cohort import CANDIDATOS, SIN_DATO, CohorteNoDisponible, disponible
|
||||
from webapi.cama_follow_up.listing import PedidoInvalido, _consulta
|
||||
from webapi.orchestration.reference.rules import valor_de
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
DIMENSIONES = ("birads", "grupo_edad", "biopsia")
|
||||
TIPOS_PERIODO = ("mes", "semestre")
|
||||
PERIODOS_MAXIMOS = 36
|
||||
HORIZONTE_POR_OMISION = 90
|
||||
|
||||
|
||||
def _seleccion(sesion: Session, *, corte, meses, filtros, contexto, hoy):
|
||||
cabecera, filas = _consulta(sesion, corte=corte, meses=0 if meses is None else meses, filtros=filtros, contexto=contexto,
|
||||
hoy=hoy, page=1, page_size=1)
|
||||
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
|
||||
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
|
||||
opciones = {f["clave"]: [(o["codigo"], o["etiqueta"]) for o in f["opciones"]] for f in cabecera["filtros_disponibles"]}
|
||||
# The columns are the list's; the analysis announces its own dimensions instead.
|
||||
encabezado = {k: v for k, v in cabecera.items() if k not in ("columnas", "filtros_disponibles", "simulado")}
|
||||
encabezado["umbral_supresion"] = umbral
|
||||
return encabezado, filas, umbral, malignos, opciones
|
||||
|
||||
|
||||
def _dimension(valor: str | None, nombre: str = "por") -> str:
|
||||
if valor not in DIMENSIONES:
|
||||
raise PedidoInvalido(f"{nombre} = {valor!r}: se admite {list(DIMENSIONES)}.")
|
||||
return valor
|
||||
|
||||
|
||||
def _medida(valor: str | None) -> str:
|
||||
valor = valor or "maligno"
|
||||
if valor not in calc.MEDIDAS:
|
||||
raise PedidoInvalido(f"medida = {valor!r}: se admite {list(calc.MEDIDAS)}.")
|
||||
return valor
|
||||
|
||||
|
||||
def catalogo(sesion: Session, **seleccion) -> dict:
|
||||
encabezado, _, umbral, _, opciones = _seleccion(sesion, **seleccion)
|
||||
return {
|
||||
**encabezado,
|
||||
"dimensiones": [{"clave": c, "etiqueta": e, "opciones": [{"codigo": k, "etiqueta": v} for k, v in opciones[c]]}
|
||||
for c, e in (("birads", "Categoría BI-RADS"), ("grupo_edad", "Grupo de edad"), ("biopsia", "Resultado de la biopsia"))],
|
||||
"medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}],
|
||||
"horizontes_dias": list(calc.HORIZONTES), "tipos_periodo": list(TIPOS_PERIODO),
|
||||
"secciones": [{"clave": c, "titulo": t, "estado": "disponible", "motivo": None} for c, t in (
|
||||
("resumen", "Indicadores de la cohorte"), ("distribucion", "Distribución de pacientes"),
|
||||
("comparacion", "Comparación entre grupos"), ("mapa", "Mapa entre variables"), ("tendencia", "Tendencia en el tiempo"))],
|
||||
"no_disponibles": calc.NO_DISPONIBLES,
|
||||
}
|
||||
|
||||
|
||||
def resumen(sesion: Session, *, horizonte: int | None = None, **seleccion) -> dict:
|
||||
horizonte = HORIZONTE_POR_OMISION if horizonte is None else horizonte
|
||||
if horizonte not in calc.HORIZONTES:
|
||||
raise PedidoInvalido(f"horizonte = {horizonte!r}: se admite {list(calc.HORIZONTES)}.")
|
||||
encabezado, filas, umbral, malignos, _ = _seleccion(sesion, **seleccion)
|
||||
corte = date.fromisoformat(encabezado["corte"])
|
||||
return {**encabezado, "horizonte_dias": horizonte, "indicadores": calc.resumen(filas, corte, horizonte, malignos, umbral),
|
||||
"no_disponibles": calc.NO_DISPONIBLES}
|
||||
|
||||
|
||||
def distribucion(sesion: Session, *, por: str | None = None, **seleccion) -> dict:
|
||||
por = _dimension(por)
|
||||
encabezado, filas, umbral, _, opciones = _seleccion(sesion, **seleccion)
|
||||
return {**encabezado, **calc.distribucion(filas, por, opciones[por], umbral)}
|
||||
|
||||
|
||||
def comparacion(sesion: Session, *, por: str | None = None, medida: str | None = None, **seleccion) -> dict:
|
||||
por, medida = _dimension(por), _medida(medida)
|
||||
if por == "biopsia":
|
||||
raise PedidoInvalido("se compara por BI-RADS o por grupo de edad: el resultado de la biopsia es lo que se mide.")
|
||||
encabezado, filas, umbral, malignos, opciones = _seleccion(sesion, **seleccion)
|
||||
return {**encabezado, **calc.comparacion(filas, por, opciones[por], medida, malignos, umbral)}
|
||||
|
||||
|
||||
def mapa(sesion: Session, *, filas_por: str | None = None, columnas_por: str | None = None, medida: str | None = None, **seleccion) -> dict:
|
||||
filas_por, columnas_por, medida = _dimension(filas_por, "filas"), _dimension(columnas_por, "columnas"), _medida(medida)
|
||||
if filas_por == columnas_por:
|
||||
raise PedidoInvalido("las filas y las columnas deben ser dimensiones distintas.")
|
||||
if "biopsia" in (filas_por, columnas_por):
|
||||
raise PedidoInvalido("el mapa cruza BI-RADS y grupo de edad: el resultado de la biopsia es lo que se mide.")
|
||||
encabezado, filas, umbral, malignos, opciones = _seleccion(sesion, **seleccion)
|
||||
return {**encabezado, **calc.mapa(filas, filas_por, columnas_por, opciones[filas_por], opciones[columnas_por], medida, malignos, umbral)}
|
||||
|
||||
|
||||
def indicadores(sesion: Session, **seleccion) -> dict:
|
||||
"""The cohort's patients by BI-RADS category: the aggregate the analysis tab has always read."""
|
||||
encabezado, filas, umbral, _, opciones = _seleccion(sesion, **seleccion)
|
||||
d = calc.distribucion(filas, "birads", opciones["birads"], umbral)
|
||||
return {"simulado": True, "cohorte": encabezado["cohorte"], "revision": encabezado["revision"], "escenario": encabezado["escenario"],
|
||||
"corte": encabezado["corte"], "umbral_supresion": umbral, "unidad": "paciente",
|
||||
"denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6",
|
||||
# This contract publishes a category only from the threshold: an empty one is not published either.
|
||||
"grupos": [{"codigo": i["codigo"], "n": None if i["suprimido"] or not i["n"] else i["n"], "suprimido": i["suprimido"] or not i["n"]}
|
||||
for i in d["items"]],
|
||||
"horizonte_dias": 0, "indicadores": []}
|
||||
|
||||
|
||||
def _periodo(fecha: date, tipo: str) -> tuple[str, date, date]:
|
||||
if tipo == "mes":
|
||||
inicio = fecha.replace(day=1)
|
||||
fin = (date(inicio.year + (inicio.month == 12), inicio.month % 12 + 1, 1))
|
||||
return f"{inicio.year}-{inicio.month:02d}", inicio, fin
|
||||
semestre = 1 if fecha.month <= 6 else 2
|
||||
inicio = date(fecha.year, 1 if semestre == 1 else 7, 1)
|
||||
fin = date(fecha.year + (semestre == 2), 7 if semestre == 1 else 1, 1)
|
||||
return f"{fecha.year}-S{semestre}", inicio, fin
|
||||
|
||||
|
||||
def _periodos_hasta(corte: date, tipo: str, cuantos: int) -> list[tuple[str, date, date]]:
|
||||
periodos = []
|
||||
ref = corte
|
||||
for _ in range(cuantos):
|
||||
periodo = _periodo(ref, tipo)
|
||||
periodos.append(periodo)
|
||||
ref = periodo[1].fromordinal(periodo[1].toordinal() - 1)
|
||||
return periodos[::-1]
|
||||
|
||||
|
||||
POBLACION_TENDENCIA = ("Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, "
|
||||
"de todas las pacientes; no la cohorte de Seguimiento")
|
||||
ALCANCE_BIOPSIAS = ("Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); "
|
||||
"una biopsia sin mastografía ligada no se cuenta")
|
||||
|
||||
|
||||
def tendencia(sesion: Session, *, tipo: str | None = None, periodos: int | None = None, corte: date | None = None,
|
||||
hoy: date | None = None) -> dict:
|
||||
"""Mammogram reports and biopsy reports per period, and the share of malignant results among the graded biopsies.
|
||||
|
||||
It is activity, not the cohort: it counts reports (a mammogram's report with a BI-RADS, a biopsy's report linked to
|
||||
one of those mammograms) by the date of the report, over every patient. It takes no window and no filter of the
|
||||
cohort, and says so; the same cut-off, period type and number of periods always give the same answer. A report is
|
||||
one count however many reports a patient has, so the shares are of reports, not of patients, and carry no test:
|
||||
repeated reports of a patient aren't independent observations. A period's total is published from the suppression
|
||||
threshold; the categories of a period hide by complement (a hidden category takes the smallest published one with
|
||||
it), so the total gives none of them away. The period the cut-off falls in is flagged.
|
||||
"""
|
||||
tipo = tipo or "mes"
|
||||
if tipo not in TIPOS_PERIODO:
|
||||
raise PedidoInvalido(f"tipo = {tipo!r}: se admite {list(TIPOS_PERIODO)}.")
|
||||
periodos = (12 if tipo == "mes" else 6) if periodos is None else periodos
|
||||
if not 1 <= periodos <= PERIODOS_MAXIMOS:
|
||||
raise PedidoInvalido(f"periodos va de 1 a {PERIODOS_MAXIMOS}.")
|
||||
if not disponible(sesion):
|
||||
raise CohorteNoDisponible("la cohorte aún no está disponible: falta correr el ciclo de indicadores de CaMa")
|
||||
hoy = hoy or date.today()
|
||||
corte = hoy if corte is None else corte
|
||||
if corte > hoy:
|
||||
raise PedidoInvalido(f"corte {corte.isoformat()} es posterior a hoy ({hoy.isoformat()}).")
|
||||
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
|
||||
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
|
||||
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
|
||||
gravedad = {c: i for i, c in enumerate(valor_de(sesion, "cama.birads_gravedad", tablas=TABLAS))}
|
||||
c = CANDIDATOS.c
|
||||
filas = sesion.execute(select(CANDIDATOS).where(c.fecha_reporte <= corte)).mappings().all()
|
||||
mastografias: dict[int, tuple] = {}
|
||||
biopsias: dict[int, tuple] = {}
|
||||
for f in filas:
|
||||
previo = mastografias.get(f["reporte_id"])
|
||||
if previo is None or gravedad.get(f["birads"], -1) > gravedad.get(previo[1], -1):
|
||||
mastografias[f["reporte_id"]] = (f["fecha_reporte"], f["birads"])
|
||||
if f["biopsia_id"] is not None and f["biopsia_fecha_reporte"] <= corte:
|
||||
previa = biopsias.get(f["biopsia_id"])
|
||||
rango = calc.GRADOS_CONOCIDOS.index(f["biopsia_grado"]) if f["biopsia_grado"] in calc.GRADOS_CONOCIDOS else -1
|
||||
if previa is None or rango > previa[2]:
|
||||
biopsias[f["biopsia_id"]] = (f["biopsia_fecha_reporte"], f["biopsia_grado"], rango)
|
||||
salida = []
|
||||
for nombre, inicio, fin in _periodos_hasta(corte, tipo, periodos):
|
||||
ultimo_dia = fin.fromordinal(fin.toordinal() - 1)
|
||||
m = [b for fecha, b in mastografias.values() if inicio <= fecha < fin]
|
||||
b = [g for fecha, g, _ in biopsias.values() if inicio <= fecha < fin]
|
||||
mm = {"4_a_6": sum(x in admitidos for x in m), "otras": sum(x not in admitidos for x in m)}
|
||||
ocultas_m = suprimir_categorias(mm, umbral)
|
||||
grados = {g: sum(x == g for x in b) for g in calc.GRADOS_CONOCIDOS}
|
||||
grados[SIN_DATO] = sum(x not in calc.GRADOS_CONOCIDOS for x in b)
|
||||
ocultas_b = suprimir_categorias(grados, umbral)
|
||||
conocidos = sum(grados[g] for g in calc.GRADOS_CONOCIDOS)
|
||||
casos = sum(grados[g] for g in calc.GRADOS_CONOCIDOS if g in malignos)
|
||||
salida.append({
|
||||
"periodo": nombre, "inicio": inicio.isoformat(), "fin": ultimo_dia.isoformat(), "incompleto": corte < ultimo_dia,
|
||||
"reportes_mastografia": {"total": None if 0 < len(m) < umbral else len(m),
|
||||
"por_categoria": {k: {"n": None if k in ocultas_m else v, "suprimido": k in ocultas_m} for k, v in mm.items()}},
|
||||
"reportes_biopsia": {"total": None if 0 < len(b) < umbral else len(b),
|
||||
"por_grado": {k: {"n": None if k in ocultas_b else v, "suprimido": k in ocultas_b} for k, v in grados.items()}},
|
||||
"maligno": calc.proporcion(casos, conocidos, umbral),
|
||||
})
|
||||
return {"corte": corte.isoformat(), "umbral_supresion": umbral, "tipo_periodo": tipo, "unidad": "reportes",
|
||||
"poblacion": POBLACION_TENDENCIA, "alcance_biopsias": ALCANCE_BIOPSIAS,
|
||||
"denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": salida}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""The statistics the descriptive analysis uses: Wilson intervals, the chi-square test of homogeneity and quantiles.
|
||||
|
||||
Plain `math`: no statistics package, so the same inputs give the same numbers on every engine and machine.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
Z95 = 1.959963984540054
|
||||
|
||||
|
||||
def wilson(k: int, n: int, z: float = Z95) -> tuple[float, float]:
|
||||
"""The Wilson score interval of `k` of `n`, as proportions in [0, 1]. Needs `n > 0` and `0 <= k <= n`."""
|
||||
if n <= 0 or not 0 <= k <= n:
|
||||
raise ValueError(f"Wilson needs 0 <= k <= n and n > 0; got k={k}, n={n}")
|
||||
p = k / n
|
||||
denominador = 1 + z * z / n
|
||||
centro = (p + z * z / (2 * n)) / denominador
|
||||
margen = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominador
|
||||
return max(0.0, round(centro - margen, 12)), min(1.0, round(centro + margen, 12))
|
||||
|
||||
|
||||
def _gamma_q(a: float, x: float) -> float:
|
||||
"""The regularized upper incomplete gamma function Q(a, x)."""
|
||||
if x <= 0:
|
||||
return 1.0
|
||||
if x < a + 1:
|
||||
# Series for P(a, x); Q = 1 - P.
|
||||
termino = suma = 1.0 / a
|
||||
n = a
|
||||
for _ in range(1000):
|
||||
n += 1
|
||||
termino *= x / n
|
||||
suma += termino
|
||||
if abs(termino) < abs(suma) * 1e-15:
|
||||
break
|
||||
return max(0.0, 1.0 - suma * math.exp(-x + a * math.log(x) - math.lgamma(a)))
|
||||
# Continued fraction for Q(a, x) (modified Lentz).
|
||||
tiny = 1e-300
|
||||
b = x + 1 - a
|
||||
c = 1 / tiny
|
||||
d = 1 / b
|
||||
h = d
|
||||
for i in range(1, 1000):
|
||||
an = -i * (i - a)
|
||||
b += 2
|
||||
d = an * d + b
|
||||
d = tiny if abs(d) < tiny else d
|
||||
c = b + an / c
|
||||
c = tiny if abs(c) < tiny else c
|
||||
d = 1 / d
|
||||
delta = d * c
|
||||
h *= delta
|
||||
if abs(delta - 1) < 1e-15:
|
||||
break
|
||||
return min(1.0, math.exp(-x + a * math.log(x) - math.lgamma(a)) * h)
|
||||
|
||||
|
||||
def chi2_sf(x: float, gl: int) -> float:
|
||||
"""The probability that a chi-square variable with `gl` degrees of freedom exceeds `x`."""
|
||||
if gl < 1:
|
||||
raise ValueError("a chi-square needs at least one degree of freedom")
|
||||
return _gamma_q(gl / 2, x / 2)
|
||||
|
||||
|
||||
def chi2_homogeneidad(grupos: list[tuple[int, int]], minimo_esperado: float = 5.0) -> dict:
|
||||
"""The chi-square test that `k` groups share one proportion, from each group's (cases, total).
|
||||
|
||||
Valid only with at least two groups and every expected count (cases and non-cases) at or above `minimo_esperado`;
|
||||
otherwise it says why it isn't. Never a p-value from a table the approximation can't be trusted on.
|
||||
"""
|
||||
if len(grupos) < 2:
|
||||
return {"valida": False, "motivo": "Hacen falta al menos dos grupos con datos publicados."}
|
||||
casos, total = sum(k for k, _ in grupos), sum(n for _, n in grupos)
|
||||
if total == 0 or casos in (0, total):
|
||||
return {"valida": False, "motivo": "Todos los pacientes tienen el mismo resultado."}
|
||||
p = casos / total
|
||||
esperados = [(n * p, n * (1 - p)) for _, n in grupos]
|
||||
if any(min(a, b) < minimo_esperado for a, b in esperados):
|
||||
return {"valida": False, "motivo": f"Algún conteo esperado es menor que {minimo_esperado:g}: la aproximación no es confiable."}
|
||||
estadistico = sum((k - n * p) ** 2 / (n * p) + ((n - k) - n * (1 - p)) ** 2 / (n * (1 - p)) for k, n in grupos)
|
||||
gl = len(grupos) - 1
|
||||
return {"valida": True, "estadistico": round(estadistico, 4), "gl": gl, "p": chi2_sf(estadistico, gl)}
|
||||
|
||||
|
||||
def cuantil(valores: list[float], q: float) -> float:
|
||||
"""The quantile `q` (0 to 1) by linear interpolation between order statistics (the common 'type 7')."""
|
||||
if not valores:
|
||||
raise ValueError("a quantile needs at least one value")
|
||||
ordenados = sorted(valores)
|
||||
posicion = (len(ordenados) - 1) * q
|
||||
abajo = math.floor(posicion)
|
||||
arriba = min(abajo + 1, len(ordenados) - 1)
|
||||
return ordenados[abajo] + (ordenados[arriba] - ordenados[abajo]) * (posicion - abajo)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Suppression of small groups in the descriptive analysis.
|
||||
|
||||
A count of 1 to `umbral - 1` patients is never published. Hiding only those would still let a difference give them away
|
||||
(a published total minus the published cells), so a hidden cell drags the smallest published cell of its line with it
|
||||
until the hidden patients are at least `umbral`. A proportion is published only when neither its group, its cases nor its
|
||||
non-cases is such a small count. Zero is published: it describes nobody.
|
||||
"""
|
||||
|
||||
PEQUENO = lambda n, umbral: 0 < n < umbral # noqa: E731
|
||||
|
||||
|
||||
def proporcion_publicable(casos: int, total: int, umbral: int) -> bool:
|
||||
"""Whether `casos` of `total` may be published: the group, the cases and the rest are each zero or at least `umbral`."""
|
||||
return total >= umbral and not PEQUENO(casos, umbral) and not PEQUENO(total - casos, umbral)
|
||||
|
||||
|
||||
def _completar(suprimidas: set, conteos: dict, linea: list, umbral: int) -> bool:
|
||||
"""Adds to `suprimidas` the smallest published cells of `linea` until the hidden ones of it total `umbral` or more."""
|
||||
cambio = False
|
||||
while True:
|
||||
ocultos = sum(conteos[c] for c in linea if c in suprimidas)
|
||||
if ocultos == 0 or ocultos >= umbral:
|
||||
return cambio
|
||||
candidatas = [c for c in linea if c not in suprimidas and conteos[c] > 0]
|
||||
if not candidatas:
|
||||
return cambio
|
||||
suprimidas.add(min(candidatas, key=lambda c: (conteos[c], str(c))))
|
||||
cambio = True
|
||||
|
||||
|
||||
def suprimir_categorias(conteos: dict[str, int], umbral: int) -> set[str]:
|
||||
"""The categories of one distribution whose count is not published."""
|
||||
suprimidas = {c for c, n in conteos.items() if PEQUENO(n, umbral)}
|
||||
_completar(suprimidas, conteos, list(conteos), umbral)
|
||||
return suprimidas
|
||||
|
||||
|
||||
def suprimir_tabla(conteos: dict[tuple[str, str], int], umbral: int) -> set[tuple[str, str]]:
|
||||
"""The cells of a two-way table whose count is not published, with the same rule applied along every row and column."""
|
||||
suprimidas = {c for c, n in conteos.items() if PEQUENO(n, umbral)}
|
||||
filas = {f for f, _ in conteos}
|
||||
columnas = {c for _, c in conteos}
|
||||
lineas = [[k for k in conteos if k[0] == f] for f in sorted(filas)] + [[k for k in conteos if k[1] == c] for c in sorted(columnas)]
|
||||
cambio = True
|
||||
while cambio:
|
||||
cambio = False
|
||||
for linea in lineas:
|
||||
cambio |= _completar(suprimidas, conteos, linea, umbral)
|
||||
return suprimidas
|
||||
@@ -0,0 +1,9 @@
|
||||
"""CaMa's follow-up list (`GET /cama/seguimiento`): the patients of the BI-RADS cohort at a cut-off, one row each.
|
||||
|
||||
cohort.py who is in the cohort at a cut-off and what each row shows
|
||||
listing.py the selection (window, filters, suppression), the pages, the file and the revision
|
||||
routes.py the routes: validate the request and answer
|
||||
|
||||
The cohort is read from dbt's `cama_cohorte_birads` view. Every response is marked `simulado`: the list holds
|
||||
patient-level rows, and who may read it on real data is an access rule still to be defined.
|
||||
"""
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Retain dev's optional access callback; no new authentication policy."""
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
|
||||
def configured_access():
|
||||
check = current_app.config.get('CAMA_COHORT_ACCESS')
|
||||
if check is not None and (not callable(check) or not check(request)):
|
||||
return jsonify(error='Acceso no autorizado'), 403
|
||||
@@ -0,0 +1,146 @@
|
||||
"""The BI-RADS cohort at a cut-off.
|
||||
|
||||
Each patient counts once, through her latest mammogram whose report (with a BI-RADS) is dated on or before the cut-off;
|
||||
she belongs to the cohort when that BI-RADS is one of `cama.birads_4_a_6`. The latest is the one with the latest
|
||||
date taken, then the greatest source id, then the latest report date, then the greatest report id, so the same data
|
||||
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.
|
||||
|
||||
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 sqlalchemy import Date, Integer, String, column, func, inspect, select, table
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import valor_de
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
COHORTE = "cama_birads_v1"
|
||||
ESCENARIO = "diagnostico"
|
||||
VERSION = "0.1.0"
|
||||
SIN_DATO = "SIN_DATO"
|
||||
SIN_BIOPSIA = "SIN_BIOPSIA"
|
||||
# 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")
|
||||
|
||||
CANDIDATOS = table(
|
||||
"cama_cohorte_birads",
|
||||
column("pac_id", Integer), column("procedimiento_id", Integer), column("fuente_id", String),
|
||||
column("fecha_toma", Date), column("reporte_id", Integer), column("fecha_reporte", Date), column("birads", String),
|
||||
column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String),
|
||||
column("biopsia_fecha_reporte", Date), column("biopsia_grado", String),
|
||||
)
|
||||
|
||||
|
||||
class CohorteNoDisponible(RuntimeError):
|
||||
"""The cohort's view 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)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Fila:
|
||||
"""One patient of the cohort: the codes the list shows and filters by."""
|
||||
|
||||
pac_id: int
|
||||
mastografia_fecha: date
|
||||
birads: str
|
||||
grupo_edad: str
|
||||
biopsia: str | None
|
||||
biopsia_fecha: date | None
|
||||
# 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
|
||||
|
||||
@property
|
||||
def resultado(self) -> str:
|
||||
"""The value the biopsy filter compares: the grade, `SIN_DATO` for a report without one, `SIN_BIOPSIA` for none."""
|
||||
if self.biopsia_fecha is None:
|
||||
return SIN_BIOPSIA
|
||||
return self.biopsia or SIN_DATO
|
||||
|
||||
|
||||
def _rango_de_grado(grado: str | None) -> int:
|
||||
return GRADOS_POR_GRAVEDAD.index(grado) if grado in GRADOS_POR_GRAVEDAD else -1
|
||||
|
||||
|
||||
def codigo_birads(fuente: str) -> str:
|
||||
"""`B4A` as the list names it: `BIRADS_4A`."""
|
||||
return "BIRADS_" + fuente[1:]
|
||||
|
||||
|
||||
def grupos_de_edad(sesion: Session) -> list[str]:
|
||||
"""The age groups of `cama.grupos_edad` in order, with the open ones at both ends (`<40`, `40-49`, ..., `70+`)."""
|
||||
cortes = valor_de(sesion, "cama.grupos_edad", tablas=TABLAS)
|
||||
return [g.etiqueta for g in sorted(grupos_de_cortes(cortes, tablas=TABLAS), key=lambda g: g.edad_min)]
|
||||
|
||||
|
||||
def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
|
||||
"""The completed age at the cut-off in its group; `SIN_DATO` without a birth date or with one after the cut-off."""
|
||||
if nacimiento is None or nacimiento > corte:
|
||||
return SIN_DATO
|
||||
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
|
||||
for grupo in grupos:
|
||||
if grupo.edad_min <= edad <= grupo.edad_max:
|
||||
return grupo.etiqueta
|
||||
return SIN_DATO
|
||||
|
||||
|
||||
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
|
||||
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
|
||||
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)
|
||||
c = CANDIDATOS.c
|
||||
candidatas = sesion.execute(
|
||||
select(CANDIDATOS).where(c.fecha_reporte <= corte, c.fecha_toma <= c.fecha_reporte)
|
||||
).mappings().all()
|
||||
|
||||
gravedad = {codigo: rango for rango, codigo in enumerate(valor_de(sesion, "cama.birads_gravedad", tablas=TABLAS))}
|
||||
por_mastografia: dict[tuple, dict] = {}
|
||||
for fila in candidatas:
|
||||
mastografia = por_mastografia.setdefault(
|
||||
(fila["pac_id"], fila["procedimiento_id"], fila["reporte_id"], fila["birads"]), {"fila": fila, "biopsias": []})
|
||||
# A biopsy report dated after the cut-off, or before the mammogram, doesn't exist for this list.
|
||||
if fila["biopsia_id"] is not None and fila["fecha_toma"] <= fila["biopsia_fecha_reporte"] <= corte:
|
||||
mastografia["biopsias"].append(fila)
|
||||
mastografias: dict[int, tuple] = {}
|
||||
for mastografia in por_mastografia.values():
|
||||
fila = mastografia["fila"]
|
||||
llave = (fila["fecha_toma"], str(fila["fuente_id"]), fila["fecha_reporte"], fila["reporte_id"],
|
||||
gravedad.get(fila["birads"], -1))
|
||||
if fila["pac_id"] not in mastografias or llave > mastografias[fila["pac_id"]][0]:
|
||||
mastografias[fila["pac_id"]] = (llave, mastografia)
|
||||
|
||||
cohorte = []
|
||||
for pac_id, (_, elegida) in mastografias.items():
|
||||
fila = elegida["fila"]
|
||||
if fila["birads"] not in admitidos:
|
||||
continue
|
||||
biopsia = max(elegida["biopsias"], key=lambda b: (b["biopsia_fecha_reporte"], str(b["biopsia_fuente_id"]), b["biopsia_id"],
|
||||
_rango_de_grado(b["biopsia_grado"])), default=None)
|
||||
cohorte.append(Fila(
|
||||
pac_id=pac_id, mastografia_fecha=fila["fecha_toma"], birads=codigo_birads(fila["birads"]),
|
||||
grupo_edad=grupo_de_edad(fila["fecha_nacimiento"], corte, grupos),
|
||||
biopsia=biopsia["biopsia_grado"] if biopsia else None,
|
||||
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),
|
||||
))
|
||||
return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id))
|
||||
|
||||
|
||||
def construccion(sesion: Session) -> str:
|
||||
"""The data the cohort stands on: the last load that added or changed rows (`carga-<id>`, `carga-0` without any)."""
|
||||
carga = TABLAS.Carga
|
||||
ultima = sesion.execute(
|
||||
select(func.max(carga.carga_id)).where((carga.filas_nuevas > 0) | (carga.filas_cambiadas > 0))
|
||||
).scalar()
|
||||
return f"carga-{ultima or 0}"
|
||||
@@ -0,0 +1,190 @@
|
||||
"""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
|
||||
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,
|
||||
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"}
|
||||
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"}]},
|
||||
]
|
||||
|
||||
|
||||
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"}]},
|
||||
]
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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}
|
||||
|
||||
|
||||
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_al(sesion, corte), 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
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The routes of CaMa's follow-up list: `GET /cama/seguimiento` and `GET /cama/seguimiento/exportacion`."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
from flask import Blueprint, Response, current_app, jsonify, request
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.cama_follow_up.cohort import CohorteNoDisponible
|
||||
from webapi.cama_follow_up.access import configured_access
|
||||
from webapi.cama_follow_up.listing import (
|
||||
ExportacionGrande, GrupoPequeno, PaginaFuera, PedidoInvalido, RevisionDistinta, exportacion_de, seguimiento_de, paciente_de,
|
||||
)
|
||||
|
||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
FILTROS = ("birads", "grupo_edad", "biopsia")
|
||||
CONTEXTO = ("cohorte", "escenario", "revision")
|
||||
ENTEROS = ("meses", "page", "page_size")
|
||||
|
||||
|
||||
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""The blueprint of the list and its file, to register with `url_prefix="/cama"`."""
|
||||
blueprint = Blueprint("cama_seguimiento", __name__)
|
||||
blueprint.before_request(configured_access)
|
||||
|
||||
@blueprint.after_request
|
||||
def no_store(response):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
def answer(build, admitidos: tuple[str, ...], legacy_mode=None, patient=None):
|
||||
reader = current_app.config.get('CAMA_COHORT_READER')
|
||||
if legacy_mode and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
|
||||
from webapi.cama_analysis_legacy import SelectionError, selection_response
|
||||
try:
|
||||
return selection_response(request.args, legacy_mode, patient)
|
||||
except SelectionError as error:
|
||||
return jsonify(error=error.message), error.status
|
||||
try:
|
||||
pedido = _requested(request.args, admitidos)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = build(sesion, **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except GrupoPequeno as error:
|
||||
return jsonify({"error": str(error), "motivo": "supresion"}), 403
|
||||
except PaginaFuera as error:
|
||||
return jsonify({"error": str(error)}), 404
|
||||
except RevisionDistinta as error:
|
||||
return jsonify({"error": str(error), "motivo": "revision"}), 409
|
||||
except ExportacionGrande as error:
|
||||
return jsonify({"error": str(error)}), 413
|
||||
except CohorteNoDisponible as error:
|
||||
return jsonify({"error": str(error), "motivo": "cohorte"}), 503
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
@blueprint.get("/seguimiento")
|
||||
def get_seguimiento():
|
||||
"""The BI-RADS cohort's follow-up list at a cut-off, one page."""
|
||||
return answer(seguimiento_de, ("corte", *ENTEROS, *CONTEXTO, *FILTROS), 'list')
|
||||
|
||||
@blueprint.get("/seguimiento/exportacion")
|
||||
def get_exportacion():
|
||||
"""Every row of the same selection, for a file."""
|
||||
return answer(exportacion_de, ("corte", "meses", *CONTEXTO, *FILTROS), 'export')
|
||||
|
||||
@blueprint.get('/pacientes/<pac_id>')
|
||||
def paciente(pac_id):
|
||||
return answer(lambda session, **pedido: paciente_de(session, pac_id, **pedido),
|
||||
('corte', *ENTEROS, *CONTEXTO, *FILTROS), 'patient', pac_id)
|
||||
|
||||
return blueprint
|
||||
|
||||
|
||||
def _requested(args, admitidos: tuple[str, ...]) -> dict:
|
||||
"""The query's parameters, typed. `ValueError` for an unknown, repeated or badly written one."""
|
||||
for nombre in args:
|
||||
if nombre not in admitidos:
|
||||
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos)}.")
|
||||
if len(args.getlist(nombre)) > 1:
|
||||
raise ValueError(f"parámetro repetido {nombre!r}.")
|
||||
pedido: dict = {}
|
||||
if (corte := args.get("corte")) is not None:
|
||||
if not FECHA.fullmatch(corte):
|
||||
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
|
||||
try:
|
||||
pedido["corte"] = date.fromisoformat(corte)
|
||||
except ValueError:
|
||||
raise ValueError(f"corte {corte!r} no es una fecha") from None
|
||||
for nombre in ENTEROS:
|
||||
if nombre in args:
|
||||
if not re.fullmatch(r"\d{1,6}", args[nombre]):
|
||||
raise ValueError(f"{nombre} debe ser un entero; llegó {args[nombre]!r}")
|
||||
pedido[nombre] = int(args[nombre])
|
||||
contexto = {n: args[n] for n in CONTEXTO if n in args}
|
||||
if contexto and len(contexto) != len(CONTEXTO):
|
||||
raise ValueError(f"el contexto de la cohorte lleva {list(CONTEXTO)} juntos.")
|
||||
if any(not v for v in contexto.values()):
|
||||
raise ValueError("el contexto de la cohorte no puede ir vacío.")
|
||||
pedido.update(contexto)
|
||||
filtros = {n: args[n] for n in FILTROS if n in args}
|
||||
if any(not v for v in filtros.values()):
|
||||
raise ValueError("un filtro no puede ir vacío.")
|
||||
if filtros:
|
||||
pedido["filtros"] = filtros
|
||||
return pedido
|
||||
@@ -9,4 +9,8 @@ def configure_cama_cohort(app):
|
||||
with get_cama_session() as session:
|
||||
return CamaCohort(session).rows(cutoff)
|
||||
|
||||
read._cama_default_reader = True
|
||||
# Distinguish the historical default from an explicit integration override.
|
||||
# Normal create_app uses L1-L3; consumers that replace the callback keep dev's contract.
|
||||
read._cama_default_reader = True
|
||||
app.config['CAMA_COHORT_READER'] = read
|
||||
|
||||
@@ -284,6 +284,10 @@ class MeasureQueries:
|
||||
for a in p.at_end if a.known_at}
|
||||
for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)):
|
||||
known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())}
|
||||
# The follow-up fact of a composition (the biopsy of the chosen sample) is compared with the knowledge cut-off too:
|
||||
# its column has to be read as a datetime, or a text compare against the cut-off would be wrong.
|
||||
follow_up = getattr(getattr(definition, "category", None), "follow_up", None)
|
||||
known |= {definition.dimensions[n] for n in (follow_up.known_at if follow_up else ())}
|
||||
self.status = getattr(definition, "population", None)
|
||||
if self.status is not None:
|
||||
names |= {definition.dimensions[n] for n in self.status.columns()}
|
||||
|
||||
Reference in New Issue
Block a user