"""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}