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>
159 lines
7.1 KiB
Python
159 lines
7.1 KiB
Python
import sys
|
|
import os
|
|
import json
|
|
import numpy as np
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
|
|
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 = "./intermedios_recurrencia"
|
|
ALFA = 0.05
|
|
FREQ_MIN = 0.80
|
|
|
|
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
|
|
variables = meta["covariables"]
|
|
tratamiento = meta["tratamiento"]
|
|
intrinsecas = [v for v in variables if v not in tratamiento]
|
|
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
|
|
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in variables})
|
|
|
|
|
|
# ---- funciones ----
|
|
def bh(p):
|
|
p = np.asarray(p, float)
|
|
orden = np.argsort(p)
|
|
aj = np.empty_like(p)
|
|
m = len(p)
|
|
prev = 1.0
|
|
for rango, i in zip(range(m, 0, -1), orden[::-1]):
|
|
prev = min(prev, p[i] * m / rango)
|
|
aj[i] = prev
|
|
return aj
|
|
|
|
|
|
def variable_de(termino, vars_modelo):
|
|
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
|
|
|
|
|
|
def km_en(m, e, h):
|
|
T = int(m.max()) + 2
|
|
d = np.bincount(m[e], minlength=T)
|
|
c = np.bincount(m[~e], minlength=T)
|
|
en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
|
with np.errstate(divide="ignore", invalid="ignore"):
|
|
q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0)
|
|
v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0)
|
|
h = min(h, T - 1)
|
|
S = np.prod(q[:h + 1])
|
|
return S, S * np.sqrt(np.sum(v[:h + 1]))
|
|
|
|
|
|
def procesar_horizonte(H):
|
|
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
|
|
libre = coh_total["tiempo_meses"] > H
|
|
datos_km = coh_total.copy()
|
|
coh = coh_total[recurre | libre].reset_index(drop=True)
|
|
datos = coh[variables].astype(str)
|
|
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
|
|
meses = np.floor(np.minimum(datos_km["tiempo_meses"].values, H + 1)).astype(int)
|
|
evento = ((datos_km["evento"] == 1) & (datos_km["tiempo_meses"] <= H)).values
|
|
datos_km = datos_km[variables].astype(str)
|
|
|
|
def referencia(v):
|
|
return datos[v].value_counts().idxmax()
|
|
|
|
def ajustar_or(vars_modelo):
|
|
X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float)
|
|
refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo}
|
|
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
|
|
X = X.loc[:, X.nunique() > 1]
|
|
X = X.loc[:, ~X.T.duplicated()]
|
|
modelo = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
|
ic = modelo.conf_int()
|
|
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(modelo.params[X.columns].values),
|
|
"IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values),
|
|
"p": modelo.pvalues[X.columns].values})
|
|
|
|
def delta_s(v, cat, ref):
|
|
a = (datos_km[v] == cat).values
|
|
b = (datos_km[v] == ref).values
|
|
Sa, ea = km_en(meses[a], evento[a], H)
|
|
Sb, eb = km_en(meses[b], evento[b], H)
|
|
d = Sa - Sb
|
|
es = np.sqrt(ea ** 2 + eb ** 2)
|
|
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
|
|
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
|
|
|
|
def completar(t, vars_modelo):
|
|
t = t.copy()
|
|
t["variable"] = [variable_de(x, vars_modelo) for x in t["termino"]]
|
|
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
|
|
t["referencia"] = [referencia(v) for v in t["variable"]]
|
|
t["p_ajustado_BH"] = bh(t["p"])
|
|
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
|
|
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
|
|
|
|
tab = completar(ajustar_or(intrinsecas), intrinsecas)
|
|
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
|
|
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
|
|
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
|
|
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
|
|
|
|
mh = modelos.get(str(H), {})
|
|
n_rep = mh.get("n_replicas", 0)
|
|
sel = mh.get("seleccion_lr", {})
|
|
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: sel.get(v, 0) / n_rep if n_rep else np.nan)
|
|
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
|
manta = set(mh.get("padres_hbn", []))
|
|
tab["en_manta_markov"] = tab["variable"].isin(manta)
|
|
tab["c3_manta_markov"] = tab["en_manta_markov"]
|
|
|
|
crit = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
|
tab["criterios_cumplidos"] = tab[crit].astype(bool).sum(axis=1)
|
|
|
|
def clasificar(r):
|
|
if r["categoria"] == "Desconocido":
|
|
return "no aplica (categoria desconocida)"
|
|
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
|
|
return f"{r['direccion']} robusto"
|
|
if r["criterios_cumplidos"] >= 2:
|
|
return f"{r['direccion']} sugerente"
|
|
return "no concluyente"
|
|
|
|
tab["clasificacion"] = tab.apply(clasificar, axis=1)
|
|
tab["tipo"] = "factor de riesgo"
|
|
|
|
if tratamiento:
|
|
tr = ajustar_or(intrinsecas + tratamiento)
|
|
tr["_v"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
|
|
tr = tr[tr["_v"].isin(tratamiento) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
|
|
tr = completar(tr, tratamiento)
|
|
tr["tipo"] = "tratamiento"
|
|
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
|
tab = pd.concat([tab, tr], ignore_index=True)
|
|
|
|
tab["cohorte"] = COHORTE
|
|
tab["horizonte_meses"] = H
|
|
return tab
|
|
|
|
|
|
columnas = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
|
|
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
|
|
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
|
|
"criterios_cumplidos", "clasificacion"]
|
|
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
|
|
|
|
nuevo = pd.concat([procesar_horizonte(H) for H in HORIZONTES], ignore_index=True)
|
|
nuevo["_t"] = (nuevo["tipo"] != "factor de riesgo").astype(int)
|
|
nuevo["_o"] = nuevo["clasificacion"].map(orden).fillna(5)
|
|
nuevo = nuevo.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[columnas]
|
|
|
|
destino = "./factores_riesgo_recurrencia.csv"
|
|
if os.path.exists(destino):
|
|
previo = pd.read_csv(destino)
|
|
previo = previo[previo["cohorte"] != COHORTE]
|
|
nuevo = pd.concat([previo, nuevo], ignore_index=True)
|
|
nuevo.round(4).to_csv(destino, index=False)
|