Files
ISSSTELEON/Persistance/persistance/aristas/oro/cohortes.py
T

338 lines
14 KiB
Python

"""Oro: cohortes para modelos y sus lotes de riesgos, la escritura (ADR-MD-003, ADR-MD-005).
El kit arma el marco de una cohorte (quién entra, su fecha índice, sus variables,
la atrición) y sus huellas. Aquí se guarda: el armado con sus filas, el lote de
riesgos con las llaves de MLflow, y los cambios de estado de las evaluaciones.
Rearmar lo mismo no guarda otro armado (misma `huella` y mismo `marco_sha`), y
puntuar lo mismo otra vez no guarda otro lote (misma `huella` del lote). Una
evaluación solo crece: confirmarla (`preliminary` -> `final`) o anularla
(`entered-in-error`) agrega una versión con su motivo.
"""
import hashlib
import json
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from datetime import date, datetime, timezone
from typing import TypeVar
from core.indicadores.cohortes import TablasCohorte
from sqlalchemy import func
from sqlmodel import Session, SQLModel, select
from persistance.repository import Repository
PROCEDENCIA = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
PRELIMINAR, FINAL, ERROR = "preliminary", "final", "entered-in-error"
# Lo que el kit entrega para guardar un armado: la fila del armado y sus hijas, sin `armado_id`.
Armado = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
T = TypeVar("T")
class RiesgoFueraDeCohorte(ValueError):
"""Se quiso guardar el riesgo de alguien que no es miembro del armado puntuado."""
class CohorteRepository(Repository):
"""Los armados de cohortes de un dominio y sus lotes de riesgos. Cada método, una sesión."""
def __init__(self, session_factory, cohortes: TablasCohorte):
super().__init__(session_factory, cohortes.CohorteArmado)
self.cohortes = cohortes
def armar(self, armado: Callable[[Session], Armado]) -> tuple[int, bool]:
"""Calcula el armado con `armado(sesion)` y lo guarda en esa sesión. Devuelve (`armado_id`, nuevo)."""
with self._session_factory() as sesion:
return guardar_armado_en(sesion, *armado(sesion))
def leer(self, leer: Callable[[Session], T]) -> T:
"""Lo que `leer(sesion)` lee de las cohortes, en una sesión (el marco de un armado para estimar). No escribe."""
with self._session_factory() as sesion:
return leer(sesion)
def guardar_lote(
self, armado_id: int, procedencia: dict, desenlace: str, riesgos, *, ahora: datetime | None = None
) -> tuple[int, bool]:
with self._session_factory() as sesion:
return guardar_lote_en(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
ahora=ahora)
def cambiar_estado(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
with self._session_factory() as sesion:
return cambiar_estado_en(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
def latest_build(self, url: str) -> int | None:
"""The most recent build of the cohort `url`, or `None` if it has none."""
build = self.cohortes.CohorteArmado
with self._session_factory() as sesion:
return sesion.exec(
select(build.armado_id).where(build.url == url).order_by(build.armado_id.desc()).limit(1)
).first()
def members(self, build_id: int) -> list["CohortMember"]:
"""The members of a build, ordered by `pac_id`; empty if the build doesn't exist."""
member = self.cohortes.CohorteMiembro
with self._session_factory() as sesion:
rows = sesion.exec(select(member).where(member.armado_id == build_id).order_by(member.pac_id)).all()
return [CohortMember(row.pac_id, row.fecha_indice, row.indice_fuente_tabla, row.indice_fuente_id)
for row in rows]
def build(self, build_id: int) -> "CohortBuild | None":
"""A build's lineage fields, or `None` if it doesn't exist."""
with self._session_factory() as sesion:
row = sesion.get(self.cohortes.CohorteArmado, build_id)
return None if row is None else _cohort_build(row)
def builds(self, url: str | None = None) -> list["CohortBuild"]:
"""Every build, newest first, with its lineage fields; only those of the cohort `url` if given."""
armado = self.cohortes.CohorteArmado
query = select(armado).order_by(armado.armado_id.desc())
if url is not None:
query = query.where(armado.url == url)
with self._session_factory() as sesion:
return [_cohort_build(row) for row in sesion.exec(query).all()]
def membership(self, pac_id: int, url: str) -> "PatientMembership | None":
"""The patient in the cohort's latest build: its version, index date and stored variables (`c`, `l`, `r`,
`pap_0`, `hpv_0`...); `None` if the cohort has no build or the patient isn't a member of the latest one."""
if (build_id := self.latest_build(url)) is None:
return None
member, variable = self.cohortes.CohorteMiembro, self.cohortes.CohorteVariable
with self._session_factory() as sesion:
row = sesion.get(member, (build_id, pac_id))
if row is None:
return None
build = sesion.get(self.cohortes.CohorteArmado, build_id)
values = sesion.exec(select(variable).where(variable.armado_id == build_id, variable.pac_id == pac_id)).all()
return PatientMembership(build_id, url, build.version, row.fecha_indice,
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
for v in values})
def current_risk(self, pac_id: int) -> "PatientRisk | None":
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
horizons whose latest version is `entered-in-error` are left out. `None` if no batch of the patient is
confirmed."""
e = self.cohortes.EvaluacionRiesgo
with self._session_factory() as sesion:
batches = sesion.exec(select(e.lote_id).where(e.pac_id == pac_id).distinct().order_by(e.lote_id.desc())).all()
for lote_id in batches:
latest = _latest_versions(sesion, e, lote_id)
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == lote_id, e.estado == FINAL).limit(1)).first():
continue
rows = sesion.exec(select(e).join(latest, _same_version(e, latest))
.where(e.lote_id == lote_id, e.pac_id == pac_id, e.estado != ERROR)
.order_by(e.horizonte_anios)).all()
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
return PatientRisk(lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado)
for r in rows])
return None
@dataclass(frozen=True)
class PatientMembership:
"""A patient in a cohort's latest build: which build, from which index date, and its stored variables."""
armado_id: int
url: str
version: str
fecha_indice: date
variables: dict
@dataclass(frozen=True)
class RiskHorizon:
"""A patient's risk at one horizon, at its latest version."""
horizonte_anios: float
probabilidad: float
ic_bajo: float | None
ic_alto: float | None
estado: str
@dataclass(frozen=True)
class PatientRisk:
"""A patient's risks in the current batch, with the model that produced them."""
lote_id: int
modelo_nombre: str
modelo_version: str
evaluado_en: datetime
estado_lote: str
horizontes: list[RiskHorizon]
def _latest_versions(sesion: Session, e, lote_id: int):
"""The latest version of each (patient, horizon) of a batch, as a subquery."""
return (select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
.where(e.lote_id == lote_id).group_by(e.pac_id, e.horizonte_anios).subquery())
def _same_version(e, latest):
return (e.pac_id == latest.c.pac_id) & (e.horizonte_anios == latest.c.horizonte_anios) & (e.version == latest.c.version)
@dataclass(frozen=True)
class CohortMember:
"""A member of a cohort build: who, from which index date, and the row of its index event."""
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
@dataclass(frozen=True)
class CohortBuild:
"""What identifies a cohort build in a model's lineage.
`datos_as_of` is the clinical cut-off; `conocida_hasta` is what had been loaded when the build was made
(`None`: everything loaded at the time). Reading the timeline again with both reproduces the build's input
once silver keeps its history.
"""
armado_id: int
url: str
version: str
huella: str
marco_sha: str
datos_as_of: date
conocida_hasta: datetime | None
n_miembros: int
armado_en: datetime
def _cohort_build(row: SQLModel) -> CohortBuild:
"""A `cohorte_armado` row as `CohortBuild`; `conocida_hasta` comes from its parameters."""
known_until = json.loads(row.parametros or "{}").get("conocida_hasta")
return CohortBuild(row.armado_id, row.url, row.version, row.huella, row.marco_sha, row.datos_as_of,
None if known_until is None else datetime.fromisoformat(known_until),
row.n_miembros, row.armado_en)
def guardar_armado_en(
sesion: Session, armado: SQLModel, exclusiones: Iterable[SQLModel], miembros: Iterable[SQLModel],
variables: Iterable[SQLModel],
) -> tuple[int, bool]:
"""Guarda un armado con su atrición, sus miembros y sus variables. Devuelve (`armado_id`, nuevo). Todo o nada.
Las hijas llegan sin `armado_id`: se lo pone este cuerpo. Si ya hay un armado
con la misma `huella` y el mismo `marco_sha`, no guarda y devuelve ese.
"""
modelo = type(armado)
previo = sesion.exec(
select(modelo).where(modelo.huella == armado.huella, modelo.marco_sha == armado.marco_sha)
).first()
if previo is not None:
return previo.armado_id, False
try:
sesion.add(armado)
sesion.flush()
armado_id = armado.armado_id
for grupo in (exclusiones, miembros, variables):
filas = list(grupo)
for fila in filas:
fila.armado_id = armado_id
sesion.add_all(filas)
sesion.flush() # los miembros antes que sus variables (llave foránea)
sesion.commit()
except Exception:
sesion.rollback()
raise
return armado_id, True
def guardar_lote_en(
sesion: Session,
armado_id: int,
procedencia: dict,
desenlace: str,
riesgos: list[tuple[int, float, float, float | None, float | None]],
*,
cohortes: TablasCohorte,
ahora: datetime | None = None,
) -> tuple[int, bool]:
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
No copia nada de MLflow: guarda sus llaves (`PROCEDENCIA`). Puntuar lo mismo
otra vez (mismo armado, modelo y riesgos) no duplica: la huella del lote ya está.
"""
faltan = [c for c in PROCEDENCIA if not procedencia.get(c)]
if faltan:
raise ValueError(f"La procedencia no trae {faltan}.")
miembro = cohortes.CohorteMiembro
miembros = set(sesion.exec(select(miembro.pac_id).where(miembro.armado_id == armado_id)))
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
if ajenos:
raise RiesgoFueraDeCohorte(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
huella = _sha_json({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROCEDENCIA},
"riesgos": sorted(riesgos)})
lote = cohortes.EvaluacionRiesgoLote
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
if previo is not None:
return previo.lote_id, False
momento = ahora or datetime.now(timezone.utc)
try:
fila = lote(armado_id=armado_id, desenlace=desenlace, evaluado_en=momento, n_evaluaciones=len(riesgos),
huella=huella, **{c: str(procedencia[c]) for c in PROCEDENCIA})
sesion.add(fila)
sesion.flush()
sesion.add_all(
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, horizonte_anios=float(h), probabilidad=float(p),
ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR, registrado_en=momento)
for pac, h, p, bajo, alto in riesgos
)
sesion.commit()
except Exception:
sesion.rollback()
raise
return fila.lote_id, True
def cambiar_estado_en(
sesion: Session, lote_id: int, estado: str, motivo: str, *, cohortes: TablasCohorte,
ahora: datetime | None = None,
) -> int:
"""Agrega una versión con `estado` a cada evaluación vigente del lote. Devuelve cuántas cambió."""
if estado not in (FINAL, ERROR):
raise ValueError(f"Estado desconocido: {estado!r} (se confirma a {FINAL!r} o se anula con {ERROR!r}).")
e = cohortes.EvaluacionRiesgo
ultima = (
select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
.where(e.lote_id == lote_id)
.group_by(e.pac_id, e.horizonte_anios)
.subquery()
)
vigentes = sesion.exec(
select(e).join(ultima, (e.pac_id == ultima.c.pac_id) & (e.horizonte_anios == ultima.c.horizonte_anios)
& (e.version == ultima.c.version)).where(e.lote_id == lote_id, e.estado != estado)
).all()
momento = ahora or datetime.now(timezone.utc)
try:
sesion.add_all(
e(lote_id=lote_id, pac_id=v.pac_id, horizonte_anios=v.horizonte_anios, probabilidad=v.probabilidad,
ic_bajo=v.ic_bajo, ic_alto=v.ic_alto, version=v.version + 1, estado=estado, motivo=motivo,
registrado_en=momento)
for v in vigentes
)
sesion.commit()
except Exception:
sesion.rollback()
raise
return len(vigentes)
def _sha_json(objeto) -> str:
"""sha256 del JSON canónico (el mismo de `indicadores_kit.oro.cohortes.definicion.sha_json`)."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()