"""Stage 04, modeling: the stepwise logistic regression (LR) and the hybrid Bayesian network (HBN) on the balanced cohort, their comparison on the internal test, and the LR on the natural population. Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `balanced_csv`, `natural_csv` and `modeling` (its settings). The heavy routines live apart: `lr_selection.py`, `hbn.py` and `natural.py`; the bootstrap and the proposal comparison, which repeat this pipeline, are `resampling.py`. """ import os from dataclasses import dataclass import numpy as np import pandas as pd import statsmodels.api as sm from matplotlib import rc_context from matplotlib.figure import Figure from sklearn.calibration import calibration_curve from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve from sklearn.model_selection import train_test_split from models.cama.seer_survival import hbn, lr_selection from models.cama.seer_survival.natural import NaturalResults, fit_natural from models.cama.seer_survival.settings import ModelingSettings # seaborn's "whitegrid", which the script set globally for its figures WHITEGRID = {"axes.facecolor": "white", "axes.edgecolor": ".8", "axes.grid": True, "grid.color": ".8", "grid.linestyle": "-", "axes.axisbelow": True} @dataclass(frozen=True, eq=False) class Design: X: pd.DataFrame y: pd.Series @dataclass(frozen=True, eq=False) class Split: X_train: pd.DataFrame X_test: pd.DataFrame y_train: pd.Series y_test: pd.Series @dataclass(frozen=True, eq=False) class HbnFit: model: object # the fitted DiscreteBayesianNetwork edges: list bn_train: pd.DataFrame bn_test: pd.DataFrame # ---------------------------------------------------------------- the data def balanced_raw(balanced_csv: str) -> pd.DataFrame: return pd.read_csv(balanced_csv, dtype=str) def fit_race_column(balanced_raw: pd.DataFrame, modeling: ModelingSettings) -> str | None: """SEER's race column as it comes (the recoding never recodes it), found by keyword; None when it is already one of the canonical map's columns.""" race = next((c for c in balanced_raw.columns if "race" in c.lower().replace("_", " ")), None) return None if race in modeling.canonical_map else race def fit_rename_map(balanced_raw: pd.DataFrame, modeling: ModelingSettings) -> dict: """The columns that exist -> canonical names; the depuration may have kept `Tamano_tumor_cat` instead of `Tumor_group`, and then that one is the tumor size.""" mapping = dict(modeling.canonical_map) if "Tumor_group" not in balanced_raw.columns and "Tamano_tumor_cat" in balanced_raw.columns: mapping["Tamano_tumor_cat"] = "Tamano_tumor" return {k: v for k, v in mapping.items() if k in balanced_raw.columns} def fit_frame(balanced_raw: pd.DataFrame, fit_rename_map: dict, fit_race_column: str | None) -> pd.DataFrame: """The balanced cohort under the canonical names, with `outcome` (1 = survives). It SELECTS by the original names and only then renames, so a raw SEER column that already has a canonical name is never carried along.""" df = balanced_raw[list(fit_rename_map.keys())].rename(columns=fit_rename_map).copy() if fit_race_column: df["Race"] = balanced_raw[fit_race_column] dup = df.columns[df.columns.duplicated()].tolist() assert not dup, f"Columnas duplicadas tras construir df: {dup}. Revisar canonical_map / la columna de raza." assert (df["Outcome_cat"] == "Desconocido").sum() == 0, \ "Se esperaba que la cohorte balanceada ya excluyera el desenlace desconocido." df["outcome"] = (df["Outcome_cat"] == "Sobrevive").astype(int) return df def fit_features(fit_frame: pd.DataFrame, modeling: ModelingSettings) -> list[str]: """The categorical covariates present, in the settings' order.""" return [c for c in modeling.categorical_order if c in fit_frame.columns] def fit_design(fit_frame: pd.DataFrame, fit_features: list[str]) -> Design: enc = lr_selection.encode(fit_frame, fit_features) X = pd.get_dummies(enc[fit_features], drop_first=True).astype(float) constant = [c for c in X.columns if X[c].nunique() <= 1] return Design(X.drop(columns=constant) if constant else X, enc["outcome"]) def fit_split(fit_design: Design, modeling: ModelingSettings) -> Split: X_train, X_test, y_train, y_test = train_test_split( fit_design.X, fit_design.y, test_size=modeling.test_size, random_state=modeling.random_state, stratify=fit_design.y) constant = [c for c in X_train.columns if X_train[c].nunique() <= 1] if constant: X_train, X_test = X_train.drop(columns=constant), X_test.drop(columns=constant) return Split(X_train, X_test, y_train, y_test) # ---------------------------------------------------------------- stepwise logistic regression def lr_selected(fit_split: Split, modeling: ModelingSettings) -> list[str]: """The stepwise selection over the pre-filtered columns, on a stratified subsample of the train.""" s = modeling prefiltered = lr_selection.prefiltered_columns(fit_split.X_train, fit_split.y_train, s.prefilter_alpha, s.max_candidates, always_sort=False) X_search, y_search = lr_selection.search_sample(fit_split.X_train, fit_split.y_train, prefiltered, s.max_search_rows, s.random_state) return lr_selection.stepwise_selection(X_search, y_search, s.alpha_in, s.alpha_out) def lr_model(fit_split: Split, lr_selected: list[str], modeling: ModelingSettings) -> object: """The final LR, refitted on the WHOLE train with the selected variables.""" return sm.Logit(fit_split.y_train, sm.add_constant(fit_split.X_train[lr_selected])).fit( disp=0, method="bfgs", maxiter=modeling.lr_maxiter) def lr_odds_ratios(lr_model: object) -> pd.DataFrame: conf = lr_model.conf_int() conf["OR"] = lr_model.params conf.columns = ["2.5%", "97.5%", "OR"] table = np.exp(conf) table["p_value"] = lr_model.pvalues return table.round(3) def lr_test_prediction(fit_split: Split, lr_model: object, lr_selected: list[str]) -> pd.Series: return lr_model.predict(sm.add_constant(fit_split.X_test[lr_selected], has_constant="add")) # ---------------------------------------------------------------- hybrid Bayesian network def hbn_fit(fit_frame: pd.DataFrame, fit_features: list[str], modeling: ModelingSettings) -> HbnFit: s = modeling enc = lr_selection.encode(fit_frame, fit_features) bn_cols = [c for c in fit_features if c in enc.columns] + ["outcome"] small = enc[bn_cols].astype(str) bn_train, bn_test = train_test_split(small, test_size=s.test_size, random_state=s.random_state, stratify=small["outcome"]) edges = hbn.learn_structure(bn_train, bn_cols, s, s.n_restarts, s.random_state) return HbnFit(hbn.fit_network(edges, bn_train), edges, bn_train, bn_test) def hbn_test_prediction(hbn_fit: HbnFit) -> pd.DataFrame: """The HBN's test rows with `pred`, the survival probability; rows whose query failed are dropped.""" preds = hbn.predict_survival(hbn_fit.model, hbn_fit.bn_test) return hbn_fit.bn_test.assign(pred=preds).dropna(subset=["pred"]) def hbn_arcs(hbn_fit: HbnFit) -> pd.DataFrame: return pd.DataFrame(list(hbn_fit.model.edges()), columns=["origen", "destino"]) def hbn_arc_strength(hbn_fit: HbnFit, modeling: ModelingSettings) -> pd.DataFrame: return hbn.arc_strength(hbn_fit.model, hbn_fit.bn_train, modeling.bdeu_ess) def hbn_graph_figure(hbn_fit: HbnFit, modeling: ModelingSettings) -> Figure: import networkx as nx with rc_context(WHITEGRID): fig = Figure(figsize=(10, 8)) ax = fig.subplots() G = nx.DiGraph(hbn_fit.model.edges()) pos = nx.spring_layout(G, seed=modeling.random_state, k=0.8) nx.draw(G, pos, ax=ax, with_labels=True, node_color="lightblue", node_size=2500, font_size=8, arrowsize=15) ax.set_title("Estructura de la Red Bayesiana Híbrida (aproximación)") return fig # ---------------------------------------------------------------- the internal test: LR vs HBN def auc_internal(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> pd.DataFrame: return pd.DataFrame([ {"modelo": "LR", "AUC": roc_auc_score(fit_split.y_test, lr_test_prediction)}, {"modelo": "HBN", "AUC": roc_auc_score(hbn_test_prediction["outcome"].astype(int), hbn_test_prediction["pred"])}, ]).round(4) def roc_figure(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame, auc_internal: pd.DataFrame) -> Figure: hb = hbn_test_prediction fpr_lr, tpr_lr, _ = roc_curve(fit_split.y_test, lr_test_prediction) fpr_hbn, tpr_hbn, _ = roc_curve(hb["outcome"].astype(int), hb["pred"]) auc_lr, auc_hbn = auc_internal["AUC"].tolist() with rc_context(WHITEGRID): fig = Figure(figsize=(7, 6)) ax = fig.subplots() ax.plot(fpr_lr, tpr_lr, label=f"LR (AUC={auc_lr:.3f})", color="black") ax.plot(fpr_hbn, tpr_hbn, label=f"HBN (AUC={auc_hbn:.3f})", color="crimson") ax.plot([0, 1], [0, 1], linestyle="--", color="gray") ax.set_xlabel("1 - Especificidad") ax.set_ylabel("Sensibilidad") ax.set_title("Curvas ROC -- comparacion LR vs. HBN") ax.legend() return fig def calibration_figure(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> Figure: hb = hbn_test_prediction true_lr, pred_lr = calibration_curve(fit_split.y_test, lr_test_prediction, n_bins=10) true_hbn, pred_hbn = calibration_curve(hb["outcome"].astype(int), hb["pred"], n_bins=10) with rc_context(WHITEGRID): fig = Figure(figsize=(7, 6)) ax = fig.subplots() ax.plot(pred_lr, true_lr, marker="o", label="LR", color="black") ax.plot(pred_hbn, true_hbn, marker="o", label="HBN", color="crimson") ax.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Calibracion perfecta") ax.set_xlabel("Probabilidad predicha") ax.set_ylabel("Probabilidad observada") ax.set_title("Curvas de calibracion") ax.legend() return fig def dca_figure(lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> Figure | None: """The decision-curve (net benefit) figure, or None when `dcurves` isn't installed.""" try: import matplotlib.pyplot as plt from dcurves import dca, plot_graphs except ImportError: return None plt.switch_backend("Agg") # `plot_graphs` draws with pyplot and shows: never open a window from a pipeline hb = hbn_test_prediction data = pd.DataFrame({"outcome": hb["outcome"].astype(int).values, "lr_pred": lr_test_prediction.reindex(hb.index).values, "hbn_pred": hb["pred"].values}) result = dca(data=data, outcome="outcome", modelnames=["lr_pred", "hbn_pred"]) plt.close("all") with rc_context(WHITEGRID): plot_graphs(plot_df=result, graph_type="net_benefit", y_limits=[-0.05, 0.5]) fig = plt.gcf() plt.close("all") return fig def _differentiation(y_true, y_prob, threshold: float) -> dict: tn, fp, fn, tp = confusion_matrix(y_true, (y_prob >= threshold).astype(int)).ravel() return {"ACC": (tp + tn) / (tp + tn + fp + fn), "TPR": tp / (tp + fn), "TNR": tn / (tn + fp), "PPV": tp / (tp + fp) if (tp + fp) > 0 else np.nan, "NPV": tn / (tn + fn) if (tn + fn) > 0 else np.nan} def _youden(y_true, y_prob) -> float: fpr, tpr, thresholds = roc_curve(y_true, y_prob) return thresholds[np.argmax(tpr - fpr)] def differentiation_table(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> pd.DataFrame: """Accuracy, sensitivity, specificity and predictive values of each model at the 0.5 threshold and at its own Youden-optimal one.""" y_lr, p_lr = fit_split.y_test.values, lr_test_prediction.values y_hbn, p_hbn = hbn_test_prediction["outcome"].astype(int).values, hbn_test_prediction["pred"].values thr_lr, thr_hbn = _youden(y_lr, p_lr), _youden(y_hbn, p_hbn) rows = [{"Model": "LR", "Umbral": 0.50, **_differentiation(y_lr, p_lr, 0.5)}, {"Model": "HBN tabular", "Umbral": 0.50, **_differentiation(y_hbn, p_hbn, 0.5)}, {"Model": "LR", "Umbral": round(thr_lr, 3), **_differentiation(y_lr, p_lr, thr_lr)}, {"Model": "HBN tabular", "Umbral": round(thr_hbn, 3), **_differentiation(y_hbn, p_hbn, thr_hbn)}] return pd.DataFrame(rows).set_index(["Model", "Umbral"]).round(2) # ---------------------------------------------------------------- the natural population def natural_raw(natural_csv: str, modeling: ModelingSettings) -> pd.DataFrame | None: """The natural population's file; None when the phase is off or the file isn't there.""" if not modeling.run_lr_natural or not os.path.exists(natural_csv): return None return pd.read_csv(natural_csv, dtype=str) def natural_results(natural_raw: pd.DataFrame | None, fit_frame: pd.DataFrame, fit_rename_map: dict, fit_race_column: str | None, fit_features: list[str], fit_split: Split, lr_model: object, lr_selected: list[str], modeling: ModelingSettings) -> NaturalResults | None: if natural_raw is None: return None return fit_natural(natural_raw, fit_frame, fit_rename_map, fit_race_column, fit_features, fit_split.X_train, fit_split.y_train, lr_model, lr_selected, modeling)