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:
Angel Capetillo Zavala
2026-11-17 10:44:07 -06:00
parent 0571b5e6af
commit b1bbbc25b4
27 changed files with 2729 additions and 12 deletions
+12
View File
@@ -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
+187
View File
@@ -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."},
]
+108
View File
@@ -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
+202
View File
@@ -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}
+93
View File
@@ -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)
+49
View File
@@ -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