Files

165 lines
8.1 KiB
Python

"""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.
Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on
or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise.
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, timedelta
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"
POST_TRATAMIENTO = "POST_TRATAMIENTO"
EN_OBSERVACION = "EN_OBSERVACION"
# 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),
)
LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date))
class CohorteNoDisponible(RuntimeError):
"""The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't
run (503)."""
def disponible(sesion: Session) -> bool:
inspector = inspect(sesion.get_bind())
return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO))
@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
escenario_clinico: str = EN_OBSERVACION
@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 en_postratamiento(sesion: Session, corte: date) -> set[int]:
"""The patients whose timeline puts them in post-treatment on or before `corte`."""
linea = LINEA_DE_TIEMPO.c
# Before the next day, so a date stored with a time still counts on its own day.
return set(sesion.execute(select(linea.pac_id).distinct().where(
linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars())
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
postratamiento = en_postratamiento(sesion, corte)
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),
escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION,
))
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}"