Files
models/models/cama/recurrence/reports.py
T

162 lines
5.9 KiB
Python

"""What the governance page draws, as JSON: the development tables (AUC, risk factors,
calculator points, scenario summaries) and the scenarios' figures, as v1 published them in
`analisis/recurrencia_desarrollo.json` and `analisis/recurrencia.json`, and the five routine
records (`rutinas/`)."""
import numpy as np
import pandas as pd
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
from models.cama.recurrence.modeling import (
ALPHA_IN,
ALPHA_OUT,
COX_PENALIZER,
ESS,
HORIZONS,
MAX_PARENTS,
CohortFit,
)
VERSION = 1
AUC_COLUMNS = [
"cohorte",
"horizonte_meses",
"modelo",
"n_modelo",
"recurrencias",
"AUC_validacion_interna",
"AUC_bootstrap_medio",
"AUC_bootstrap_IC95_inf",
"AUC_bootstrap_IC95_sup",
"replicas_bootstrap",
]
def table(rows, columns=None) -> dict:
"""Columns and records; NaN and infinities are null."""
frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object)
return {
"columnas": [str(c) for c in frame.columns],
"filas": frame.where(frame.notna(), None).to_dict("records"),
}
def auc_rows(fitted: CohortFit) -> list[dict]:
"""Per horizon and model, the AUC on the internal split and over the bootstrap
replicates (mean, 2.5 and 97.5 percentiles); then the Cox model's C-index."""
source, rows = fitted.cohort.source, []
for h, hz in fitted.horizons.items():
for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))):
aucs = hz.aucs[:, j]
boot = (
[np.nanmean(aucs), *np.nanpercentile(aucs, [2.5, 97.5])]
if len(aucs)
else [None] * 3
)
rows.append(
{
"cohorte": source,
"horizonte_meses": h,
"modelo": name,
"n_modelo": hz.n,
"recurrencias": hz.events,
"AUC_validacion_interna": internal,
**dict(zip(AUC_COLUMNS[6:9], boot, strict=True)),
"replicas_bootstrap": len(aucs) if len(aucs) else None,
}
)
frame = fitted.cohort.frame
rows.append(
{
"cohorte": source,
"horizonte_meses": "completo",
"modelo": "Cox penalizado (C-index)",
"n_modelo": len(frame),
"recurrencias": int(frame["evento"].sum()),
"AUC_validacion_interna": fitted.c_index,
}
)
return [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in rows]
def metrics(auc: list[dict]) -> dict[str, float]:
"""v1's metric names: `{cohort}.auc_{LR|HBN}_{H}m` (internal split), with `_bootstrap`
(the replicates' mean), and `{cohort}.c_index_cox`."""
found = {}
for r in auc:
if r["horizonte_meses"] == "completo":
found[f"{r['cohorte']}.c_index_cox"] = float(r["AUC_validacion_interna"])
continue
tag = f"{r['cohorte']}.auc_{r['modelo']}_{r['horizonte_meses']}m"
found[tag] = float(r["AUC_validacion_interna"])
if r.get("AUC_bootstrap_medio") is not None:
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
return found
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"""The five routine records a promotion reads."""
return {
"MUESTREO": {
"cohortes": {
s: {
"pacientes": len(c.frame),
"recaidas": int(c.frame["evento"].sum()),
"covariables": len(c.covariates),
"eliminadas_por_colinealidad": c.eliminated,
}
for s, c in cohorts.items()
},
**next(iter(cohorts.values())).sampling,
},
"DATOS_FALTANTES": {
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
"no se imputa ni se descarta",
"desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
},
"METODO_ANALITICO": {
"modelos": "regresión logística con selección stepwise y red bayesiana con padres "
"del desenlace por BDeu, uno por horizonte",
"horizontes_meses": list(HORIZONS),
"alfa_entrada": ALPHA_IN,
"alfa_salida": ALPHA_OUT,
"ess_bdeu": ESS,
"maximo_de_padres": MAX_PARENTS,
"cox_penalizado": COX_PENALIZER,
"combinacion": "promedio de la LR y la HBN",
},
"BALANCE_CLASES": {
"aplica": False,
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres "
"de ella después; no se rebalancea",
},
"CONFIANZA_SALIDA": {
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
"bootstrap",
"replicas": {
**{s: n_bootstrap.get(s, 0) for s in cohorts},
"calculadora": RESAMPLES,
},
"eventos_minimos_por_escenario": MIN_EVENTS,
},
}
def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict:
"""`recurrencia_desarrollo`: the tables behind the figures."""
return {
"version": VERSION,
"tablas": {
"auc": table(auc, AUC_COLUMNS),
"factores_riesgo": table(factors),
"calculadora": table(pd.DataFrame(points).round(4)),
"escenarios_resumen": table(summary),
},
}
def figures(records: list[dict]) -> dict:
"""`recurrencia`: each scenario's curves and calculator points."""
return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records}