acc8c371bc
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the cohort's events, fits the interval survival, writes the five routines and publishes the population curves (analisis/curvas.json) with the version. An estimate may carry the model's own index date.
142 lines
7.2 KiB
Python
142 lines
7.2 KiB
Python
"""Stage 04, resampling: the pipeline repeated on bootstrap resamples (the indices of stage 03) and on each
|
|
categorization proposal of stage 02b, to put intervals on the AUCs and compare the proposals on the same splits.
|
|
|
|
Each public function is a Hamilton node; it continues `modeling.py` (`fit_frame`, `fit_features`) and takes
|
|
`bootstrap_indices` (stage 03's array), `proposals_csv` and `modeling` (its settings) as inputs. One replica is
|
|
`replica.py`. Both loops stop by themselves when their time cap is reached and use what they have.
|
|
"""
|
|
|
|
import time
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
from models.cama.seer_survival.replica import run_replica
|
|
from models.cama.seer_survival.settings import ModelingSettings
|
|
|
|
|
|
# ---------------------------------------------------------------- bootstrap
|
|
|
|
def bootstrap_runs(fit_frame: pd.DataFrame, bootstrap_indices: np.ndarray, fit_features: list[str],
|
|
modeling: ModelingSettings) -> list[dict]:
|
|
"""The replica pipeline on each resample, in order, until `n_bootstrap_run` or the time cap."""
|
|
assert bootstrap_indices.shape[1] == len(fit_frame), (
|
|
f"bootstrap_indices tiene {bootstrap_indices.shape[1]} filas por réplica, pero el balanceado tiene "
|
|
f"{len(fit_frame)}: la etapa de bootstrapping debe correr sobre el mismo CSV balanceado.")
|
|
s = modeling
|
|
runs, t0 = [], time.time()
|
|
for b in range(s.n_bootstrap_run):
|
|
if time.time() - t0 > s.bootstrap_max_seconds:
|
|
break
|
|
df_b = fit_frame.iloc[bootstrap_indices[b]].reset_index(drop=True)
|
|
runs.append(run_replica(df_b, s.random_state + b, fit_features, s, s.bootstrap_include_hbn,
|
|
s.bootstrap_restarts))
|
|
return runs
|
|
|
|
|
|
def bootstrap_selection(bootstrap_runs: list[dict], fit_features: list[str]) -> pd.DataFrame:
|
|
"""The terms each replica's LR kept, and the outcome's parents in each replica's HBN: how stable the selection is."""
|
|
longest_first = sorted(fit_features, key=len, reverse=True)
|
|
|
|
def variable_of(term):
|
|
return next((c for c in longest_first if term.startswith(c + "_")), term)
|
|
|
|
rows = []
|
|
for b, res in enumerate(bootstrap_runs):
|
|
if res["coefs"] is not None:
|
|
rows.append({"replica": b, "modelo": "LR", "variable": "", "termino": "(replica)", "coef": np.nan})
|
|
rows += [{"replica": b, "modelo": "LR", "variable": variable_of(t), "termino": t, "coef": v}
|
|
for t, v in res["coefs"].items()]
|
|
if res["padres"] is not None:
|
|
rows.append({"replica": b, "modelo": "HBN", "variable": "", "termino": "(replica)", "coef": np.nan})
|
|
rows += [{"replica": b, "modelo": "HBN", "variable": p, "termino": p, "coef": np.nan} for p in res["padres"]]
|
|
return pd.DataFrame(rows)
|
|
|
|
|
|
def _interval(values) -> tuple[float, float, int]:
|
|
arr = np.array([a for a in values if not np.isnan(a)])
|
|
if len(arr) == 0:
|
|
return (np.nan, np.nan, 0)
|
|
lo, hi = np.percentile(arr, [2.5, 97.5])
|
|
return (lo, hi, len(arr))
|
|
|
|
|
|
def bootstrap_auc(bootstrap_runs: list[dict]) -> pd.DataFrame:
|
|
"""Mean AUC and its 95 % percentile interval over the replicas with a valid AUC, per model."""
|
|
rows = []
|
|
for name, key in [("LR (stepwise)", "auc_lr"), ("HBN (CPT tabular)", "auc_hbn")]:
|
|
values = [r[key] for r in bootstrap_runs]
|
|
lo, hi, n_valid = _interval(values)
|
|
rows.append({"modelo": name, "AUC medio": np.nanmean(values) if n_valid else np.nan,
|
|
"IC 95% lo": lo, "IC 95% hi": hi, "replicas validas": n_valid})
|
|
return pd.DataFrame(rows).round(3)
|
|
|
|
|
|
def bootstrap_auc_difference(bootstrap_runs: list[dict]) -> pd.DataFrame | None:
|
|
"""The paired difference LR - HBN over the replicas where both exist; None when there is none."""
|
|
d = np.array([r["auc_lr"] for r in bootstrap_runs]) - np.array([r["auc_hbn"] for r in bootstrap_runs])
|
|
d = d[~np.isnan(d)]
|
|
if not len(d):
|
|
return None
|
|
return pd.DataFrame([{"dif_AUC_LR_menos_HBN": d.mean(), "IC95_inf": np.percentile(d, 2.5),
|
|
"IC95_sup": np.percentile(d, 97.5), "pct_replicas_LR_gana": (d > 0).mean() * 100}]).round(4)
|
|
|
|
|
|
# ---------------------------------------------------------------- categorization proposals
|
|
|
|
def proposal_runs(fit_frame: pd.DataFrame, proposals_csv: str, fit_features: list[str],
|
|
modeling: ModelingSettings) -> pd.DataFrame:
|
|
"""The replica pipeline for each proposal on `n_splits_prop` splits (the same seeds for all: a paired comparison)."""
|
|
s = modeling
|
|
prop = pd.read_csv(proposals_csv, dtype=str)
|
|
assert len(prop) == len(fit_frame), (f"propuestas_categorizacion.csv tiene {len(prop)} filas y el balanceado "
|
|
f"{len(fit_frame)}: deben salir del MISMO balanceo (mismo orden de filas)")
|
|
ids = sorted({c.split("__", 1)[1] for c in prop.columns if "__" in c})
|
|
if s.proposals_only:
|
|
ids = [i for i in ids if i in s.proposals_only]
|
|
results, t0, stop = [], time.time(), False
|
|
for pid in ids:
|
|
df_p = fit_frame.copy()
|
|
k_age = k_tumor = None
|
|
if f"Age_group__{pid}" in prop.columns:
|
|
df_p["Edad"] = prop[f"Age_group__{pid}"].values
|
|
k_age = df_p["Edad"].nunique()
|
|
if f"Tumor_group__{pid}" in prop.columns and "Tamano_tumor" in df_p.columns:
|
|
df_p["Tamano_tumor"] = prop[f"Tumor_group__{pid}"].values
|
|
k_tumor = df_p["Tamano_tumor"].nunique(dropna=False)
|
|
for split in range(s.n_splits_prop):
|
|
if time.time() - t0 > s.proposals_max_seconds:
|
|
stop = True
|
|
break
|
|
res = run_replica(df_p, s.random_state + split, fit_features, s, s.proposals_include_hbn,
|
|
s.bootstrap_restarts)
|
|
results.append({"propuesta": pid, "split": split, "K_edad": k_age, "K_tumor": k_tumor, **res})
|
|
if stop:
|
|
break
|
|
return pd.DataFrame(results)
|
|
|
|
|
|
def proposal_summary(proposal_runs: pd.DataFrame) -> pd.DataFrame:
|
|
summary = (proposal_runs.groupby("propuesta")
|
|
.agg(K_edad=("K_edad", "first"), K_tumor=("K_tumor", "first"),
|
|
AUC_LR=("auc_lr", "mean"), sd_LR=("auc_lr", "std"),
|
|
AUC_HBN=("auc_hbn", "mean"), sd_HBN=("auc_hbn", "std"),
|
|
vars_LR=("n_selected_lr", "mean"), padres_HBN=("n_parents_hbn", "mean"),
|
|
n_splits=("split", "count")).round(3))
|
|
return summary.sort_values("AUC_LR", ascending=False)
|
|
|
|
|
|
def proposal_deltas(proposal_runs: pd.DataFrame) -> pd.DataFrame:
|
|
"""Each proposal's AUC minus the base proposal's (`P1_actual`, else the first), on the same splits."""
|
|
runs = proposal_runs
|
|
base = "P1_actual" if "P1_actual" in runs["propuesta"].values else runs["propuesta"].iloc[0]
|
|
b = runs[runs["propuesta"] == base].set_index("split")
|
|
rows = []
|
|
for pid in runs["propuesta"].unique():
|
|
if pid == base:
|
|
continue
|
|
j = b.join(runs[runs["propuesta"] == pid].set_index("split"), lsuffix="_b", rsuffix="_x", how="inner")
|
|
rows.append({"propuesta": pid, f"ΔAUC_LR vs {base}": (j["auc_lr_x"] - j["auc_lr_b"]).mean(),
|
|
f"ΔAUC_HBN vs {base}": (j["auc_hbn_x"] - j["auc_hbn_b"]).mean(), "splits_comparados": len(j)})
|
|
return pd.DataFrame(rows).round(4)
|