73c5176482
Luis's recurrence scripts are kept as experiments. `models/cama/recurrence` holds the variable dictionary, the scenarios and the settings as data (`model.toml`), the writer of each cohort file as CaMa import files, the recode of the timeline into the per-patient frame and the analysis (Cramér's-V pruning, logistic terms and Bayesian-network parents per horizon, the scenario figures). The variable reader of the survival model is public so both share it. Includes the survival pipeline work this builds on. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
262 lines
11 KiB
Python
262 lines
11 KiB
Python
import json
|
|
import os
|
|
import sys
|
|
import warnings
|
|
import numpy as np
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
from sklearn.model_selection import train_test_split
|
|
from sklearn.metrics import roc_auc_score, roc_curve
|
|
from sklearn.calibration import calibration_curve
|
|
from lifelines import CoxPHFitter
|
|
from lifelines.utils import concordance_index
|
|
from pgmpy.estimators import HillClimbSearch, BDeu
|
|
from pgmpy.causal_discovery import ExpertKnowledge
|
|
import matplotlib
|
|
matplotlib.use("Agg")
|
|
import matplotlib.pyplot as plt
|
|
import networkx as nx
|
|
|
|
warnings.filterwarnings("ignore")
|
|
|
|
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
|
|
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
|
|
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
|
|
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
|
|
os.makedirs(DIR_INT, exist_ok=True)
|
|
os.makedirs(DIR_FIG, exist_ok=True)
|
|
|
|
SEMILLA = 42
|
|
N_BOOTSTRAP = int(os.environ.get("N_BOOTSTRAP", 100 if COHORTE == "metabric" else 40))
|
|
BDEU_ESS = 10
|
|
MAX_PADRES = 6
|
|
ALFA_IN, ALFA_OUT, ALFA_PREFILTRO = 0.10, 0.15, 0.10
|
|
|
|
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
|
|
covariables = meta["covariables"]
|
|
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
|
|
|
|
TIER_DEMOGRAFIA = ["Edad", "Estado_menopausico"]
|
|
TIER_TUMOR = ["Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
|
|
"Receptor_progesterona", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Cluster_integrativo", "Lateralidad",
|
|
"Ki67", "Subtipo_clinico", "Estadio_clinico"]
|
|
TIER_TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
|
|
|
|
|
|
# ---- funciones ----
|
|
def orden_temporal(cols):
|
|
tiers = [[c for c in t if c in cols] for t in (TIER_DEMOGRAFIA, TIER_TUMOR, TIER_TRATAMIENTO, ["outcome"])]
|
|
sin = [c for c in cols if c not in sum(tiers, [])]
|
|
return ([sin] if sin else []) + [t for t in tiers if t]
|
|
|
|
|
|
def codificar(df):
|
|
X = pd.get_dummies(df[covariables], drop_first=True).astype(float)
|
|
return X.loc[:, X.nunique() > 1]
|
|
|
|
|
|
def ajuste_logit(y, X):
|
|
try:
|
|
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def prefiltro(X, y):
|
|
keep = []
|
|
for c in X.columns:
|
|
m = ajuste_logit(y, X[[c]])
|
|
if m is not None and m.pvalues[c] < ALFA_PREFILTRO:
|
|
keep.append(c)
|
|
return keep
|
|
|
|
|
|
def stepwise(X, y):
|
|
incl = []
|
|
for _ in range(200):
|
|
cambio = False
|
|
mejor, p_mejor = None, ALFA_IN
|
|
for c in [c for c in X.columns if c not in incl]:
|
|
m = ajuste_logit(y, X[incl + [c]])
|
|
if m is not None and m.pvalues[c] < p_mejor:
|
|
mejor, p_mejor = c, m.pvalues[c]
|
|
if mejor is not None:
|
|
incl.append(mejor)
|
|
cambio = True
|
|
if incl:
|
|
m = ajuste_logit(y, X[incl])
|
|
if m is not None:
|
|
p = m.pvalues.drop("const")
|
|
if p.max() > ALFA_OUT:
|
|
incl.remove(p.idxmax())
|
|
cambio = True
|
|
if not cambio:
|
|
break
|
|
return incl
|
|
|
|
|
|
def lr_completo(df_train, df_test):
|
|
Xall = codificar(pd.concat([df_train, df_test]))
|
|
Xtr, Xte = Xall.loc[df_train.index], Xall.loc[df_test.index]
|
|
Xtr = Xtr.loc[:, Xtr.nunique() > 1]
|
|
Xte = Xte[Xtr.columns]
|
|
cand = prefiltro(Xtr, df_train["y"])
|
|
sel = stepwise(Xtr[cand], df_train["y"]) if cand else []
|
|
if not sel:
|
|
return None, [], np.full(len(df_test), df_train["y"].mean())
|
|
m = ajuste_logit(df_train["y"], Xtr[sel])
|
|
return m, sel, m.predict(sm.add_constant(Xte[sel], has_constant="add")).values
|
|
|
|
|
|
def variable_de(t):
|
|
return next((c for c in sorted(covariables, key=len, reverse=True) if t.startswith(c + "_")), t)
|
|
|
|
|
|
def padres_outcome(train, candidatos):
|
|
sc = BDeu(train, equivalent_sample_size=BDEU_ESS)
|
|
padres, actual = [], sc.local_score("outcome", [])
|
|
while len(padres) < MAX_PADRES:
|
|
mejor, ganancia = None, 0
|
|
for c in candidatos:
|
|
if c in padres:
|
|
continue
|
|
g = sc.local_score("outcome", padres + [c]) - actual
|
|
if g > ganancia:
|
|
mejor, ganancia = c, g
|
|
if mejor is None:
|
|
break
|
|
padres.append(mejor)
|
|
actual += ganancia
|
|
return padres
|
|
|
|
|
|
def prob_hbn(train, test, padres):
|
|
if not padres:
|
|
return np.full(len(test), (train["outcome"] == "1").mean())
|
|
q = int(np.prod([train[p].nunique() for p in padres]))
|
|
alpha = BDEU_ESS / (2 * q)
|
|
g = train.groupby(padres)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
|
p_glob = (train["outcome"] == "1").mean()
|
|
tabla = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
|
|
return np.array([tabla.get(k, p_glob) for k in map(tuple, test[padres].values)])
|
|
|
|
|
|
def tabla_bn(df):
|
|
t = df[covariables].astype(str).copy()
|
|
t["outcome"] = df["y"].astype(int).astype(str)
|
|
return t
|
|
|
|
|
|
def cohorte_a_horizonte(H):
|
|
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
|
|
libre = coh_total["tiempo_meses"] > H
|
|
d = coh_total[recurre | libre].reset_index(drop=True)
|
|
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
|
|
return d
|
|
|
|
|
|
# ---- Cox de referencia (tiempo completo) ----
|
|
cox_df = pd.get_dummies(coh_total[["tiempo_meses", "evento"] + covariables], columns=covariables, drop_first=True).astype(float)
|
|
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
|
|
ctr, cte = train_test_split(cox_df, test_size=0.3, random_state=SEMILLA, stratify=cox_df["evento"])
|
|
_ok = [c for c in ctr.columns if c in ("tiempo_meses", "evento") or 10 <= ctr[c].sum() <= len(ctr) - 10]
|
|
ctr, cte = ctr[_ok], cte[_ok]
|
|
cox = CoxPHFitter(penalizer=0.05).fit(ctr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
|
|
c_index = concordance_index(cte["tiempo_meses"], -cox.predict_partial_hazard(cte), cte["evento"])
|
|
|
|
|
|
# ---- modelos por horizonte ----
|
|
filas_auc, modelos_json, curvas = [], {}, {}
|
|
for H in HORIZONTES:
|
|
coh = cohorte_a_horizonte(H)
|
|
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=SEMILLA, stratify=coh["y"])
|
|
tr, te = coh.loc[tr_idx], coh.loc[te_idx]
|
|
|
|
modelo_lr, sel_lr, p_lr = lr_completo(tr, te)
|
|
auc_lr = roc_auc_score(te["y"], p_lr)
|
|
|
|
bn_tr, bn_te = tabla_bn(tr), tabla_bn(te)
|
|
padres = padres_outcome(bn_tr, covariables)
|
|
p_hbn = prob_hbn(bn_tr, bn_te, padres)
|
|
auc_hbn = roc_auc_score(te["y"], p_hbn)
|
|
|
|
if H == max(HORIZONTES):
|
|
expert = ExpertKnowledge(temporal_order=orden_temporal(list(bn_tr.columns)))
|
|
estructura = HillClimbSearch(bn_tr).estimate(scoring_method=BDeu(bn_tr, equivalent_sample_size=BDEU_ESS), max_indegree=4,
|
|
expert_knowledge=expert, show_progress=False)
|
|
arcos_red = [(u, v) for u, v in estructura.edges() if u != "outcome" and v != "outcome"] + [(p, "outcome") for p in padres]
|
|
G = nx.DiGraph(arcos_red)
|
|
plt.figure(figsize=(10, 7))
|
|
nx.draw(G, nx.spring_layout(G, seed=SEMILLA, k=0.9), with_labels=True, node_color="lightblue", node_size=2200, font_size=7, arrowsize=14)
|
|
plt.title(f"Estructura de la red bayesiana ({COHORTE}, {H} meses)")
|
|
plt.tight_layout()
|
|
plt.savefig(f"{DIR_FIG}/hbn_estructura_{COHORTE}.png", dpi=150)
|
|
plt.close()
|
|
|
|
rng = np.random.default_rng(SEMILLA)
|
|
aucs, cuenta_lr, cuenta_hbn, n_lr, n_hbn = [], {}, {}, 0, 0
|
|
for b in range(N_BOOTSTRAP):
|
|
db = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
|
|
try:
|
|
dtr, dte = train_test_split(db, test_size=0.3, random_state=SEMILLA + b, stratify=db["y"])
|
|
m, sel, p = lr_completo(dtr, dte)
|
|
a_lr = roc_auc_score(dte["y"], p)
|
|
btr, bte = tabla_bn(dtr), tabla_bn(dte)
|
|
pa = padres_outcome(btr, covariables)
|
|
a_h = roc_auc_score(dte["y"], prob_hbn(btr, bte, pa))
|
|
except Exception:
|
|
continue
|
|
aucs.append((a_lr, a_h))
|
|
n_lr += 1
|
|
n_hbn += 1
|
|
if m is not None:
|
|
for v in {variable_de(t) for t in m.params.drop("const").index}:
|
|
cuenta_lr[v] = cuenta_lr.get(v, 0) + 1
|
|
for v in pa:
|
|
cuenta_hbn[v] = cuenta_hbn.get(v, 0) + 1
|
|
aucs = np.array(aucs)
|
|
for j, (nombre, auc_int) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
|
|
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": H, "modelo": nombre, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
|
|
"AUC_validacion_interna": auc_int, "AUC_bootstrap_medio": aucs[:, j].mean(),
|
|
"AUC_bootstrap_IC95_inf": np.percentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.percentile(aucs[:, j], 97.5),
|
|
"replicas_bootstrap": len(aucs)})
|
|
ci = modelo_lr.conf_int()
|
|
modelos_json[str(H)] = {"terminos_lr": list(sel_lr), "padres_hbn": padres, "n_replicas": n_lr,
|
|
"seleccion_lr": cuenta_lr, "seleccion_hbn": cuenta_hbn,
|
|
"arcos_hbn": [list(a) for a in (arcos_red if H == max(HORIZONTES) else [(p, "outcome") for p in padres])]}
|
|
curvas[H] = (te["y"].values, p_lr, p_hbn)
|
|
|
|
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(coh_total),
|
|
"recurrencias": int(coh_total["evento"].sum()), "AUC_validacion_interna": c_index})
|
|
json.dump(modelos_json, open(f"{DIR_INT}/modelos{SFX}.json", "w", encoding="utf8"), indent=1, ensure_ascii=False)
|
|
|
|
# ---- consolidado de AUC (un solo archivo con las dos cohortes) ----
|
|
nuevo = pd.DataFrame(filas_auc)
|
|
destino = "./auc_recurrencia.csv"
|
|
if os.path.exists(destino):
|
|
previo = pd.read_csv(destino)
|
|
previo = previo[~((previo["cohorte"] == COHORTE) & (previo["horizonte_meses"].astype(str).isin([str(h) for h in HORIZONTES] + ["completo"])))]
|
|
nuevo = pd.concat([previo, nuevo], ignore_index=True)
|
|
nuevo.round(4).to_csv(destino, index=False)
|
|
|
|
# ---- figuras: ROC y calibracion (un panel por horizonte) ----
|
|
for nombre_fig, tipo in [("roc", "roc"), ("calibracion", "cal")]:
|
|
fig, axs = plt.subplots(1, len(HORIZONTES), figsize=(5.2 * len(HORIZONTES), 5), squeeze=False)
|
|
for ax, H in zip(axs[0], HORIZONTES):
|
|
y, pl, ph = curvas[H]
|
|
for nom, p in [("LR", pl), ("HBN", ph)]:
|
|
if tipo == "roc":
|
|
f, t, _ = roc_curve(y, p)
|
|
ax.plot(f, t, label=f"{nom} (AUC {roc_auc_score(y, p):.3f})")
|
|
else:
|
|
fr, mp = calibration_curve(y, p, n_bins=8, strategy="quantile")
|
|
ax.plot(mp, fr, "o-", label=nom)
|
|
ax.plot([0, 1], [0, 1], "k:")
|
|
ax.set_title(f"{COHORTE}: {H} meses")
|
|
ax.set_xlabel("1 - especificidad" if tipo == "roc" else "probabilidad predicha de recurrencia")
|
|
ax.set_ylabel("sensibilidad" if tipo == "roc" else "frecuencia observada")
|
|
ax.legend()
|
|
fig.tight_layout()
|
|
fig.savefig(f"{DIR_FIG}/{nombre_fig}_{COHORTE}.png", dpi=150)
|
|
plt.close(fig)
|