CaMa survival: the published figure runs the SEER pipeline's stage-5 functions, and the production model keeps its structure settings

This commit is contained in:
rockdrigo
2026-11-21 10:33:48 -06:00
parent 0cf3e60341
commit ec430c3ee3
4 changed files with 144 additions and 62 deletions
+1 -1
View File
@@ -110,7 +110,7 @@ def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings: Su
"""The pipeline's `Cohort` of these members, with the categories and dummy columns it was coded by."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], None)
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
+17 -14
View File
@@ -33,23 +33,26 @@ observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with its settings.
[config.desarrollo]
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort.
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort,
# with the pipeline's own budgets (`models/cama/seer_survival/model.toml`). The bootstrap and the proposals stop at their
# time caps and use what they have. One adaptation: `exclude_censored_years` is off, because this follow-up is short and
# would leave every year out of the outcome.
enabled = true
null_perm = 20
n_bootstrap = 20
bootstrap_max_seconds = 240
bootstrap_restarts = 2
n_splits_proposals = 2
proposals_max_seconds = 120
restarts = 4
null_perm = 100
n_bootstrap = 60
bootstrap_max_seconds = 2700
bootstrap_restarts = 3
n_splits_proposals = 5
proposals_max_seconds = 3600
restarts = 10
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [45, 60, 75]
hbn_fixed_parents = [] # empty = learn the network's parents by the BDeu score
hbn_age_parent = false
hbn_parents = "reaprender"
hbn_fixed_parents = ["histologic_type", "age_group"] # the SEER pipeline's expert parents that this data has (its stage and treatment are not reported yet); empty = learn them by the BDeu score
hbn_age_parent = false # the grouped age is already in `hbn_fixed_parents`
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [6, 12, 18] # months
censoring = "riesgo" # a model per interval using all the follow-up
@@ -57,7 +60,7 @@ combine = true # one LR + HBN indicator, per-interval stacking
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 200
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
@@ -71,8 +74,8 @@ inset_zoom = false
inset_months = 18
cap_months = 24 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 30
ks_sub_max_seconds = 30
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
subgroups = []
+46 -45
View File
@@ -13,75 +13,76 @@ the clinicians' wording is a setting, not code.
import numpy as np
import pandas as pd
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival.estimator import interval_cohort
from models.cama.survival.estimator import FEATURES, UNKNOWN
SERIES = ("LR", "HBN", "COMB")
GRID_STEP = 0.25 # months between the points of a fitted curve
RECORD_VERSION = 1
def curve_cohort(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
"""The members, coded as the interval models take them."""
return interval_cohort(labelled_members, labelled_members[["months", "event"]], survival_settings)[0]
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts as
alive) and the covariates as categories."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def km_curve(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> dict:
"""Kaplan-Meier from the index to `months_max`, with the Greenwood 95 % interval on the log-log scale."""
horizon = max(survival_settings.months_max, max(survival_settings.horizons))
S, low, high = fw.km_curva(labelled_members["months"].to_numpy(int), labelled_members["event"].to_numpy(bool), horizon)
return {"months": list(range(horizon + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()}
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
"""The members coded as the stage-5 models take them (`survival_curves.sv_cohort`)."""
return luis.sv_cohort(survival_frame, survival_settings)
def adjusted_km(curve_cohort: sm.Cohort, km_curve: dict, survival_settings: SurvivalSettings) -> np.ndarray:
"""The covariate-adjusted survival curve, month by month (direct standardization over the members)."""
return sm.adjusted_curve(curve_cohort, np.arange(len(curve_cohort.months)), km_curve["months"][-1],
survival_settings.adjust_step)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
"""Kaplan-Meier with the Greenwood interval (`survival_curves.sv_km`)."""
return luis.sv_km(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
"""Kaplan-Meier from the index to `months_max`, with its interval, as the record carries it."""
return {"months": list(range(km_raw.T + 1)), "S": km_raw.S.tolist(), "low": km_raw.lo.tolist(), "high": km_raw.hi.tolist()}
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
"""The covariate-adjusted survival curve, month by month (`survival_curves.sv_adjusted`)."""
return luis.sv_adjusted(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR."""
everyone = np.ones(len(curve_cohort.months), bool)
return sm.stacking_weights(curve_cohort, survival_settings, everyone,
*sm.out_of_fold(curve_cohort, survival_settings, len(curve_cohort.months)))
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR (`sv_weights_cohort`)."""
return luis.sv_weights_cohort(curve_cohort, luis.sv_oof(curve_cohort, survival_settings), survival_settings)
def point_estimates(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> dict:
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member."""
lr, hbn, combined, _ = sm.estimate_combined(curve_cohort, survival_settings, np.arange(len(curve_cohort.months)), None,
population_weights["w_LR"].to_numpy())
return {"LR": lr, "HBN": hbn, "COMB": combined}
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member (`sv_points`)."""
return luis.sv_points(curve_cohort, population_weights, survival_settings)
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> np.ndarray:
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample."""
s, n = survival_settings, len(curve_cohort.months)
rng = np.random.default_rng(s.seed)
weights = population_weights["w_LR"].to_numpy()
rows = []
for _ in range(s.n_boot):
r = sm.estimate_combined(curve_cohort, s, rng.integers(0, n, n), None, weights)
rows.append(np.concatenate([r[0], r[1], r[2]]))
return np.array(rows) if rows else np.full((1, len(SERIES) * len(s.horizons)), np.nan)
def point_estimates(luis_points: luis.Points) -> dict:
return {"LR": luis_points.lr, "HBN": luis_points.hbn, "COMB": luis_points.combined}
def _fixed_k(classic: dict, survival_settings: SurvivalSettings) -> float:
return classic["k"] if survival_settings.k_ident == "clasico" else float(survival_settings.k_ident)
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample, the
HBN's parents kept or learned again as `hbn_parents` says (`sv_bootstrap`)."""
return luis.sv_bootstrap(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> dict:
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
"""The classic and the fractional Weibull fitted to the adjusted curve as if it came from as many members as the
cohort has, evaluated on a grid of months, with their parameters."""
S, n = adjusted_km, len(curve_cohort.months)
d = np.concatenate([np.maximum(n * (S[:-1] - S[1:]), 0.0), [0.0, 0.0]])
c = np.zeros(len(d))
c[len(S) - 1] = n * S[-1]
classic = fw.ajustar_weibull(d, c)
fractional = fw.ajustar_ks(d, c, k_fijo=_fixed_k(classic, survival_settings), lam_ref=classic["lam"],
max_seg=survival_settings.ks_max_seconds)
grid = np.arange(0, len(S) - 1 + GRID_STEP, GRID_STEP)
cohort has (`survival_curves._fit_to_curve`), evaluated on a grid of months, with their parameters."""
classic, fractional = luis._fit_to_curve(adjusted_km, len(survival_frame.df), survival_settings, survival_settings.ks_max_seconds)
grid = np.arange(0, len(adjusted_km) - 1 + GRID_STEP, GRID_STEP)
parameters = lambda fit: {key: float(fit[key]) for key in ("k", "alpha", "beta", "lam", "nll") if key in fit}
return {"t": grid.tolist(), "classic": np.asarray(classic["S"](grid), float).tolist(),
"fractional": np.asarray(fractional["S"](grid), float).tolist(),