Keep the original SEER survival scripts as experiments (not packaged)

This commit is contained in:
2026-11-20 13:40:06 -06:00
parent 7b2eae2782
commit 76d6b96409
7 changed files with 4087 additions and 0 deletions
@@ -0,0 +1,443 @@
import matplotlib
matplotlib.use("Agg")
import os, json, itertools
import numpy as np
import pandas as pd
INPUT_CSV = "./dataframe_recodificado.csv"
OUTPUT_CSV = "./dataframe_depurado.csv"
OUT_DIR = "./depuracion_resultados_1"
EXCLUDE = ["Outcome_cat"] # nunca se analiza ni se toca
AUTO_EXTRA = ["Age_group", "Tumor_group"] # se incluyen si existen
EXTRA_COLS = []
PROTEGIDAS = [] # p. ej. ["Estadio_cat"]: nunca se eliminan
PREFERIR = ["Tumor_group", "Age_group"] # en un empate/duplicada, gana la que esté aquí (son las discretizaciones propias del proyecto)
DROP_RAW_SOURCES = True # también quita la columna cruda de SEER de la variable eliminada (evita que el balanceo la reintroduzca por palabra clave)
MAPEO_JSON = "./mapeo_columnas_recodificadas.json"
UNKNOWN_LABEL = "Desconocido"
DUP_U = 0.90 # paso A
U_REDUND = 0.80 # paso B
GVIF_DROP = 2.24 # paso C: GVIF^(1/2gl) (equivale a VIF 5)
MAX_ITER_GVIF = 20
os.makedirs(OUT_DIR, exist_ok=True)
df_raw = pd.read_csv(INPUT_CSV, dtype=str)
cols = [c for c in df_raw.columns if c.endswith("_cat") and c not in EXCLUDE]
for c in AUTO_EXTRA + EXTRA_COLS:
if c in df_raw.columns and c not in cols and c not in EXCLUDE:
cols.append(c)
df = df_raw[cols].fillna(UNKNOWN_LABEL)
cols = [c for c in cols if df[c].nunique() >= 2]
df = df[cols]
def theil_u_matrix(d, columnas):
U = pd.DataFrame(np.nan, index=columnas, columns=columnas)
H = {}
for c in columnas:
p = d[c].value_counts(normalize=True).values
H[c] = float(-(p * np.log(p)).sum())
for a, b in itertools.combinations(columnas, 2):
pxy = pd.crosstab(d[a], d[b]).values.astype(float)
pxy /= pxy.sum()
nz = pxy[pxy > 0]
hxy = float(-(nz * np.log(nz)).sum())
mi = H[a] + H[b] - hxy
U.loc[a, b] = mi / H[a] if H[a] > 0 else np.nan
U.loc[b, a] = mi / H[b] if H[b] > 0 else np.nan
return U
def design(d, columnas):
bloques = {}
for c in columnas:
ind = pd.get_dummies(d[c], prefix=c, prefix_sep="=").astype(float)
ind = ind.drop(columns=ind.sum().idxmax())
ind = ind.loc[:, ind.std() > 0]
if ind.shape[1] > 0:
bloques[c] = ind
X = pd.concat(bloques.values(), axis=1)
return X, bloques
def gvif_table(d, columnas):
X, bloques = design(d, columnas)
R = np.corrcoef(X.values, rowvar=False)
pos = {n: i for i, n in enumerate(X.columns)}
s, ld = np.linalg.slogdet(R)
if not (s > 0 and np.isfinite(ld) and ld > -30):
cand = []
for c, b in bloques.items():
otros = [x for x in X.columns if x not in b.columns]
A = np.column_stack([X[otros].values, np.ones(len(X))])
for x in b.columns:
y = X[x].values
coef, *_ = np.linalg.lstsq(A, y, rcond=None)
r2 = 1 - ((y - A @ coef) ** 2).sum() / ((y - y.mean()) ** 2).sum()
if r2 >= 0.9999:
cand.append((b.shape[1], c)); break
return None, sorted(cand)
filas = []
for c, b in bloques.items():
idx = [pos[n] for n in b.columns]
resto = [i for i in range(len(pos)) if i not in set(idx)]
s1, l1 = np.linalg.slogdet(R[np.ix_(idx, idx)])
s2, l2 = np.linalg.slogdet(R[np.ix_(resto, resto)]) if resto else (1, 0.0)
gv = float(np.exp(l1 + l2 - ld))
filas.append({"variable": c, "gl": len(idx), "GVIF": gv,
"GVIF_ajustado": gv ** (1 / (2 * len(idx)))})
return pd.DataFrame(filas).sort_values("GVIF_ajustado", ascending=False).reset_index(drop=True), []
import itertools, json, datetime
from scipy.cluster.hierarchy import linkage, cophenet, fcluster
from scipy.spatial.distance import squareform
# ===================== PARÁMETROS DE LA CALIBRACIÓN (independientes de los datos) =====================
UMBRALES_AUTO = False # True: aplica las sugerencias a DUP_U / U_REDUND / GVIF_DROP / clustering
N_MAX_CAL = 300_000 # si hay más filas, se calibra sobre una submuestra reproducible
NULL_PERM = 100 # permutaciones para el piso por azar de U
K_AZAR = 5 # U_REDUND debe ser >= K_AZAR x (U máximo por azar)
U_CONVENCIONAL = 0.80 # valor de respaldo si los datos no permiten calibrar
U_GAP_DESDE = 0.70 # se buscan brechas cuyo borde superior sea >= este U
U_GAP_MIN_BRECHA = 0.10 # brecha mínima para considerarla "natural"
U_RANGO_PLAUSIBLE = (0.60, 0.95) # límites del umbral sugerido
VIF_CORTE = 5 # 5 (R2=0.80) o 10 (R2=0.90)
R_GRANDE = 0.5 # Cohen (1988): |phi| 0.1 pequeño, 0.3 mediano, 0.5 grande
MIN_N_CAT = 30 # categorías con menos pacientes se excluyen del clustering
MAX_CAT_CLUSTER = 400 # tope de columnas (categorías) en la matriz del clustering
CLUSTER_DIST = "signed" # "signed": d = 1-r | "abs": d = 1-|r|
SEMILLA_CAL = 0
GVIF_GRID = sorted({round(1.5, 2), 2.0, round(float(np.sqrt(VIF_CORTE)), 2), 2.5, round(float(np.sqrt(10)), 2)})
CLUSTER_METODO = "average" # se recalcula abajo
PAR_R_MIN = R_GRANDE
CLUSTER_CORTE = round(1 - R_GRANDE, 2)
rng_cal = np.random.default_rng(SEMILLA_CAL)
REPORTE = {"fecha": datetime.datetime.now().isoformat(timespec="seconds"), "advertencias": [], "parametros": {
"NULL_PERM": NULL_PERM, "K_AZAR": K_AZAR, "U_CONVENCIONAL": U_CONVENCIONAL, "U_GAP_DESDE": U_GAP_DESDE,
"U_GAP_MIN_BRECHA": U_GAP_MIN_BRECHA, "U_RANGO_PLAUSIBLE": list(U_RANGO_PLAUSIBLE), "VIF_CORTE": VIF_CORTE,
"R_GRANDE": R_GRANDE, "MIN_N_CAT": MIN_N_CAT, "SEMILLA": SEMILLA_CAL}}
def _aviso(msg):
REPORTE["advertencias"].append(msg)
# ===================== preparación y diagnóstico de los datos =====================
if len(cols) < 2:
raise ValueError("La calibración necesita al menos 2 variables categóricas.")
df_cal = df if len(df) <= N_MAX_CAL else df.sample(N_MAX_CAL, random_state=SEMILLA_CAL)
CODES = {c: pd.factorize(df_cal[c])[0] for c in cols}
KCAT = {c: int(df_cal[c].nunique()) for c in cols}
n_cal = len(df_cal)
celdas_med = float(np.median([n_cal / (KCAT[a] * KCAT[b]) for a, b in itertools.combinations(cols, 2)]))
if n_cal < 1000: _aviso(f"n pequeño ({n_cal}): U está sesgado hacia arriba; el piso por azar lo compensa, pero interpreta con cautela.")
if celdas_med < 5: _aviso(f"tablas de contingencia dispersas (mediana {celdas_med:.1f} pacientes/celda < 5): U se infla; confía más en el piso por azar que en el valor absoluto.")
if len(cols) < 4: _aviso("pocas variables (< 4): el GVIF y la brecha natural son poco informativos.")
if max(KCAT.values()) > 30: _aviso(f"variable con {max(KCAT.values())} categorías: considera agruparlas antes de depurar.")
REPORTE["datos"] = {"n": int(len(df)), "n_calibracion": int(n_cal), "n_variables": len(cols), "categorias_por_variable": KCAT,
"pacientes_por_celda_mediana": celdas_med}
# ===================== 1. U de Theil: pares, exactitud y piso por azar =====================
def _h(p):
p = p[p > 0]; return float(-(p * np.log(p)).sum())
def info_par(cx, cy, kx, ky):
j = np.bincount(cx * ky + cy, minlength=kx * ky).reshape(kx, ky).astype(float)
n = j.sum(); px = j.sum(1) / n; py = j.sum(0) / n
hxy = _h((j / n).ravel()); hx = _h(px); hy = _h(py)
return dict(hx=hx, hy=hy, mi=hx + hy - hxy, acc_x_dado_y=j.max(0).sum() / n, acc_y_dado_x=j.max(1).sum() / n,
base_x=px.max(), base_y=py.max())
filas, techo = [], []
for a, b in itertools.combinations(cols, 2):
ip = info_par(CODES[a], CODES[b], KCAT[a], KCAT[b])
mi_null = np.array([info_par(CODES[a], rng_cal.permutation(CODES[b]), KCAT[a], KCAT[b])["mi"] for _ in range(NULL_PERM)])
for x, y, hx, acc, base in [(a, b, ip["hx"], ip["acc_x_dado_y"], ip["base_x"]), (b, a, ip["hy"], ip["acc_y_dado_x"], ip["base_y"])]:
u = ip["mi"] / hx if hx > 0 else np.nan
u_null = mi_null.max() / hx if hx > 0 else np.nan
filas.append({"X": x, "dado_Y": y, "U(X|Y)": u, "U_azar_max": u_null, "exactitud_X_desde_Y": acc, "exactitud_base_X": base})
techo.append(u_null)
PARES_U = pd.DataFrame(filas).sort_values("U(X|Y)", ascending=False).reset_index(drop=True)
PARES_U["brecha_al_siguiente"] = PARES_U["U(X|Y)"] - PARES_U["U(X|Y)"].shift(-1)
techo_azar = float(np.nanmax(techo))
PARES_U.to_csv(f"{OUT_DIR}/calibracion_U_pares.csv", index=False)
# ---- regla de sugerencia para U_REDUND (piso por azar + brecha natural + respaldo convencional)
def sugerir_U(pares_u, techo_azar, gap_desde=None, gap_min=None):
gap_desde = U_GAP_DESDE if gap_desde is None else gap_desde
gap_min = U_GAP_MIN_BRECHA if gap_min is None else gap_min
v = np.sort(pares_u["U(X|Y)"].dropna().round(4).unique())[::-1]
out = {"metodo": "convencional", "brecha": None, "borde_sup": None, "borde_inf": None, "confianza": "revisar"}
mejor = None
for i in range(len(v) - 1):
if v[i] >= gap_desde and (mejor is None or v[i] - v[i + 1] > mejor[0]):
mejor = (v[i] - v[i + 1], v[i], v[i + 1])
if mejor is not None and mejor[0] >= gap_min:
mid = float(np.clip((mejor[1] + mejor[2]) / 2, *U_RANGO_PLAUSIBLE))
out.update(metodo="brecha natural", U=mid, brecha=round(float(mejor[0]), 3), borde_sup=round(float(mejor[1]), 3),
borde_inf=round(float(mejor[2]), 3), confianza="alta")
else:
out["U"] = U_CONVENCIONAL
out["motivo"] = ("no hay pares con U >= %.2f" % gap_desde) if mejor is None else ("la mayor brecha (%.3f) < %.2f" % (mejor[0], gap_min))
piso = K_AZAR * techo_azar
if out["U"] < piso:
out["U"] = float(min(piso, 0.99)); out["metodo"] += " + piso por azar"; out["confianza"] = "revisar"
out["U"] = round(float(out["U"]), 2)
return out
SUG_U = sugerir_U(PARES_U, techo_azar)
# ===================== 2. Sensibilidad: ¿qué variables se eliminan al mover cada umbral, y con qué regla? =====================
_pct_unk = {c: float((df_cal[c] == UNKNOWN_LABEL).mean()) for c in cols}
_ncat = {c: int(df_cal[c].nunique()) for c in cols}
_orden = {c: i for i, c in enumerate(cols)}
def _perdedora(a, b):
if a in PROTEGIDAS and b in PROTEGIDAS: return None
if a in PROTEGIDAS: return b, a
if b in PROTEGIDAS: return a, b
if a in PREFERIR and b not in PREFERIR: return b, a
if b in PREFERIR and a not in PREFERIR: return a, b
k = lambda c: (_pct_unk[c], _ncat[c], _orden[c])
return (a, b) if k(a) > k(b) else (b, a)
_cacheU, _cacheG = {}, {}
def _Umat(cols_t):
if cols_t not in _cacheU:
M_ = pd.DataFrame(np.nan, index=list(cols_t), columns=list(cols_t))
for a, b in itertools.combinations(cols_t, 2):
ip = info_par(CODES[a], CODES[b], KCAT[a], KCAT[b])
M_.loc[a, b] = ip["mi"] / ip["hx"] if ip["hx"] > 0 else np.nan
M_.loc[b, a] = ip["mi"] / ip["hy"] if ip["hy"] > 0 else np.nan
_cacheU[cols_t] = M_
return _cacheU[cols_t]
def _Gtab(cols_t):
if cols_t not in _cacheG: _cacheG[cols_t] = gvif_table(df_cal, list(cols_t))
return _cacheG[cols_t]
_chk = theil_u_matrix(df_cal, cols); _fast = _Umat(tuple(cols))
assert np.allclose(_chk.values.astype(float), _fast.loc[cols, cols].values.astype(float), equal_nan=True, atol=1e-9), "U rápida != theil_u_matrix"
def depurar_con(dup_u, u_redund, gvif_drop):
# Reproduce A, B y C con otros umbrales. Devuelve ({variable: paso}, activas).
activas, out = list(cols), {}
U = _Umat(tuple(activas)) # A
for a, b in itertools.combinations(list(activas), 2):
if a not in activas or b not in activas: continue
if U.loc[a, b] >= dup_u and U.loc[b, a] >= dup_u:
r = _perdedora(a, b)
if r: activas.remove(r[0]); out[r[0]] = "A"
U = _Umat(tuple(activas)); cand = [] # B
for x in activas:
for y in activas:
if x != y and U.loc[x, y] >= u_redund and U.loc[y, x] < u_redund: cand.append((U.loc[x, y], x, y))
for u, x, y in sorted(cand, reverse=True):
if x in activas and y in activas and x not in PROTEGIDAS and x not in PREFERIR:
activas.remove(x); out[x] = "B"
for _ in range(MAX_ITER_GVIF): # C
if len(activas) < 3: break
tabla, exactas = _Gtab(tuple(activas))
if tabla is None:
ex = [c for _, c in exactas if c not in PROTEGIDAS]
if not ex: break
activas.remove(ex[0]); out[ex[0]] = "C"; continue
cd = tabla[(tabla["GVIF_ajustado"] >= gvif_drop) & (~tabla["variable"].isin(PROTEGIDAS))]
if cd.empty: break
v_ = cd.iloc[0]["variable"]; activas.remove(v_); out[v_] = "C"
return out, activas
def _etq(d): return ", ".join(f"{k} [{p}]" for k, p in sorted(d.items())) or "(nada)"
base_out, base_act = depurar_con(DUP_U, U_REDUND, GVIF_DROP)
# decisión del umbral sugerido y su estabilidad
dup_sug = round(min(max(0.90, SUG_U["U"] + 0.05), 0.99), 2)
out_sug, _ = depurar_con(dup_sug, SUG_U["U"], GVIF_DROP)
mismo = set(out_sug) == set(base_out)
SUG_U["misma_decision_que_config"] = bool(mismo)
if not mismo and SUG_U["confianza"] == "alta": SUG_U["confianza"] = "revisar"
if not mismo: _aviso("los umbrales sugeridos producen un conjunto distinto de variables eliminadas: revisa los barridos A-C antes de aplicarlos.")
# ---- D) Barrido de los parámetros de la REGLA de brecha: U_GAP_DESDE y U_GAP_MIN_BRECHA son CONVENCIONES (no salen de los datos).
# Se verifica si cambiarlos modifica el umbral sugerido o las variables que se eliminan.
GAP_DESDE_GRID = [0.50, 0.60, 0.70, 0.80, 0.90]
GAP_MIN_GRID = [0.02, 0.05, 0.10, 0.15, 0.20, 0.30]
_filas_gap = []
for gd in GAP_DESDE_GRID:
for gm in GAP_MIN_GRID:
s_ = sugerir_U(PARES_U, techo_azar, gd, gm)
dup_s = round(min(max(0.90, s_["U"] + 0.05), 0.99), 2)
o_, _ = depurar_con(dup_s, s_["U"], GVIF_DROP)
_filas_gap.append({"U_GAP_DESDE": gd, "U_GAP_MIN_BRECHA": gm, "U_REDUND sugerido": s_["U"], "método": s_["metodo"],
"misma decisión": set(o_) == set(base_out), "elimina [regla]": _etq(o_)})
SENS_GAP = pd.DataFrame(_filas_gap)
_frac = float(SENS_GAP["misma decisión"].mean())
_umin, _umax = float(SENS_GAP["U_REDUND sugerido"].min()), float(SENS_GAP["U_REDUND sugerido"].max())
_dist = SENS_GAP[~SENS_GAP["misma decisión"]]
if len(_dist):
_aviso(f"la decisión depende de U_GAP_DESDE / U_GAP_MIN_BRECHA en {len(_dist)} de {len(SENS_GAP)} combinaciones: son convenciones; revisa el barrido D antes de fijar el umbral.")
REPORTE["sensibilidad_regla_brecha"] = {"grilla_U_GAP_DESDE": GAP_DESDE_GRID, "grilla_U_GAP_MIN_BRECHA": GAP_MIN_GRID,
"proporcion_misma_decision": _frac, "U_sugerido_min": _umin, "U_sugerido_max": _umax}
# ===================== 3. GVIF: equivalencia con VIF y R^2, y margen =====================
GVIF_DROP_SUG = round(float(np.sqrt(VIF_CORTE)), 2)
eq = pd.DataFrame({"GVIF ajustado (umbral)": GVIF_GRID})
eq["VIF = GVIF_aj^2"] = eq["GVIF ajustado (umbral)"] ** 2
eq["R^2 de la variable con las demás"] = 1 - 1 / eq["VIF = GVIF_aj^2"]
tab_k, _ = _Gtab(tuple(base_act))
margen_g = None
if tab_k is not None and len(tab_k):
tab_k = tab_k.copy(); tab_k["margen_al_umbral"] = GVIF_DROP - tab_k["GVIF_ajustado"]
margen_g = float(tab_k["margen_al_umbral"].min())
if margen_g < 0.15: _aviso("alguna variable conservada está muy cerca del umbral de GVIF: la decisión es sensible al corte.")
# ===================== 4. Clustering: método de enlace (cofenética) y corte (Cohen) =====================
def _cat_matrix(d, columnas, min_n):
X = pd.get_dummies(d[columnas], prefix_sep="=", dtype=np.float32); s = X.sum()
X = X.loc[:, (s >= min_n) & (s <= len(X) - min_n)]
if X.shape[1] > MAX_CAT_CLUSTER:
X = X[X.sum().sort_values(ascending=False).index[:MAX_CAT_CLUSTER]]
_aviso(f"demasiadas categorías para el clustering: se usan las {MAX_CAT_CLUSTER} más frecuentes.")
return X
min_n_eff = MIN_N_CAT
_X = _cat_matrix(df_cal, cols, min_n_eff)
if _X.shape[1] < 6:
min_n_eff = max(5, int(0.005 * n_cal)); _X = _cat_matrix(df_cal, cols, min_n_eff)
_aviso(f"muy pocas categorías con >= {MIN_N_CAT} pacientes: se baja el mínimo a {min_n_eff} para el clustering.")
CLUSTER_OK = _X.shape[1] >= 4
metodo_sug, coph, CLUSTER_CORTE_SIL, tab_corte = CLUSTER_METODO, {}, None, pd.DataFrame()
if not CLUSTER_OK:
_aviso("no hay suficientes categorías para calibrar el clustering; se mantienen los valores por convención.")
else:
_nom = list(_X.columns); _var = np.array([c.split("=", 1)[0] for c in _nom])
_V = _X.values.astype(np.float32); _V -= _V.mean(0); _cov = _V.T @ _V; _sd = np.sqrt(np.diag(_cov)); _R = (_cov / np.outer(_sd, _sd)).astype(float)
_D = 1 - _R if CLUSTER_DIST == "signed" else 1 - np.abs(_R)
_D = np.clip((_D + _D.T) / 2, 0, None); np.fill_diagonal(_D, 0); _cond = squareform(_D, checks=False)
for m_ in ["single", "complete", "average", "weighted"]:
coph[m_] = float(cophenet(linkage(_cond, method=m_), _cond)[0])
metodo_sug = max(coph, key=coph.get)
try:
from sklearn.metrics import silhouette_score; _hay_sil = True
except Exception:
_hay_sil = False
Zc = linkage(_cond, method=metodo_sug); filas = []
for t_ in np.round(np.arange(0.30, 1.01, 0.05), 2):
lab = fcluster(Zc, t=float(t_), criterion="distance"); ng = len(set(lab))
multi = sum(1 for g in set(lab) if len(set(_var[lab == g])) >= 2)
sil = float(silhouette_score(_D, lab, metric="precomputed")) if _hay_sil and 2 <= ng <= len(lab) - 1 else np.nan
filas.append({"corte (dist.)": t_, "r medio exigido": round(1 - t_, 2), "n_grupos": ng, "grupos_multivariable": multi, "silueta": round(sil, 3) if sil == sil else np.nan})
tab_corte = pd.DataFrame(filas)
if tab_corte["silueta"].notna().any(): CLUSTER_CORTE_SIL = float(tab_corte.loc[tab_corte["silueta"].idxmax(), "corte (dist.)"])
tab_corte.to_csv(f"{OUT_DIR}/calibracion_clustering_corte.csv", index=False)
# ===================== 5. Resumen, decisión y reporte JSON =====================
resumen = pd.DataFrame([
{"parámetro": "U_REDUND", "configurado": U_REDUND, "sugerido": SUG_U["U"], "criterio": SUG_U["metodo"], "confianza": SUG_U["confianza"]},
{"parámetro": "DUP_U", "configurado": DUP_U, "sugerido": dup_sug, "criterio": "max(0.90, U_REDUND+0.05)", "confianza": SUG_U["confianza"]},
{"parámetro": "GVIF_DROP", "configurado": GVIF_DROP, "sugerido": GVIF_DROP_SUG, "criterio": f"sqrt(VIF {VIF_CORTE}) (R2={1-1/VIF_CORTE:.2f})",
"confianza": "alta" if (margen_g is None or margen_g >= 0.15) else "revisar"},
{"parámetro": "CLUSTER_METODO", "configurado": CLUSTER_METODO, "sugerido": metodo_sug, "criterio": "máx. correlación cofenética", "confianza": "alta" if CLUSTER_OK else "revisar"},
{"parámetro": "CLUSTER_CORTE", "configurado": CLUSTER_CORTE, "sugerido": round(1 - R_GRANDE, 2), "criterio": f"Cohen: r medio >= {R_GRANDE}", "confianza": "alta"},
{"parámetro": "PAR_R_MIN", "configurado": PAR_R_MIN, "sugerido": R_GRANDE, "criterio": "Cohen: efecto grande", "confianza": "alta"}])
if UMBRALES_AUTO:
U_REDUND, DUP_U, GVIF_DROP, CLUSTER_METODO = SUG_U["U"], dup_sug, GVIF_DROP_SUG, metodo_sug
CLUSTER_CORTE = round(1 - R_GRANDE, 2); PAR_R_MIN = R_GRANDE
def _jsonable(o):
if isinstance(o, (np.floating,)): return float(o)
if isinstance(o, (np.integer,)): return int(o)
if isinstance(o, (set, tuple)): return list(o)
return str(o)
REPORTE.update({"piso_azar_U": techo_azar, "sugerencia_U": SUG_U, "resumen": resumen.to_dict(orient="records"),
"umbrales_en_uso": {"DUP_U": DUP_U, "U_REDUND": U_REDUND, "GVIF_DROP": GVIF_DROP, "CLUSTER_METODO": CLUSTER_METODO,
"CLUSTER_CORTE": CLUSTER_CORTE, "PAR_R_MIN": PAR_R_MIN, "AUTO": bool(UMBRALES_AUTO)},
"eliminadas_con_config": base_out, "correlacion_cofenetica": coph})
with open(f"{OUT_DIR}/calibracion_umbrales.json", "w", encoding="utf-8") as fh:
json.dump(REPORTE, fh, ensure_ascii=False, indent=2, default=_jsonable)
eliminadas = [] # (variable, paso, motivo, a_favor_de)
activas = list(cols)
pct_unk = {c: float((df[c] == UNKNOWN_LABEL).mean()) for c in cols}
ncat = {c: int(df[c].nunique()) for c in cols}
orden = {c: i for i, c in enumerate(cols)}
def quitar(var, paso, motivo, favor):
activas.remove(var)
eliminadas.append({"variable": var, "paso": paso, "motivo": motivo, "a_favor_de": favor})
def elegir_perdedora(a, b):
if a in PROTEGIDAS and b in PROTEGIDAS: return None
if a in PROTEGIDAS: return b, a
if b in PROTEGIDAS: return a, b
if a in PREFERIR and b not in PREFERIR: return b, a
if b in PREFERIR and a not in PREFERIR: return a, b
clave = lambda c: (pct_unk[c], ncat[c], orden[c])
return (a, b) if clave(a) > clave(b) else (b, a)
# ---------------- PASO A: duplicadas ----------------
U = theil_u_matrix(df, activas)
for a, b in itertools.combinations(list(activas), 2):
if a not in activas or b not in activas: continue
if U.loc[a, b] >= DUP_U and U.loc[b, a] >= DUP_U:
r = elegir_perdedora(a, b)
if r:
quitar(r[0], "A duplicada", f"U({a}|{b})={U.loc[a,b]:.2f}, U({b}|{a})={U.loc[b,a]:.2f}", r[1])
# ---------------- PASO B: derivadas ----------------
U = theil_u_matrix(df, activas)
cand = []
for x in activas:
for y in activas:
if x != y and U.loc[x, y] >= U_REDUND and U.loc[y, x] < U_REDUND:
cand.append((U.loc[x, y], x, y))
for u, x, y in sorted(cand, reverse=True):
if x in activas and y in activas and x not in PROTEGIDAS and x not in PREFERIR:
quitar(x, "B derivada", f"U({x}|{y})={u:.2f} vs U({y}|{x})={U.loc[y,x]:.2f}", y)
for it in range(MAX_ITER_GVIF):
if len(activas) < 3: break
tabla, exactas = gvif_table(df, activas)
if tabla is None:
exactas = [c for _, c in exactas if c not in PROTEGIDAS]
if not exactas: break
quitar(exactas[0], "C anidada exacta", "combinación exacta de otras variables", "(el resto)")
continue
cand = tabla[(tabla["GVIF_ajustado"] >= GVIF_DROP) & (~tabla["variable"].isin(PROTEGIDAS))]
if cand.empty: break
v = cand.iloc[0]
quitar(v["variable"], "C GVIF", f"GVIF ajustado={v['GVIF_ajustado']:.2f} >= {GVIF_DROP}", "(el resto)")
conservadas = list(activas)
rep = pd.DataFrame(eliminadas, columns=["variable", "paso", "motivo", "a_favor_de"])
# ---------------- Verificación final ----------------
tabla, exactas = gvif_table(df, conservadas)
U_fin = theil_u_matrix(df, conservadas)
# ---------------- Guardar ----------------
a_quitar = [c for c in rep["variable"]]
crudas = []
if DROP_RAW_SOURCES and os.path.exists(MAPEO_JSON):
with open(MAPEO_JSON, encoding="utf-8") as f:
_map = json.load(f)
crudas = [_map[v] for v in a_quitar if v in _map and _map[v] in df_raw.columns]
out = df_raw.drop(columns=a_quitar + crudas)
out.to_csv(OUTPUT_CSV, index=False)
rep.to_csv(f"{OUT_DIR}/variables_eliminadas.csv", index=False)
with open(f"{OUT_DIR}/variables_conservadas.json", "w", encoding="utf-8") as f:
json.dump({"entrada": INPUT_CSV, "conservadas": conservadas, "eliminadas": a_quitar, "crudas_eliminadas": crudas,
"umbrales": {"DUP_U": DUP_U, "U_REDUND": U_REDUND, "GVIF_DROP": GVIF_DROP}},
f, ensure_ascii=False, indent=2)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,31 @@
import numpy as np
import pandas as pd
RANDOM_STATE = 42
rng = np.random.default_rng(RANDOM_STATE)
CSV_PATH = "./dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
df = pd.read_csv(CSV_PATH, dtype=str)
n = len(df)
N_BOOTSTRAP = 200
bootstrap_indices = np.empty((N_BOOTSTRAP, n), dtype=np.int64)
for b in range(N_BOOTSTRAP):
bootstrap_indices[b] = rng.integers(0, n, size=n)
import json
np.save("./bootstrap_indices.npy", bootstrap_indices)
metadata = {
"source_csv": CSV_PATH,
"n_filas": int(n),
"n_bootstrap": int(N_BOOTSTRAP),
"random_state": int(RANDOM_STATE),
}
with open("./bootstrap_metadata.json", "w") as f:
json.dump(metadata, f, indent=2)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,828 @@
import matplotlib
matplotlib.use("Agg")
import os
os.environ.setdefault("TQDM_DISABLE", "1")
import sys, subprocess, time, re, warnings
import numpy as np, pandas as pd
warnings.filterwarnings("ignore")
try:
from tqdm.auto import tqdm
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "tqdm"]); from tqdm.auto import tqdm
INPUT_CSV = "./dataframe_depurado.csv" # salida de 03 (cohorte completa; debe traer meses de seguimiento y estado vital)
EDAD_MODO = "categorizada" # cómo entra la edad a la LR: "categorizada" | "continua" (lineal) | "continua_cuadratica". La edad numérica es el punto medio del grupo de 5 años de SEER.
# (la HBN solo usa variables discretas: con la edad continua, la HBN no incluye la edad)
INCLUIR_EDAD = True # agrega la edad agrupada (Edad_cat) a las covariables si no hay ya una columna de edad categórica
CORTES_EDAD = [45, 60, 75] # cortes de la edad agrupada
HBN_PADRES_FIJOS = ["Estadio", "Tipo_histologico", "Tratamiento_quirurgico", "Quimioterapia", "Radioterapia"] # padres del desenlace en la HBN ya aprendida en 06 (se buscan por palabra clave entre las covariables); None = aprenderlos aquí (BDeu)
HBN_EDAD_PADRE = True # True: agrega la edad agrupada como padre del desenlace en la HBN (decisión de experto / conocimiento previo; el algoritmo de 06 no la eligió). False: solo los padres de HBN_PADRES_FIJOS
HBN_PADRES = "fijos" # "fijos": los padres de la HBN se aprenden una vez y se mantienen en el bootstrap (IC más estable) | "reaprender": se buscan de nuevo en cada réplica
COVARIABLES = None # None = todas las columnas que terminan en "_cat" (menos el desenlace); o una lista explícita de columnas
HORIZONTES = [6, 12, 18] # meses en los que se muestran los puntos de LR y HBN
CENSURA_MODELOS = "riesgo" # "riesgo": un modelo por intervalo (0-6, 6-12, 12-18) que usa todo el seguimiento | "ipcw": pondera | "excluir": descarta las vivas con seguimiento < h (definición del proyecto)
COMBINAR = True # un solo indicador LR+HBN (combinación por intervalo con pesos de apilamiento fuera de muestra); solo con CENSURA_MODELOS = "riesgo"
MOSTRAR_INDIVIDUALES = False # además del combinado, dibuja LR y HBN por separado
STACK_FOLDS = 5 # pliegues de la validación cruzada que decide los pesos
STACK_SHRINK = 20 # contracción hacia 50/50 con pocas muertes: lambda = STACK_SHRINK / (STACK_SHRINK + muertes del intervalo)
DIAGNOSTICO = True # imprime los puntos con los tres tratamientos de la censura (sin bootstrap) junto a Kaplan-Meier
B_BOOT = 100 # réplicas bootstrap para el IC de LR y HBN (200 = más fino, más lento)
SEMILLA = 42
HBN_ESS = 1000 # tamaño de muestra equivalente del prior BDeu
HBN_MAX_PADRES = 5 # máximo de padres del desenlace en la HBN
K_IDENT = "clasico" # k fijo del Weibull fraccional: "clasico" = k del Weibull clásico | o un número
CURVAS = "ajustada" # "ajustada": KM y Weibull fraccional estandarizados por las mismas covariables que LR/HBN (Cox) | "cruda": KM y Weibull sin ajustar
PASO_AJUSTE = 3 # meses por intervalo de la curva ajustada (más corto = más fina y más lenta)
MOSTRAR_KM_CRUDO = True # dibuja además, en gris fino, el KM sin ajustar como referencia
YLIM_PRINCIPAL = None # p. ej. (0.94, 1.0) para hacer zoom en el eje y de la figura principal; None = automático
INSET_ZOOM = False # recuadro con zoom a los primeros INSET_MESES meses (donde están los puntos de LR y HBN)
INSET_MESES = 18 # tope del panel de zoom (último horizonte)
TOPE_MESES = 24 # el análisis de las curvas llega solo hasta este mes: el seguimiento se trunca ahí (muertes posteriores y seguimiento restante cuentan como vivas/censuradas en TOPE_MESES). None = sin tope
MESES_MAX = TOPE_MESES or 60 # hasta dónde se dibuja el eje de tiempo
SUF = "" if EDAD_MODO == "categorizada" else f"_edad_{EDAD_MODO}" # sufijo de los archivos de salida para no sobrescribir
TAG = "" if EDAD_MODO == "categorizada" else f" [edad {EDAD_MODO.replace('_', ' ')}]"
SALIDA_PNG = f"./curva_supervivencia_KM_KS_LR_HBN{SUF}.png"
SALIDA_CSV = f"./curva_supervivencia_puntos_LR_HBN{SUF}.csv"
df = pd.read_csv(INPUT_CSV, dtype=str)
def find_col(df, keywords, exclude=()):
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords) and not any(e in d for e in exclude):
return col
return None
COL_MESES = find_col(df, ["survival months"])
COL_VITAL = find_col(df, ["vital status"])
assert COL_MESES and COL_VITAL, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
df["meses"] = pd.to_numeric(df[COL_MESES], errors="coerce")
df["evento"] = df[COL_VITAL].astype(str).str.lower().str.contains("dead")
df = df[df["meses"].notna()].reset_index(drop=True)
df["meses_int"] = df["meses"].astype(int)
if TOPE_MESES: # truncar el seguimiento en TOPE_MESES: solo cuentan las muertes ocurridas antes del tope
df["evento"] = df["evento"] & (df["meses_int"] < TOPE_MESES)
df["meses_int"] = np.minimum(df["meses_int"], TOPE_MESES)
def _edad(v):
m_ = re.search(r"\d+", str(v)); return float(m_.group()) if m_ else np.nan
_cands = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
COL_EDAD = sorted(_cands, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0] if _cands else None
df["_edad"] = df[COL_EDAD].map(_edad) if COL_EDAD else np.nan
_hay_edad_cat = any(re.search(r"(^|_)age(_|$)|edad", c.lower()) for c in df.columns if c.endswith("_cat")) # (no confundir con "Stage")
if INCLUIR_EDAD and not _hay_edad_cat:
if df["_edad"].notna().mean() > 0.5:
_b = [-np.inf] + list(CORTES_EDAD) + [np.inf]
_l = [f"<{CORTES_EDAD[0]}"] + [f"{a}-{b-1}" for a, b in zip(CORTES_EDAD[:-1], CORTES_EDAD[1:])] + [f"≥{CORTES_EDAD[-1]}"]
df["Edad_cat"] = pd.cut(df["_edad"], _b, right=False, labels=_l).astype(object)
if COVARIABLES is None:
COVARIABLES = [c for c in df.columns if c.endswith("_cat") and "outcome" not in c.lower()]
elif INCLUIR_EDAD and "Edad_cat" in df.columns and "Edad_cat" not in COVARIABLES:
COVARIABLES = list(COVARIABLES) + ["Edad_cat"]
def _edad_media(v):
n_ = [float(x) for x in re.findall(r"\d+", str(v))]
if not n_: return np.nan
return n_[0] + 2.5 if "+" in str(v) else float(np.mean(n_[:2]))
_ed = df[COL_EDAD].map(_edad_media).astype(float) if COL_EDAD else pd.Series(np.nan, index=df.index)
df["_edad_z"] = ((_ed - _ed.mean()) / _ed.std()).fillna(0.0); df["_edad_cuad"] = df["_edad_z"] ** 2
COLS_NUM = []
if EDAD_MODO != "categorizada":
assert _ed.notna().mean() > 0.5, "EDAD_MODO continua: no se pudo leer la edad numérica de la columna de edad."
COVARIABLES = [c for c in COVARIABLES if not re.search(r"(^|_)age(_|$)|edad", c.lower())] # la edad categórica sale de las covariables
COLS_NUM = ["_edad_z"] + (["_edad_cuad"] if EDAD_MODO == "continua_cuadratica" else [])
def construir_X_dum():
M_ = pd.get_dummies(df[COVARIABLES], drop_first=True).values.astype(np.float32) # referencia = primera categoría
return np.column_stack([M_, df[COLS_NUM].values.astype(np.float32)]) if COLS_NUM else M_
assert COVARIABLES, "No hay covariables: define COVARIABLES con los nombres de columna."
for c in COVARIABLES:
df[c] = df[c].fillna("NA").astype(str).str.strip()
import sys, subprocess, numpy as np
try:
import mpmath as mp
except ImportError: # el kernel de Jupyter no lo trae: se instala solo
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"])
import mpmath as mp
from functools import lru_cache
from scipy.special import gammaln
@lru_cache(maxsize=256)
def _coefs(rho, m, l, N, dps):
mp.mp.dps = dps
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
c = [mp.mpf(1)]
for i in range(N - 1):
c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1)))
return tuple(c)
def _log_terms(az, rho, m, l, N):
i = np.arange(N - 1)
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))])
n = np.arange(N)
with np.errstate(divide="ignore"):
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
return lt
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l)
out = np.full(z.shape, np.nan)
az = np.abs(z)
N = 400
lt = _log_terms(az, rho, m, l, N)
lmax, llast = lt.max(axis=1), lt[:, -1]
zero = az == 0
out[zero] = 1.0
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
if okf.any():
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
terms[:, 0] = 1.0
out[okf] = terms.sum(axis=1)
rest = np.where(~zero & ~okf)[0]
if rest.size:
with np.errstate(over="ignore"):
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
est = np.maximum(est, lmax[rest])
use = rest[est <= logmax_cap]
if use.size:
est_u = est[est <= logmax_cap]
dps = 30 + int(est_u.max() / 2.3) + 10
zmax = float(az[use].max())
with np.errstate(over="ignore"):
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
N2 = max(N2, 60)
while True:
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
mp.mp.dps = dps
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
if last < tol or N2 >= nmax:
break
N2 *= 2
if last < tol:
cr = list(c)[::-1]
for j in use:
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
return out
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
tau1 = lam if tau1 is None else tau1
tau2 = lam if tau2 is None else tau2
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full_like(t, np.nan)
m = s/beta + 1; l = s/beta
pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1)))
with np.errstate(divide="ignore", invalid="ignore"):
z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1)
z = np.where(t > 0, z, 0.0)
res = np.ones_like(t)
pos = t > 0
if pos.any():
res[pos] = kilbas_saigo(z[pos], beta, m, l)
return np.clip(res, 0.0, 1.0)
def S_weibull(t, k, lam):
t = np.asarray(t, float)
return np.exp(-(t/lam)**k)
import time
import numpy as np
from scipy.optimize import minimize
def tabla_eventos(meses, evento):
meses = np.asarray(meses, int); evento = np.asarray(evento, bool)
T = int(meses.max()) + 2
d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T)
return d, c
def _nll_from_S(Sfun, d, c):
T = len(d)
grid = np.arange(0, T + 1, dtype=float)
Sg = Sfun(grid)
mid = Sfun(np.arange(T) + 0.5)
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
return 1e12 # región inválida / no calculable
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def ajustar_weibull(d, c):
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c)
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50., 200., 1000.):
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
if best is None or r.fun < best.fun: best = r
k, lam = np.exp(best.x)
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
S=lambda t: S_weibull(t, k, lam))
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120):
amin = max(0.0, 1.0 - k_fijo) + 1e-6
def unpack(p):
return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2])
T_max = float(len(d))
t_fin = time.time() + max_seg
agotado = [False]
def f(p):
if time.time() > t_fin:
agotado[0] = True
return 1e12
a, b, lam = unpack(p)
# penaliza regiones degeneradas (|z| enorme en el último mes -> serie costosa e inestable)
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
return 1e12
try:
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
except Exception:
return 1e12
lams = [lam_ref] if lam_ref else []
lams += [100., 500.]
best = None
inicios = []
if lam_ref: # primero el punto que reproduce el Weibull clásico (alpha=1, beta~1): como el clásico es un caso particular, el fraccional nunca queda peor
inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
for l0 in lams:
for a0 in (0.3, 1.0):
for b0 in (0.5, 0.9):
inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)])
for p0 in inicios:
if time.time() > t_fin and best is not None: break
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
if best is None or r.fun < best.fun: best = r
a, b, lam = unpack(best.x)
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
S=lambda t: S_ks(t, k_fijo, a, b, lam))
def km_curva(meses_int, evento, T):
d, c = tabla_eventos(meses_int, evento)
L = max(len(d), T + 1)
d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c)))
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
with np.errstate(divide="ignore", invalid="ignore"):
se = np.sqrt(V) / np.abs(np.log(S))
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
return S, lo, hi
T_KM = max(MESES_MAX, max(HORIZONTES))
S_km, lo_km, hi_km = km_curva(df["meses_int"].values, df["evento"].values, T_KM)
d_t, c_t = tabla_eventos(df["meses_int"].values, df["evento"].values)
w_fit = ajustar_weibull(d_t, c_t)
k_f = w_fit["k"] if K_IDENT == "clasico" else float(K_IDENT)
ks_fit = ajustar_ks(d_t, c_t, k_fijo=k_f, lam_ref=w_fit["lam"])
from sklearn.linear_model import LogisticRegression
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
X_dum = construir_X_dum()
def curva_ajustada(idx, T, paso=PASO_AJUSTE):
m, e = MESES_V[idx], EV_V[idx]
bordes = list(range(0, T + 1, paso))
if bordes[-1] < T: bordes.append(T)
S_i = np.ones(len(idx)); S_b = [1.0]
for a, b in zip(bordes[:-1], bordes[1:]):
sel = np.where(m >= a)[0]
y = np.where(e[sel] & (m[sel] < b), 0, 1); w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
if y.min() == y.max():
S_i = S_i * y.mean()
else:
lr = LogisticRegression(C=10.0, max_iter=300).fit(X_dum[idx][sel], y, sample_weight=w)
S_i = S_i * lr.predict_proba(X_dum[idx])[:, 1]
S_b.append(S_i.mean())
S_b = np.minimum.accumulate(np.array(S_b))
S = np.interp(np.arange(T + 1), bordes, np.log(np.maximum(S_b, 1e-12)))
return np.exp(S)
S_aj = curva_ajustada(np.arange(len(df)), T_KM)
def ajustar_a_curva(S, N_eq):
d = np.maximum(N_eq * (S[:-1] - S[1:]), 0.0); T = len(d)
d = np.concatenate([d, [0.0, 0.0]]); c = np.zeros(T + 2); c[T] = N_eq * S[-1]
w = ajustar_weibull(d, c)
ks = ajustar_ks(d, c, k_fijo=(w["k"] if K_IDENT == "clasico" else float(K_IDENT)), lam_ref=w["lam"])
return w, ks
if CURVAS == "ajustada":
S_base = S_aj; lo_base = hi_base = None
_, ks_plot = ajustar_a_curva(S_aj, len(df))
else:
S_base, lo_base, hi_base, ks_plot = S_km, lo_km, hi_km, ks_fit
from scipy.special import gammaln
from sklearn.linear_model import LogisticRegression
def pesos_y(meses, evento, h, modo):
m = np.asarray(meses, int); e = np.asarray(evento, bool)
conocido = e | (m >= h)
y = (m >= h).astype(int)
w = np.ones(len(m))
if modo == "ipcw":
T = int(m.max()) + 2
cen = np.bincount(m[~e], minlength=T); mu = np.bincount(m, minlength=T)
nr = len(m) - np.concatenate([[0], np.cumsum(mu)[:-1]])
G = np.concatenate([[1.0], np.cumprod(1 - cen / np.maximum(nr, 1))]) # G[t] = P(no censurada antes del mes t)
G = np.clip(G, 0.05, 1.0)
w = 1.0 / G[np.minimum(m, h)]
return conocido, y, w
# Matriz de covariables: codificación entera por covariable y dummies para la LR
X_int = np.column_stack([pd.factorize(df[c])[0] for c in COVARIABLES]).astype(int)
niv = X_int.max(axis=0) + 1
X_dum = construir_X_dum()
def bdeu(codigo, y, w, q, ess):
n = np.bincount(codigo * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
nj = n.sum(1); aj = ess / q; ajk = aj / 2
return float(np.sum(gammaln(aj) - gammaln(aj + nj) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)))
def buscar_padres(X, niv, y, w, ess=HBN_ESS, max_padres=HBN_MAX_PADRES):
padres, cod, q = [], np.zeros(len(y), int), 1
mejor = bdeu(cod, y, w, q, ess)
while len(padres) < max_padres:
cand = None
for j in range(X.shape[1]):
if j in padres or q * niv[j] > 200_000: continue
c2 = cod * niv[j] + X[:, j]; s = bdeu(c2, y, w, q * niv[j], ess)
if s > mejor + 1e-9 and (cand is None or s > cand[0]): cand = (s, j, c2, q * niv[j])
if cand is None: break
mejor, j, cod, q = cand; padres.append(j)
return padres
PADRES_FIJOS_IDX = None
if HBN_PADRES_FIJOS:
PADRES_FIJOS_IDX = []
_kws = list(HBN_PADRES_FIJOS) + (["Edad"] if HBN_EDAD_PADRE and not any(re.search(r"(^|_)age(_|$)|edad", k.lower()) for k in HBN_PADRES_FIJOS) else [])
for kw in _kws:
hit = [j for j, c in enumerate(COVARIABLES) if kw.lower() in c.lower()]
assert hit, f"HBN_PADRES_FIJOS: no hay una covariable que contenga '{kw}' en {COVARIABLES}"
PADRES_FIJOS_IDX.append(hit[0])
def ajustar_hbn(X, niv, y, w, ess=HBN_ESS, pad=None):
if pad is None and PADRES_FIJOS_IDX is not None: pad = PADRES_FIJOS_IDX
pad = buscar_padres(X, niv, y, w, ess) if pad is None else list(pad)
q = int(np.prod([niv[j] for j in pad])) if pad else 1
cod = np.zeros(len(y), int)
for j in pad: cod = cod * niv[j] + X[:, j]
n = np.bincount(cod * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj = ess / q
pbar = (n[:, 1].sum() + 0.5) / (n.sum() + 1) # prior centrado en la supervivencia marginal (evita sesgar hacia 0.5)
return pad, (n[:, 1] + aj * pbar) / (n.sum(1) + aj) # P(Y=1 | padres), suavizada hacia la marginal
def predecir_hbn(modelo, X, niv):
pad, cpt = modelo
cod = np.zeros(len(X), int)
for j in pad: cod = cod * niv[j] + X[:, j]
return cpt[cod]
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
def pred_h(idx, h, modo, pad=None):
m, e = MESES_V[idx], EV_V[idx]
kn, y, w = pesos_y(m, e, h, modo)
sel = np.where(kn)[0]
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[idx][sel], y[sel], sample_weight=w[sel])
mod = ajustar_hbn(X_int[idx][sel], niv, y[sel], w[sel], pad=pad)
return lr.predict_proba(X_dum[idx])[:, 1], predecir_hbn(mod, X_int[idx], niv), list(mod[0])
BORDES = [0] + list(HORIZONTES)
def pred_riesgo_int(idx, padres=None, test=None):
test = idx if test is None else test
m, e = MESES_V[idx], EV_V[idx]
P_lr, P_hb, pads = [], [], []
for i_, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
sel = np.where(m >= a)[0] # llegan vivas al inicio del intervalo
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = sobrevive el intervalo
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censura dentro del intervalo: medio riesgo
lr = LogisticRegression(C=1e6, max_iter=500).fit(X_dum[idx][sel], y, sample_weight=w)
mod = ajustar_hbn(X_int[idx][sel], niv, y, w, pad=None if padres is None else padres[i_])
P_lr.append(lr.predict_proba(X_dum[test])[:, 1]); P_hb.append(predecir_hbn(mod, X_int[test], niv)); pads.append(list(mod[0]))
return np.column_stack(P_lr), np.column_stack(P_hb), pads
def pred_riesgo(idx, padres=None):
Pl, Ph, pads = pred_riesgo_int(idx, padres)
return np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1), pads
def predecir_pacientes(idx, modo, padres=None):
if modo == "riesgo":
return pred_riesgo(idx, padres)
r = [pred_h(idx, h, modo, None if padres is None else padres[i_]) for i_, h in enumerate(HORIZONTES)]
return np.column_stack([x[0] for x in r]), np.column_stack([x[1] for x in r]), [x[2] for x in r]
def estimar(idx, modo, padres=None):
P_lr, P_hb, pads = predecir_pacientes(idx, modo, padres)
return P_lr.mean(axis=0), P_hb.mean(axis=0), pads
from scipy.optimize import minimize_scalar
ESTILO_MOD = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
N = len(df); todas = np.arange(N)
COMB_ACTIVO = bool(COMBINAR) and CENSURA_MODELOS == "riesgo"
MODS_PLOT = (["LR", "HBN", "COMB"] if MOSTRAR_INDIVIDUALES else ["COMB"]) if COMB_ACTIVO else ["LR", "HBN"]
# ---- Robustez fuera de muestra: predicciones por pliegues (cada paciente se predice con modelos que no la vieron)
if COMB_ACTIVO:
_fold = np.random.default_rng(SEMILLA + 7).permutation(N) % STACK_FOLDS
OOF_lr = np.zeros((N, len(HORIZONTES))); OOF_hb = np.zeros_like(OOF_lr)
for k in range(STACK_FOLDS):
te = np.where(_fold == k)[0]; tr = np.where(_fold != k)[0]
Pl_, Ph_, _ = pred_riesgo_int(tr, None, te); OOF_lr[te] = Pl_; OOF_hb[te] = Ph_
def pesos_apilados(mask, shrink=STACK_SHRINK):
filas_ = []
for j, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
idx_ = np.where(mask & (MESES_V >= a))[0]
e_, m_ = EV_V[idx_], MESES_V[idx_]
y = np.where(e_ & (m_ < b), 0, 1); wt = np.where((~e_) & (m_ < b), 0.5, 1.0)
p1 = np.clip(OOF_lr[idx_, j], 1e-9, 1 - 1e-9); p2 = np.clip(OOF_hb[idx_, j], 1e-9, 1 - 1e-9)
muertes = int((y == 0).sum())
if len(idx_) == 0:
filas_.append(dict(intervalo=f"{a}-{b}", n_riesgo=0, muertes=0, w_LR=0.5, w_LR_sin_contraer=0.5, dLL_LR_menos_HBN=0.0, z=0.0, decision="mezcla")); continue
def nll(w_):
p = np.clip(w_ * p1 + (1 - w_) * p2, 1e-9, 1 - 1e-9)
return -np.sum(wt * (y * np.log(p) + (1 - y) * np.log1p(-p)))
w_star = float(minimize_scalar(nll, bounds=(0, 1), method="bounded").x)
lam = shrink / (shrink + muertes); w_fin = (1 - lam) * w_star + lam * 0.5
d = wt * (y * (np.log(p1) - np.log(p2)) + (1 - y) * (np.log1p(-p1) - np.log1p(-p2))) # log-score LR - HBN por paciente
z = d.sum() / (np.sqrt(len(d)) * d.std(ddof=1)) if len(d) > 2 and d.std(ddof=1) > 0 else 0.0
dec = "solo LR" if w_fin >= 0.95 else "solo HBN" if w_fin <= 0.05 else "mezcla"
filas_.append(dict(intervalo=f"{a}-{b}", n_riesgo=len(idx_), muertes=muertes, w_LR=w_fin, w_LR_sin_contraer=w_star,
dLL_LR_menos_HBN=float(d.sum()), z=float(z), decision=dec))
return pd.DataFrame(filas_)
def estimar4(idx, padres, W):
Pl, Ph, pads_ = pred_riesgo_int(idx, padres)
Sc = np.cumprod(W[None, :] * Pl + (1 - W[None, :]) * Ph, axis=1)
return np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0), Sc.mean(0), pads_
rng = np.random.default_rng(SEMILLA)
if COMB_ACTIVO:
TAB_W_ALL = pesos_apilados(np.ones(N, bool)); W_ALL = TAB_W_ALL["w_LR"].values
p_lr, p_hbn, p_cmb, pads = estimar4(todas, None, W_ALL)
else:
p_lr, p_hbn, pads = estimar(todas, CENSURA_MODELOS); p_cmb = None
PADRES_REF = pads if HBN_PADRES == "fijos" else None # padres de la HBN aprendidos en la cohorte completa
if DIAGNOSTICO: # mismos puntos con los otros tratamientos de la censura (sin bootstrap), para ver cuánto depende el resultado de él
diag = {"KM crudo": [S_km[h] for h in HORIZONTES], "KM ajustada": [S_aj[h] for h in HORIZONTES]}
for modo in ("riesgo", "ipcw", "excluir"):
r = estimar(todas, modo); diag[f"LR ({modo})"] = r[0]; diag[f"HBN ({modo})"] = r[1]
boots = []
for b in tqdm(range(B_BOOT), desc="Bootstrap"):
idx_b = rng.integers(0, N, N)
if COMB_ACTIVO:
r = estimar4(idx_b, PADRES_REF, W_ALL); boots.append(np.concatenate([r[0], r[1], r[2]]))
else:
r = estimar(idx_b, CENSURA_MODELOS, PADRES_REF); boots.append(np.concatenate([r[0], r[1]]))
SERIES = [("LR", p_lr), ("HBN", p_hbn)] + ([("COMB", p_cmb)] if COMB_ACTIVO else [])
nh = len(HORIZONTES)
boots = np.array(boots) if B_BOOT > 0 else np.full((1, len(SERIES) * nh), np.nan)
ic = np.nanpercentile(boots, [2.5, 97.5], axis=0)
filas = []
for j, (nom, vals_) in enumerate(SERIES):
for i, h in enumerate(HORIZONTES):
filas.append(dict(modelo=nom, meses=h, S=vals_[i], IC_inf=ic[0, j * nh + i], IC_sup=ic[1, j * nh + i]))
tabla = pd.DataFrame(filas)
tabla["KM_crudo"] = [S_km[h] for h in tabla["meses"]]
tabla["KM_ajustada"] = [S_aj[h] for h in tabla["meses"]]
tabla.to_csv(SALIDA_CSV, index=False)
if COMB_ACTIVO: TAB_W_ALL.to_csv(f"./pesos_combinacion_cohorte{SUF}.csv", index=False)
import matplotlib.pyplot as plt
tt = np.arange(0, MESES_MAX + 1)
tc = np.linspace(0, MESES_MAX, 600)
if INSET_ZOOM:
fig, (ax, axi) = plt.subplots(1, 2, figsize=(15, 5.6), gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
else:
fig, ax = plt.subplots(figsize=(9.5, 5.6))
xx = np.arange(T_KM + 1)
if CURVAS == "ajustada":
if MOSTRAR_KM_CRUDO: ax.step(xx, S_km, where="post", color="#9aa5b1", lw=1.0, ls=":", label="Kaplan-Meier crudo (referencia)")
ax.step(xx, S_aj, where="post", color="#3d4852", lw=1.8, label="Kaplan-Meier ajustada por covariables")
lbl_ks = "Weibull fraccional (ajustado a la curva ajustada)"
else:
ax.fill_between(xx, lo_km, hi_km, step="post", color="#9aa5b1", alpha=.35, lw=0, label="Kaplan-Meier (IC 95 % Greenwood)")
ax.step(xx, S_km, where="post", color="#3d4852", lw=1.6, label="Kaplan-Meier")
lbl_ks = "Weibull fraccional (Kilbas-Saigo)"
ax.plot(tc, ks_plot["S"](tc), color="#d1495b", lw=2.4, label=lbl_ks)
for nom in MODS_PLOT:
col, mk, lb = ESTILO_MOD[nom]
s = tabla[tabla["modelo"] == nom]
ax.errorbar(s["meses"], s["S"], yerr=[np.clip(s["S"] - s["IC_inf"], 0, None), np.clip(s["IC_sup"] - s["S"], 0, None)], fmt=mk, color=col, ms=9 if nom == "COMB" else 8,
capsize=4, lw=1.8, mec="white", mew=1, label=f"{lb} (IC 95 % bootstrap)", zorder=5)
tabla_p = tabla[tabla["modelo"].isin(MODS_PLOT)]
ax.set_xlim(0, MESES_MAX + (0.8 if TOPE_MESES else 0)); ax.set_xlabel("Meses desde el diagnóstico"); ax.set_ylabel("Supervivencia S(t)")
vals = np.concatenate([S_base[:MESES_MAX + 1], tabla_p["IC_inf"].values, [ks_plot["S"](np.array([float(MESES_MAX)]))[0]]])
ax.set_ylim(max(0.0, np.nanmin(vals) - 0.03), 1.005)
if YLIM_PRINCIPAL: ax.set_ylim(*YLIM_PRINCIPAL)
ax.set_xticks(range(0, MESES_MAX + 1, 3 if TOPE_MESES else 6)); ax.grid(alpha=.25)
if INSET_ZOOM:
xi = np.arange(INSET_MESES + 1)
axi.step(xi, S_aj[:INSET_MESES + 1] if CURVAS == "ajustada" else S_km[:INSET_MESES + 1], where="post", color="#3d4852", lw=1.4)
if CURVAS == "ajustada" and MOSTRAR_KM_CRUDO: axi.step(xi, S_km[:INSET_MESES + 1], where="post", color="#9aa5b1", lw=1.0, ls=":")
tci = np.linspace(0, INSET_MESES, 200); axi.plot(tci, ks_plot["S"](tci), color="#d1495b", lw=2)
for nom in MODS_PLOT:
col, mk, lb = ESTILO_MOD[nom]; s_ = tabla[tabla["modelo"] == nom]
axi.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
fmt=mk, color=col, ms=6, capsize=3, lw=1.5, mec="white", mew=.8, zorder=5)
_v = np.concatenate([S_base[:INSET_MESES + 1], tabla_p["IC_inf"].values, tabla_p["IC_sup"].values]); _m = (_v.max() - _v.min()) * .08
axi.set_xlim(0, INSET_MESES + 0.8); axi.set_ylim(_v.min() - _m, min(1.002, _v.max() + _m)); axi.set_xticks(range(0, INSET_MESES + 1, 6))
axi.grid(alpha=.25); axi.set_title(f"Zoom: primeros {INSET_MESES} meses", fontsize=10); axi.set_xlabel("Meses desde el diagnóstico"); axi.spines[["top", "right"]].set_visible(False)
ax.axvspan(0, INSET_MESES, color="#888", alpha=.08, lw=0)
ax.set_title(f"Supervivencia de la cohorte completa (n = {N:,}){TAG}"); ax.legend(loc="lower left", frameon=False)
for s in ("top", "right"): ax.spines[s].set_visible(False)
fig.tight_layout(); fig.savefig(SALIDA_PNG, dpi=200)
import matplotlib.pyplot as _p; _p.close("all")
MESES_EXTRAP = TOPE_MESES or 120 # hasta dónde se extrapola (punteado) fuera del seguimiento observado
YLIM_SUB = {} # zoom manual en y por subgrupo, p. ej. {"Estadio I": (0.97, 1.0)}; los que no estén usan el automático
XLIM_SUB = None # p. ej. (0, 72) para no mostrar la extrapolación; None = (0, MESES_EXTRAP)
MIN_EVENTOS_SUB = 5 # mínimo de fallecimientos para ajustar un subgrupo
B_BOOT_SUB = B_BOOT # réplicas bootstrap de los modelos en los subgrupos (es otro bucle completo; baja el número si tarda mucho)
COL_EST = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
COL_SUB = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
_cands = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
COL_EDAD = sorted(_cands, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0] if _cands else None
def _edad(v):
m_ = re.search(r"\d+", str(v)); return float(m_.group()) if m_ else np.nan
def _estadio(v):
u = str(v).upper().replace("STAGE", "").strip()
if u.startswith("0") or u == "IS": return 0
for p_, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
if u.startswith(p_): return val
return np.nan
df["_edad"] = df[COL_EDAD].map(_edad) if COL_EDAD else np.nan
df["_estadio"] = df[COL_EST].map(_estadio) if COL_EST else np.nan
COL_CX = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
df["_her2neg"] = df[COL_SUB].astype(str).str.contains("HER2-", regex=False) if COL_SUB else False # sin HER2+ (HER2 negativo)
df["_triple_neg"] = df[COL_SUB].astype(str).str.contains("HR-/HER2-", regex=False) if COL_SUB else False # HR− / HER2−
df["_cons"] = df[COL_CX].astype(str).str.lower().str.contains("conserv") if COL_CX else False # cirugía conservadora
df["_her2pos"] = df[COL_SUB].astype(str).str.contains("HER2+", regex=False) if COL_SUB else False
# Edita aquí los subgrupos (nombre -> máscara booleana sobre df)
SUBGRUPOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": lambda d: d["_her2pos"] & (d["_edad"] >= 60) & d["_estadio"].isin([3, 4]),
"HER2+ · <60 años · estadio 0–II (Bajo)": lambda d: d["_her2pos"] & (d["_edad"] < 60) & d["_estadio"].isin([0, 1, 2]),
"Estadio IV": lambda d: d["_estadio"] == 4,
"Estadio I": lambda d: d["_estadio"] == 1,
"≥ 75 años": lambda d: d["_edad"] >= 75,
"< 45 años": lambda d: d["_edad"] < 45,
# --- combinaciones adicionales ---
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": lambda d: (d["_edad"] < 45) & d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
"HER2− · estadio 0–II · cirugía conservadora": lambda d: d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
"HER2+ · estadio 0–II · cirugía conservadora": lambda d: d["_her2pos"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
"Jóvenes (<45) · estadio 0–II": lambda d: (d["_edad"] < 45) & d["_estadio"].isin([0, 1, 2]),
"Jóvenes (<45) · HER2−": lambda d: (d["_edad"] < 45) & d["_her2neg"],
"Triple negativo (HR−/HER2−) · estadio 0–II": lambda d: d["_triple_neg"] & d["_estadio"].isin([0, 1, 2]),
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": lambda d: (d["_edad"] >= 65) & d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
}
MASCARAS = {n: np.asarray(f(df).fillna(False), dtype=bool) for n, f in SUBGRUPOS.items()}
# LR, HBN y su combinación en los subgrupos: se ajustan en la cohorte completa y se promedian las predicciones dentro de cada subgrupo
rng_sub = np.random.default_rng(SEMILLA + 1)
MODELOS_SUB = ["LR", "HBN"] + (["COMB"] if COMB_ACTIVO else [])
nm = len(MODELOS_SUB)
if COMB_ACTIVO: # pesos de la combinación por subgrupo (robustez fuera de muestra dentro del subgrupo)
W_SUB = {n: pesos_apilados(mk) for n, mk in MASCARAS.items()}
else:
W_SUB = {}
def medias_subgrupo(idx, padres):
out = {}
if COMB_ACTIVO:
Pl, Ph, _ = pred_riesgo_int(idx, padres)
Sl, Sh = np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1)
for n, mk in MASCARAS.items():
mm = mk[idx]
if not mm.any(): out[n] = np.full(nm * nh, np.nan); continue
W_ = W_SUB[n]["w_LR"].values[None, :]
Sc = np.cumprod(W_ * Pl[mm] + (1 - W_) * Ph[mm], axis=1)
out[n] = np.concatenate([Sl[mm].mean(0), Sh[mm].mean(0), Sc.mean(0)])
else:
Sl, Sh, _ = predecir_pacientes(idx, CENSURA_MODELOS, padres)
for n, mk in MASCARAS.items():
mm = mk[idx]
out[n] = np.concatenate([Sl[mm].mean(0), Sh[mm].mean(0)]) if mm.any() else np.full(nm * nh, np.nan)
return out
PT_SUB = medias_subgrupo(todas, None)
_boots = {n: [] for n in MASCARAS}
for b in tqdm(range(B_BOOT_SUB), desc="Bootstrap subgrupos"):
r_ = medias_subgrupo(rng_sub.integers(0, N, N), PADRES_REF)
for n in MASCARAS: _boots[n].append(r_[n])
MOD_SUB = {}
for n, mk in MASCARAS.items():
B_ = np.array(_boots[n]) if B_BOOT_SUB > 0 else np.full((1, nm * nh), np.nan)
ic_ = np.nanpercentile(B_, [2.5, 97.5], axis=0) if mk.any() else np.full((2, nm * nh), np.nan)
pt = PT_SUB[n]
MOD_SUB[n] = pd.DataFrame([dict(modelo=nom, meses=h, S=pt[j * nh + i], IC_inf=ic_[0, j * nh + i], IC_sup=ic_[1, j * nh + i])
for j, nom in enumerate(MODELOS_SUB) for i, h in enumerate(HORIZONTES)])
import matplotlib.pyplot as plt
def aic(nll, k): return 2 * k + 2 * nll
RES_SUB = {}
def ajustar_subgrupo(nombre):
mk = MASCARAS[nombre]; sub = df[mk]
n_, ev_ = len(sub), int(sub["evento"].sum())
if n_ == 0 or ev_ < MIN_EVENTOS_SUB:
return None
d_, c_ = tabla_eventos(sub["meses_int"].values, sub["evento"].values)
w_ = ajustar_weibull(d_, c_)
ks_ = ajustar_ks(d_, c_, k_fijo=(w_["k"] if K_IDENT == "clasico" else float(K_IDENT)), lam_ref=w_["lam"], max_seg=180)
Tm = int(sub["meses_int"].max())
Sk, lok, hik = km_curva(sub["meses_int"].values, sub["evento"].values, Tm)
grid = np.arange(0, Tm + 1, dtype=float)
fila = {"subgrupo": nombre, "n": n_, "fallecidos": ev_, "seguim. máx. (m)": Tm, "k Weibull": w_["k"],
"k KS / α / β": f"{ks_['k']:.2f} / {ks_['alpha']:.2f} / {ks_['beta']:.2f}",
"AIC Weibull": aic(w_["nll"], 2), "AIC fraccional": aic(ks_["nll"], 3), "ΔAIC (W − F)": aic(w_["nll"], 2) - aic(ks_["nll"], 3),
"máx|KM−Weibull|": np.abs(w_["S"](grid) - Sk).max(), "máx|KM−fracc.|": np.abs(ks_["S"](grid) - Sk).max()}
return dict(nombre=nombre, n=n_, ev=ev_, w=w_, ks=ks_, Sk=Sk, lok=lok, hik=hik, Tm=Tm, fila=fila, modelos=MOD_SUB[nombre], pesos=W_SUB.get(nombre))
def graficar_subgrupo(a):
if a is None: return
mp = a["modelos"][a["modelos"]["modelo"].isin(MODS_PLOT)]
Tm = a["Tm"]; tt = np.arange(Tm + 1)
if INSET_ZOOM:
fig, (ax, axi) = plt.subplots(1, 2, figsize=(15, 5.2), gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
else:
fig, ax = plt.subplots(figsize=(9, 5.2))
ax.fill_between(tt, a["lok"], a["hik"], step="post", color="#9aa5b1", alpha=.3, lw=0)
ax.step(tt, a["Sk"], where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
for key, col, ls, lb in [("w", "#1f77b4", "-", "Weibull"), ("ks", "#d1495b", "--", "Weibull fraccional")]:
t_in = np.linspace(0, Tm, 300); t_ex = np.linspace(Tm, MESES_EXTRAP, 200)
ax.plot(t_in, a[key]["S"](t_in), color=col, lw=2.2, ls=ls, label=lb)
ax.plot(t_ex, a[key]["S"](t_ex), color=col, lw=1.4, ls=":")
if not TOPE_MESES: ax.axvline(Tm, color="#888", lw=.8, ls=":")
for nom in MODS_PLOT:
col, mk_, lb = ESTILO_MOD[nom]; s_ = mp[mp["modelo"] == nom]
ax.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
fmt=mk_, color=col, ms=9 if nom == "COMB" else 8, capsize=4, lw=1.8, mec="white", mew=1, label=f"{lb} (IC 95 % bootstrap)", zorder=5)
x0, x1 = XLIM_SUB if XLIM_SUB else (0, MESES_EXTRAP + (0.8 if TOPE_MESES else 0))
xs = np.linspace(x0, x1, 400)
vis = [a["w"]["S"](xs), a["ks"]["S"](xs), a["Sk"][int(x0):int(min(x1, Tm)) + 1], a["lok"][int(x0):int(min(x1, Tm)) + 1],
mp["IC_inf"].values, mp["IC_sup"].values]
v = np.concatenate([np.ravel(u) for u in vis]); v = v[np.isfinite(v)]
mg = (v.max() - v.min()) * .06
ylim = YLIM_SUB.get(a["nombre"], (max(0, v.min() - mg), min(1.005, v.max() + mg)))
ax.set_xlim(x0, x1); ax.set_ylim(*ylim)
if INSET_ZOOM:
xi = np.arange(INSET_MESES + 1)
axi.fill_between(xi, a["lok"][:INSET_MESES + 1], a["hik"][:INSET_MESES + 1], step="post", color="#9aa5b1", alpha=.3, lw=0)
axi.step(xi, a["Sk"][:INSET_MESES + 1], where="post", color="#222", lw=1.3)
tci = np.linspace(0, INSET_MESES, 200)
axi.plot(tci, a["w"]["S"](tci), color="#1f77b4", lw=2); axi.plot(tci, a["ks"]["S"](tci), color="#d1495b", lw=2, ls="--")
for nom in MODS_PLOT:
col, mk_, lb = ESTILO_MOD[nom]; s_ = mp[mp["modelo"] == nom]
axi.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
fmt=mk_, color=col, ms=6, capsize=3, lw=1.5, mec="white", mew=.8, zorder=5)
vi = np.concatenate([a["Sk"][:INSET_MESES + 1], a["lok"][:INSET_MESES + 1], mp["IC_inf"].values, mp["IC_sup"].values, a["w"]["S"](tci)])
vi = vi[np.isfinite(vi)]; mi = (vi.max() - vi.min()) * .08
axi.set_xlim(0, INSET_MESES + 0.8); axi.set_ylim(vi.min() - mi, min(1.002, vi.max() + mi)); axi.set_xticks(range(0, INSET_MESES + 1, 6))
axi.grid(alpha=.25); axi.set_title(f"Zoom: primeros {INSET_MESES} meses", fontsize=10); axi.set_xlabel("Meses desde el diagnóstico"); axi.spines[["top", "right"]].set_visible(False)
ax.axvspan(0, INSET_MESES, color="#888", alpha=.08, lw=0)
ax.set_xlabel("Meses desde el diagnóstico"); ax.set_ylabel("Supervivencia S(t)"); ax.grid(alpha=.25)
ax.set_title(f"{a['nombre']}{TAG}\nn={a['n']:,}, fallecidos={a['ev']:,}", fontsize=11)
ax.legend(frameon=False, loc="lower left", fontsize=9)
for sp in ("top", "right"): ax.spines[sp].set_visible(False)
fig.tight_layout()
nom_arch = re.sub(r"[^A-Za-z0-9]+", "_", a["nombre"].replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt").replace("ñ", "n").replace("–", "-")).strip("_")
fig.savefig(f"./subgrupo_{nom_arch}{SUF}.png", dpi=170)
import matplotlib.pyplot as _p; _p.close("all")
RES_SUB['HER2+ · ≥60 años · estadio III–IV (Alto)'] = ajustar_subgrupo('HER2+ · ≥60 años · estadio III–IV (Alto)'); graficar_subgrupo(RES_SUB['HER2+ · ≥60 años · estadio III–IV (Alto)'])
RES_SUB['HER2+ · <60 años · estadio 0–II (Bajo)'] = ajustar_subgrupo('HER2+ · <60 años · estadio 0–II (Bajo)'); graficar_subgrupo(RES_SUB['HER2+ · <60 años · estadio 0–II (Bajo)'])
RES_SUB['Estadio IV'] = ajustar_subgrupo('Estadio IV'); graficar_subgrupo(RES_SUB['Estadio IV'])
RES_SUB['Estadio I'] = ajustar_subgrupo('Estadio I'); graficar_subgrupo(RES_SUB['Estadio I'])
RES_SUB['≥ 75 años'] = ajustar_subgrupo('≥ 75 años'); graficar_subgrupo(RES_SUB['≥ 75 años'])
RES_SUB['< 45 años'] = ajustar_subgrupo('< 45 años'); graficar_subgrupo(RES_SUB['< 45 años'])
RES_SUB['Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'])
RES_SUB['HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['HER2− · estadio 0–II · cirugía conservadora'])
RES_SUB['HER2+ · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('HER2+ · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['HER2+ · estadio 0–II · cirugía conservadora'])
RES_SUB['Jóvenes (<45) · estadio 0–II'] = ajustar_subgrupo('Jóvenes (<45) · estadio 0–II'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · estadio 0–II'])
RES_SUB['Jóvenes (<45) · HER2−'] = ajustar_subgrupo('Jóvenes (<45) · HER2−'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · HER2−'])
RES_SUB['Triple negativo (HR−/HER2−) · estadio 0–II'] = ajustar_subgrupo('Triple negativo (HR−/HER2−) · estadio 0–II'); graficar_subgrupo(RES_SUB['Triple negativo (HR−/HER2−) · estadio 0–II'])
RES_SUB['≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'])
tabla_sub = pd.DataFrame([a["fila"] for a in RES_SUB.values() if a is not None])
tabla_sub.to_csv(f"./subgrupos_KM_Weibull_fraccional{SUF}.csv", index=False)
pd.concat([a["modelos"].assign(subgrupo=a["nombre"]) for a in RES_SUB.values() if a is not None]).to_csv(f"./subgrupos_puntos_LR_HBN{SUF}.csv", index=False)
if COMB_ACTIVO:
pd.concat([a["pesos"].assign(subgrupo=a["nombre"]) for a in RES_SUB.values() if a is not None]).to_csv(f"./subgrupos_pesos_combinacion{SUF}.csv", index=False)
# Prueba: edad como variable numérica (punto medio de su grupo de 5 años) en la LR, frente a la edad categorizada
def _edad_media(v):
n_ = [float(x) for x in re.findall(r"\d+", str(v))]
if not n_: return np.nan
if "+" in str(v): return n_[0] + 2.5
return float(np.mean(n_[:2]))
ed = df[COL_EDAD].map(_edad_media).astype(float) if COL_EDAD else pd.Series(np.nan, index=df.index)
assert ed.notna().mean() > 0.5, "No se pudo leer la edad numérica"
z = ((ed - ed.mean()) / ed.std()).fillna(0.0).values # edad estandarizada (faltantes -> media)
cols_sin_edad = [c for c in COVARIABLES if not re.search(r"(^|_)age(_|$)|edad", c.lower())]
Xb = pd.get_dummies(df[cols_sin_edad], drop_first=True).values.astype(np.float32)
if "Edad_cat" in df.columns:
Xcat = np.column_stack([Xb, pd.get_dummies(df[["Edad_cat"]], drop_first=True).values.astype(np.float32)])
else:
Xcat = X_dum if EDAD_MODO == "categorizada" else None
VARIANTES = {
"sin edad": Xb,
"edad categorizada": Xcat,
"edad continua": np.column_stack([Xb, z]).astype(np.float32),
"edad continua + cuadrática": np.column_stack([Xb, z, z ** 2]).astype(np.float32),
}
if Xcat is None: VARIANTES.pop("edad categorizada")
REF_V = "edad categorizada" if "edad categorizada" in VARIANTES else "sin edad"
def lr_int(Xm, idx, test):
P = []
for a, b in zip(BORDES[:-1], BORDES[1:]):
sel = np.where(MESES_V[idx] >= a)[0]
y = np.where(EV_V[idx][sel] & (MESES_V[idx][sel] < b), 0, 1); w = np.where((~EV_V[idx][sel]) & (MESES_V[idx][sel] < b), 0.5, 1.0)
P.append(LogisticRegression(C=1e6, max_iter=500).fit(Xm[idx][sel], y, sample_weight=w).predict_proba(Xm[test])[:, 1])
return np.column_stack(P)
_fold2 = np.random.default_rng(SEMILLA + 11).permutation(N) % STACK_FOLDS
PT, OOF = {}, {}
for nom, Xm in VARIANTES.items():
PT[nom] = np.cumprod(lr_int(Xm, todas, todas), axis=1) # ajuste en toda la cohorte
O = np.zeros((N, len(HORIZONTES)))
for k in range(STACK_FOLDS):
te = np.where(_fold2 == k)[0]; tr = np.where(_fold2 != k)[0]; O[te] = lr_int(Xm, tr, te)
OOF[nom] = O
def ll_oof(O, mask):
tot = 0.0
for j, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
i_ = np.where(mask & (MESES_V >= a))[0]
y = np.where(EV_V[i_] & (MESES_V[i_] < b), 0, 1); w = np.where((~EV_V[i_]) & (MESES_V[i_] < b), 0.5, 1.0)
p = np.clip(O[i_, j], 1e-9, 1 - 1e-9); tot += np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
return tot
# 1) Supervivencia media predicha por variante vs Kaplan-Meier, por subgrupo
filas = []
for n_, mk in [("Cohorte completa", np.ones(N, bool))] + list(MASCARAS.items()):
if mk.sum() == 0: continue
Sk_, _, _ = km_curva(MESES_V[mk], EV_V[mk], max(HORIZONTES))
for i, h in enumerate(HORIZONTES):
f_ = {"subgrupo": n_, "meses": h, "KM": Sk_[h]}
for nom in VARIANTES: f_[nom] = PT[nom][mk, i].mean()
filas.append(f_)
T1 = pd.DataFrame(filas)
# 2) Resumen: error vs KM y verosimilitud fuera de muestra
res = []
for nom in VARIANTES:
err = (T1[nom] - T1["KM"]).abs()
ll_c = ll_oof(OOF[nom], np.ones(N, bool)); ll_ref = ll_oof(OOF[REF_V], np.ones(N, bool))
res.append({"variante": nom, "error abs. medio vs KM (todos los subgrupos y horizontes)": err.mean(), "error abs. máx.": err.max(),
"log-verosimilitud fuera de muestra (cohorte)": ll_c, f"Δ vs {REF_V}": ll_c - ll_ref})
T2 = pd.DataFrame(res)
T1.to_csv(f"./prueba_edad_continua_vs_categorizada{SUF}.csv", index=False); T2.to_csv(f"./prueba_edad_resumen{SUF}.csv", index=False)
@@ -0,0 +1,228 @@
import json
import numpy as np
import pandas as pd
import statsmodels.api as sm
# Definicion de factores de riesgo a partir de cuatro criterios:
# c1 OR multivariable en la poblacion natural (IC 95% sin cruzar 1 y p ajustado por Benjamini-Hochberg < ALFA)
# c2 estabilidad en bootstrap: la variable entra al stepwise de la LR en al menos FREQ_MIN de las replicas
# c3 la variable esta en la manta de Markov del desenlace en la red bayesiana
# c4 diferencia absoluta de supervivencia a HORIZONTE meses (Kaplan-Meier) frente a la categoria de referencia
# Las variables de tratamiento son una decision clinica: no se clasifican como factores de riesgo
# y no entran al modelo de c1; se reportan aparte en asociaciones_tratamiento.csv.
CSV_NATURAL = "./dataframe_poblacion_natural.csv"
CSV_SELECCION = "./seleccion_bootstrap.csv"
CSV_ARCOS = "./hbn_arcos.csv"
ALFA = 0.05
FREQ_MIN = 0.80
HORIZONTE = 18
TOPE_MESES = 24
TRATAMIENTO = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
CANONICAL_MAP = {
"Age_group": "Edad", "Tumor_group": "Tamano_tumor", "Tamano_tumor_cat": "Tamano_tumor",
"Estadio_cat": "Estadio", "Grado_histologico_cat": "Grado_histologico",
"Subtipo_molecular_cat": "Subtipo_molecular", "Receptor_estrogeno_cat": "Receptor_estrogeno",
"Receptor_progesterona_cat": "Receptor_progesterona", "Metastasis_cat": "Metastasis",
"Localizacion_mama_cat": "Localizacion_mama", "Lateralidad_cat": "Lateralidad",
"Tipo_histologico_cat": "Tipo_histologico", "Tratamiento_quirurgico_cat": "Tratamiento_quirurgico",
"Radioterapia_cat": "Radioterapia", "Quimioterapia_cat": "Quimioterapia", "Estado_civil_cat": "Estado_civil",
"Ganglios_positivos_cat": "Ganglios_positivos", "Invasion_linfovascular_cat": "Invasion_linfovascular",
"Margenes_cat": "Margenes", "Densidad_BIRADS_cat": "Densidad_BIRADS", "Masa_espiculada_cat": "Masa_espiculada",
"Microcalcificaciones_cat": "Microcalcificaciones", "Multifocalidad_cat": "Multifocalidad",
"BRCA_cat": "BRCA", "HER2_IHQ_cat": "HER2_IHQ",
}
def find_col(df, keywords):
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords):
return col
return None
nat = pd.read_csv(CSV_NATURAL, dtype=str)
nat = nat[nat["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
col_meses = find_col(nat, ["survival months"])
col_vital = find_col(nat, ["vital status"])
col_race = find_col(nat, ["race"])
datos = pd.DataFrame({v: nat[k].fillna("Desconocido").astype(str) for k, v in CANONICAL_MAP.items() if k in nat.columns})
if col_race is not None and col_race not in CANONICAL_MAP:
datos["Race"] = nat[col_race].fillna("Desconocido").astype(str)
variables = list(datos.columns)
intrinsecas = [v for v in variables if v not in TRATAMIENTO]
tratamiento = [v for v in variables if v in TRATAMIENTO]
muerte = (nat["Outcome_cat"] == "Muerte").astype(int).values
meses = np.minimum(pd.to_numeric(nat[col_meses], errors="coerce").fillna(0).astype(int).values, TOPE_MESES)
evento = nat[col_vital].astype(str).str.lower().str.contains("dead").values & (pd.to_numeric(nat[col_meses], errors="coerce").fillna(0).values < TOPE_MESES)
# ---- c1: OR multivariable (referencia = categoria mas frecuente) ----
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]
modelo = sm.GLM(muerte, sm.add_constant(X), family=sm.families.Binomial()).fit()
ic = modelo.conf_int()
t = pd.DataFrame({"termino": X.columns, "OR_muerte": 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})
return t
def variable_de(termino, vars_modelo):
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
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
tab = ajustar_or(intrinsecas)
tab["variable"] = [variable_de(t, intrinsecas) for t in tab["termino"]]
tab["categoria"] = [t[len(v) + 1:] for t, v in zip(tab["termino"], tab["variable"])]
tab["referencia"] = [referencia(v) for v in tab["variable"]]
tab["p_ajustado_BH"] = bh(tab["p"])
tab["direccion"] = np.where(tab["OR_muerte"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
# ---- c4: diferencia de supervivencia (Kaplan-Meier) frente a la referencia ----
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 delta_s(v, cat, ref):
a = (datos[v] == cat).values
b = (datos[v] == ref).values
Sa, ea = km_en(meses[a], evento[a], HORIZONTE)
Sb, eb = km_en(meses[b], evento[b], HORIZONTE)
d = Sa - Sb
es = np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S18_categoria": Sa, "S18_referencia": Sb, "delta_S18": d,
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
def tabla_delta(filas):
return pd.DataFrame([delta_s(v, c, r) for v, c, r in filas])
ds = tabla_delta(zip(tab["variable"], tab["categoria"], tab["referencia"]))
tab = pd.concat([tab.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S18"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
# ---- c2: estabilidad en bootstrap ----
freq = pd.Series(np.nan, index=intrinsecas)
try:
sel = pd.read_csv(CSV_SELECCION)
lr = sel[sel["modelo"] == "LR"]
n_rep = (lr["termino"] == "(replica)").sum()
if n_rep > 0:
por_var = lr[lr["termino"] != "(replica)"].groupby("variable")["replica"].nunique()
freq = pd.Series({v: por_var.get(v, 0) / n_rep for v in intrinsecas})
except FileNotFoundError:
n_rep = 0
tab["freq_seleccion_bootstrap"] = tab["variable"].map(freq)
tab["c2_estabilidad"] = (tab["freq_seleccion_bootstrap"] >= FREQ_MIN).astype(object).where(tab["freq_seleccion_bootstrap"].notna(), np.nan)
# ---- c3: manta de Markov del desenlace en la HBN ----
manta = None
try:
arcos = pd.read_csv(CSV_ARCOS)
padres = set(arcos.loc[arcos["destino"] == "outcome", "origen"])
hijos = set(arcos.loc[arcos["origen"] == "outcome", "destino"])
conyuges = set(arcos.loc[arcos["destino"].isin(hijos) & (arcos["origen"] != "outcome"), "origen"])
manta = padres | hijos | conyuges
except FileNotFoundError:
pass
tab["en_manta_markov"] = tab["variable"].map(lambda v: (v in manta) if manta is not None else np.nan)
tab["c3_manta_markov"] = tab["en_manta_markov"].astype(object)
# ---- clasificacion ----
CRITERIOS = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
disponibles = [c for c in CRITERIOS if tab[c].notna().all()]
tab["criterios_cumplidos"] = tab[disponibles].apply(lambda c: c.map(lambda x: x is True or x == True)).sum(axis=1)
tab["criterios_evaluados"] = len(disponibles)
min_robusto = min(3, len(disponibles))
def clasificar(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= min_robusto:
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)
columnas = ["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
"freq_seleccion_bootstrap", "en_manta_markov", "S18_categoria", "S18_referencia", "delta_S18",
"delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "criterios_evaluados", "clasificacion"]
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
tab["_o"] = tab["clasificacion"].map(orden).fillna(5)
tab = tab.sort_values(["_o", "OR_muerte"], ascending=[True, False])[columnas]
tab.round(4).to_csv("./factores_riesgo.csv", index=False)
resumen = tab[tab["clasificacion"] != "no aplica (categoria desconocida)"].groupby("variable").agg(
categorias_robustas=("clasificacion", lambda s: int(s.str.contains("robusto").sum())),
categorias_sugerentes=("clasificacion", lambda s: int(s.str.contains("sugerente").sum())),
freq_seleccion_bootstrap=("freq_seleccion_bootstrap", "first"),
en_manta_markov=("en_manta_markov", "first"),
OR_max=("OR_muerte", "max"), OR_min=("OR_muerte", "min"),
).sort_values(["categorias_robustas", "categorias_sugerentes"], ascending=False)
resumen.round(4).to_csv("./factores_riesgo_resumen_variables.csv")
# ---- tratamiento: asociaciones descriptivas, sin clasificar (decision clinica) ----
if tratamiento:
tr = ajustar_or(intrinsecas + tratamiento)
tr["variable"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
tr = tr[tr["variable"].isin(tratamiento)].copy()
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
tr["referencia"] = [referencia(v) for v in tr["variable"]]
tr["p_ajustado_BH"] = bh(tr["p"])
ds_t = tabla_delta(zip(tr["variable"], tr["categoria"], tr["referencia"]))
tr = pd.concat([tr.reset_index(drop=True), ds_t.reset_index(drop=True)], axis=1)
tr["nota"] = "asociacion ajustada por las demas variables; no implica efecto causal (confusion por indicacion)"
tr[["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
"S18_categoria", "S18_referencia", "delta_S18", "delta_IC95_inf", "delta_IC95_sup", "nota"]].round(4).to_csv(
"./asociaciones_tratamiento.csv", index=False)
with open("./factores_riesgo_criterios.json", "w", encoding="utf8") as f:
json.dump({"alfa": ALFA, "freq_min_bootstrap": FREQ_MIN, "horizonte_meses": HORIZONTE, "tope_meses": TOPE_MESES,
"replicas_bootstrap_validas": int(n_rep), "criterios_evaluados": disponibles,
"variables_tratamiento_excluidas": tratamiento}, f, indent=2, ensure_ascii=False)
@@ -0,0 +1,65 @@
"""Ejecuta las etapas del pipeline en orden (cada una en su propio proceso).
Uso (desde la carpeta que contiene los scripts y los datos):
python ejecutar_pipeline.py # todas las etapas, saltando las que estan vigentes
python ejecutar_pipeline.py --solo 05 # solo esa etapa
python ejecutar_pipeline.py --desde 02 # desde esa etapa en adelante
python ejecutar_pipeline.py --forzar 02 04 # corre esas aunque esten vigentes
python ejecutar_pipeline.py --todo # corre todas, sin saltar ninguna
Una etapa se salta solo si sus salidas existen y son mas recientes que su script y que sus entradas.
Escribe bitacora_pipeline.csv (etapa, estado, segundos). Sin mensajes en pantalla salvo errores.
"""
import argparse, csv, subprocess, sys, time
from pathlib import Path
BALANCEADO = "dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
ETAPAS = [
dict(id="01", script="01_depuracion.py", requiere=["dataframe_recodificado.csv", "mapeo_columnas_recodificadas.json"],
produce=["dataframe_depurado.csv"]),
dict(id="02", script="02_balanceo_categorizacion.py", requiere=["dataframe_depurado.csv"],
produce=[BALANCEADO, "propuestas_categorizacion.csv", "dataframe_poblacion_natural.csv"]),
dict(id="03", script="03_bootstrapping.py", requiere=[BALANCEADO], produce=["bootstrap_indices.npy", "bootstrap_metadata.json"]),
dict(id="04", script="04_modelado.py",
requiere=[BALANCEADO, "propuestas_categorizacion.csv", "bootstrap_indices.npy", "bootstrap_metadata.json", "dataframe_poblacion_natural.csv"],
produce=[]), # sin salida unica verificable: siempre se corre
dict(id="05", script="05_curvas_supervivencia.py", requiere=["dataframe_depurado.csv"],
produce=["curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"]),
dict(id="06", script="06_factores_riesgo.py",
requiere=["dataframe_poblacion_natural.csv", "seleccion_bootstrap.csv", "hbn_arcos.csv"],
produce=["factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"]),
]
def mtime(p): return Path(p).stat().st_mtime
def vigente(e):
if not e["produce"] or not all(Path(p).exists() and Path(p).stat().st_size > 0 for p in e["produce"]): return False
ref = max([mtime(e["script"])] + [mtime(p) for p in e["requiere"] if Path(p).exists()])
return min(mtime(p) for p in e["produce"]) >= ref
def guardar(bit):
with open("bitacora_pipeline.csv", "w", newline="", encoding="utf8") as f:
w = csv.writer(f); w.writerow(["etapa", "estado", "segundos"]); w.writerows(bit)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--solo", nargs="+"); ap.add_argument("--desde")
ap.add_argument("--forzar", nargs="+", default=[]); ap.add_argument("--todo", action="store_true")
a = ap.parse_args()
sel = [e for e in ETAPAS if (not a.solo or e["id"] in a.solo) and (not a.desde or e["id"] >= a.desde)]
bit = []; rehacer = False
for e in sel:
faltan = [p for p in e["requiere"] if not Path(p).exists()]
if faltan: sys.exit(f"Etapa {e['id']}: faltan entradas {faltan}")
if not (a.todo or e["id"] in a.forzar or rehacer) and vigente(e):
bit.append((e["id"], "saltada", 0)); continue
t0 = time.time(); r = subprocess.run([sys.executable, e["script"]])
bit.append((e["id"], "ok" if r.returncode == 0 else f"error({r.returncode})", round(time.time() - t0)))
guardar(bit)
if r.returncode != 0: sys.exit(r.returncode)
rehacer = rehacer or bool(e["produce"]) # si una etapa con salidas se rehizo, las siguientes tambien
guardar(bit)
if __name__ == "__main__":
main()