160 lines
10 KiB
Python
160 lines
10 KiB
Python
"""CaMa's recurrence analysis as a scenario: the dataflow from the cohort's patients loaded from METABRIC and SCAN-B (the
|
|
`fuente` of each, indexed at her first invasive biopsy) to the registered model, its results and its routines. Each node is one
|
|
stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery (`models.dags.training.train`)
|
|
saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the dashboard shows are in
|
|
`population["recurrencia"]`.
|
|
"""
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
|
|
from models.cama.recurrence import calculator as calc
|
|
from models.cama.recurrence import factors as fac
|
|
from models.cama.recurrence import modeling
|
|
from models.cama.recurrence import cohort as timeline
|
|
from models.cama.recurrence.prep import Prepared, finish
|
|
|
|
COHORTS = ("metabric", "scanb")
|
|
|
|
|
|
def dictionary() -> dict:
|
|
"""The variables, cohorts and scenarios of `cohorts.toml`."""
|
|
return timeline.load()
|
|
|
|
|
|
def prepared(cohort: pd.DataFrame, dictionary: dict, recurrence: dict) -> dict[str, Prepared]:
|
|
"""Each cohort's patients as one table of categories with its covariates (`cohort.recode`, then `prep`)."""
|
|
fixed = ["paciente", "tiempo_meses", "evento"]
|
|
return {name: finish(timeline.recode(cohort, dictionary, name), fixed, dictionary["cohorts"][name]["treatment"],
|
|
recurrence["v_max"]) for name in COHORTS}
|
|
|
|
|
|
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
|
|
"""The LR and the HBN at each horizon of each cohort, with their AUC (`modeling`)."""
|
|
base = {k: recurrence[k] for k in ("seed", "bdeu_ess", "max_parents", "alpha_in", "alpha_out", "alpha_prefilter")}
|
|
return {name: modeling.fit_cohort(name, prepared[name], list(recurrence["horizons"]),
|
|
modeling.FitSettings(n_bootstrap=recurrence[f"n_bootstrap_{name}"], **base)) for name in COHORTS}
|
|
|
|
|
|
def factors_table(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> pd.DataFrame:
|
|
"""The classified risk factors of both cohorts at each horizon (`factors`)."""
|
|
return pd.concat([fac.risk_factors(n, prepared[n], fits[n], list(recurrence["horizons"]), recurrence["alpha"], recurrence["freq_min"])
|
|
for n in COHORTS], ignore_index=True)
|
|
|
|
|
|
def calculators(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict[str, tuple[list[dict], pd.DataFrame]]:
|
|
"""The figure of each scenario of each cohort and the table of their points (`calculator`)."""
|
|
s = calc.CalculatorSettings(seed=recurrence["seed"], n_boot=recurrence["n_boot_calc"], min_events=recurrence["min_events"],
|
|
cap_months=recurrence["cap_months"], bdeu_ess=recurrence["bdeu_ess"], ks_seconds=recurrence["ks_seconds"])
|
|
return {n: calc.calculator(n, prepared[n], fits[n], list(recurrence["horizons"]), s) for n in COHORTS}
|
|
|
|
|
|
def scenario_factors(prepared: dict[str, Prepared], factors_table: pd.DataFrame, recurrence: dict) -> dict[str, pd.DataFrame]:
|
|
"""The risk factors that make up each scenario (`calculator.scenario_risk_factors`): the summary of both cohorts."""
|
|
summaries = [calc.scenario_risk_factors(n, prepared[n], factors_table, list(recurrence["horizons"]))[1] for n in COHORTS]
|
|
return {"resumen": pd.concat(summaries, ignore_index=True)}
|
|
|
|
|
|
class RecurrenceModel:
|
|
"""The recurrence models of one cohort fitted on all of it: at each horizon the logistic regression on the terms the
|
|
stepwise chose and the Bayesian network's table over the parents it chose. `predict_proba(X)` is the recurrence probability
|
|
at each horizon, the mean of the two models; `X` has the cohort's covariates as categories (the unknown, "Desconocido")."""
|
|
|
|
def __init__(self, cohort: str, horizons: list[int], covariates: list[str], tables: dict):
|
|
self.cohort, self.horizons, self.covariates, self.tables_ = cohort, horizons, covariates, tables
|
|
|
|
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
|
|
out = np.zeros((len(X), len(self.horizons)))
|
|
for j, H in enumerate(self.horizons):
|
|
t = self.tables_[str(H)]
|
|
p_lr = np.full(len(X), t["lr_prior"])
|
|
if t["lr_terms"]:
|
|
dummies = pd.get_dummies(X[self.covariates].astype(str)).astype(float).reindex(columns=t["lr_terms"], fill_value=0.0)
|
|
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + dummies.values @ np.asarray(t["lr_coefficients"]))))
|
|
parents, cpt = t["hbn_parents"], t["hbn_cpt"]
|
|
p_hbn = np.full(len(X), t["hbn_prior"]) if not parents else np.array(
|
|
[cpt.get(tuple(row), t["hbn_prior"]) for row in X[parents].astype(str).values])
|
|
out[:, j] = (p_lr + p_hbn) / 2
|
|
return out
|
|
|
|
|
|
def _tables(prepared: Prepared, fitted: modeling.CohortModels, horizons: list[int], bdeu_ess: int) -> dict:
|
|
"""What `RecurrenceModel` keeps from the fit on the whole cohort, per horizon."""
|
|
f = modeling._Fitter(prepared, modeling.FitSettings(bdeu_ess=bdeu_ess))
|
|
tables = {}
|
|
for H in horizons:
|
|
coh = f.at_horizon(H)
|
|
mh = fitted.models[str(H)]
|
|
terms, parents = mh["terminos_lr"], mh["padres_hbn"]
|
|
entry = {"lr_prior": float(coh["y"].mean()), "lr_terms": terms, "lr_constant": 0.0, "lr_coefficients": [],
|
|
"hbn_parents": parents, "hbn_prior": float(coh["y"].mean()), "hbn_cpt": {}}
|
|
if terms:
|
|
X = f.encode(coh)[terms]
|
|
model = f.logit(coh["y"], X)
|
|
if model is not None:
|
|
entry["lr_constant"], entry["lr_coefficients"] = float(model.params["const"]), [float(model.params[t]) for t in terms]
|
|
if parents:
|
|
table = f.bn_table(coh)
|
|
alpha = bdeu_ess / (2 * int(np.prod([table[p].nunique() for p in parents])))
|
|
g = table.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
|
entry["hbn_cpt"] = {(k if isinstance(k, tuple) else (k,)): float((r.n1 + alpha) / (r.n + 2 * alpha)) for k, r in g.iterrows()}
|
|
tables[str(H)] = entry
|
|
return tables
|
|
|
|
|
|
def fitted_model(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> RecurrenceModel:
|
|
"""The model that is saved: METABRIC's, the larger of the two cohorts' external references for the covariates both share."""
|
|
return RecurrenceModel("metabric", list(recurrence["horizons"]), prepared["metabric"].covariates,
|
|
_tables(prepared["metabric"], fits["metabric"], list(recurrence["horizons"]), recurrence["bdeu_ess"]))
|
|
|
|
|
|
def metrics(fits: dict[str, modeling.CohortModels]) -> dict:
|
|
"""Numbers only: each cohort's AUC by internal validation and by bootstrap, per horizon and model, and its Cox C-index."""
|
|
found = {}
|
|
for name, fit in fits.items():
|
|
for _, r in fit.auc.iterrows():
|
|
if r["horizonte_meses"] == "completo":
|
|
found[f"{name}.c_index_cox"] = float(r["AUC_validacion_interna"])
|
|
continue
|
|
tag = f"{name}.auc_{r['modelo']}_{int(r['horizonte_meses'])}m"
|
|
found[tag] = float(r["AUC_validacion_interna"])
|
|
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
|
|
return found
|
|
|
|
|
|
def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict:
|
|
"""The five routine records the registry's promotion reads (ML-01a)."""
|
|
return {
|
|
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
|
|
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
|
|
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "pacientes cargadas de METABRIC y SCAN-B (`fuente`)"},
|
|
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
|
|
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.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": recurrence["horizons"], "alfa_entrada": recurrence["alpha_in"], "alfa_salida": recurrence["alpha_out"],
|
|
"ess_bdeu": recurrence["bdeu_ess"], "maximo_de_padres": recurrence["max_parents"], "cox_penalizado": 0.05,
|
|
"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": {"metabric": recurrence["n_bootstrap_metabric"], "scanb": recurrence["n_bootstrap_scanb"], "calculadora": recurrence["n_boot_calc"]},
|
|
"eventos_minimos_por_escenario": recurrence["min_events"]},
|
|
}
|
|
|
|
|
|
def population(calculators: dict, fits: dict[str, modeling.CohortModels], factors_table: pd.DataFrame, scenario_factors: dict,
|
|
recurrence: dict) -> dict:
|
|
"""What the version publishes under `analisis/`: `recurrencia`, the figure of each scenario of each cohort the dashboard
|
|
draws, and `recurrencia_desarrollo`, the tables behind them."""
|
|
figures = [r for n in COHORTS for r in calculators[n][0]]
|
|
points = pd.concat([calculators[n][1] for n in COHORTS], ignore_index=True)
|
|
auc = pd.concat([fits[n].auc for n in COHORTS], ignore_index=True)
|
|
|
|
def table(df: pd.DataFrame) -> dict:
|
|
df = df.replace([np.inf, -np.inf], np.nan).astype(object)
|
|
return {"columnas": [str(c) for c in df.columns], "filas": df.where(df.notna(), None).to_dict("records")}
|
|
|
|
return {"recurrencia": {"version": 1, "horizons_months": list(recurrence["horizons"]), "escenarios": figures},
|
|
"recurrencia_desarrollo": {"version": 1, "tablas": {"auc": table(auc), "factores_riesgo": table(factors_table),
|
|
"calculadora": table(points), "escenarios_resumen": table(scenario_factors["resumen"])}}}
|