829 lines
46 KiB
Python
829 lines
46 KiB
Python
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)
|