diff --git a/models/cama/survival/estimator.py b/models/cama/survival/estimator.py index 6c97ddc..6d7320e 100644 --- a/models/cama/survival/estimator.py +++ b/models/cama/survival/estimator.py @@ -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 diff --git a/models/cama/survival/model.toml b/models/cama/survival/model.toml index 065d841..7a45378 100644 --- a/models/cama/survival/model.toml +++ b/models/cama/survival/model.toml @@ -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 = [] diff --git a/models/cama/survival/population.py b/models/cama/survival/population.py index 0fefbca..2f8bb71 100644 --- a/models/cama/survival/population.py +++ b/models/cama/survival/population.py @@ -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(), diff --git a/tests/cama/test_survival.py b/tests/cama/test_survival.py index c1c6a20..6127035 100644 --- a/tests/cama/test_survival.py +++ b/tests/cama/test_survival.py @@ -292,7 +292,7 @@ def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking) def development_record(cohort_frame): """The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget.""" config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30, - "proposals_max_seconds": 20, "restarts": 1}} + "proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}} dr = dataflow(*SCENARIO.modules, config=config) return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"] @@ -326,7 +326,7 @@ def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_coh "ki67_group": rng.choice(["<14", "14-19", "≥20"], n)}) members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24) settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30, - "proposals_max_seconds": 20, "restarts": 1} + "proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2} r = dev.development(members, settings)["desarrollo"] @@ -335,3 +335,81 @@ def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_coh arcs = r["tablas"]["hbn_arcos"] assert arcs["columnas"] == list(arcs["filas"][0]) and len(arcs["columnas"]) > 1 assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values()) + + +def _stage_five_table(csv_path, survival): + """The table of the SEER pipeline's stage 5 for the main curve (`sv_table`): its own nodes over a CSV of the cohort.""" + from hamilton import driver + + from models.cama.seer_survival import survival_curves + + dr = driver.Builder().with_modules(survival_curves).build() + return dr.execute(["sv_table"], inputs={"depurated_csv": str(csv_path), "survival": survival})["sv_table"] + + +@pytest.fixture(scope="module") +def members_frame(cohort_frame): + """The 240 indexed members, labelled (covariates, follow-up, death), as the figure's nodes take them.""" + return dataflow(*SCENARIO.modules, config=SCENARIO.config).execute( + ["labelled_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["labelled_members"] + + +def test_the_published_figure_is_the_seer_pipelines_stage_five_on_the_same_members(members_frame, tmp_path): + """Pins down: the Kaplan-Meier curve, the adjusted curve, the stacking weights, the points of LR, HBN and their + combination and their bootstrap interval in the published record are those that `models.cama.seer_survival`'s own stage 5 + (`run_survival`, on a CSV of the same members and the same settings) gives. Fails if the record's code path stops being + the pipeline's, which would make the dashboard's figure another model's.""" + import dataclasses + + from models.cama.survival import estimator + + survival = {**CONFIG["survival"], "n_boot": 6, "ks_max_seconds": 5} + config = {**CONFIG, "survival": survival} + ours = dataflow(*SCENARIO.modules, config=config).execute( + ["population_curves"], inputs={"source_cohort": pd.DataFrame(), "cohort_lineage": {}}, + overrides={"labelled_members": members_frame})["population_curves"]["curvas"] + + csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str), + "Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})}) + for name in estimator.FEATURES: + csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str) + csv.to_csv(tmp_path / "depurado.csv", index=False) + fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"]) + luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed) + theirs = _stage_five_table(tmp_path / "depurado.csv", luis) + + for model in ("LR", "HBN", "COMB"): + rows = theirs[theirs["modelo"] == model] + assert ours["points"][model]["S"] == pytest.approx(rows["S"].tolist(), abs=1e-9) + assert ours["points"][model]["low"] == pytest.approx(rows["IC_inf"].tolist(), abs=1e-9) + assert ours["points"][model]["high"] == pytest.approx(rows["IC_sup"].tolist(), abs=1e-9) + km = theirs[theirs["modelo"] == "COMB"] + assert [ours["km"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_crudo"].tolist(), abs=1e-9) + assert [ours["km_adjusted"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_ajustada"].tolist(), abs=1e-9) + + +def test_the_production_model_predicts_what_the_pipelines_points_say(members_frame, tmp_path): + """Pins down: the `IntervalSurvival` a version in production is (the model that scores each patient) gives, averaged over + the members it was fitted on, the survival at each horizon that the pipeline's stage 5 gives for LR, HBN and their + combination, exactly (the same data, the same settings). Fails if the model that scores patients drifts from the model whose + figure is published.""" + import dataclasses + + from models.cama.survival import estimator + from models.cama.survival.estimator import IntervalSurvival + + survival = {**CONFIG["survival"], "n_boot": 0} + model = IntervalSurvival(survival, tuple(h / 12 for h in survival["horizons"])).fit( + members_frame[estimator.FEATURES], members_frame[["months", "event"]]) + mean_combined = model.survival_proba(members_frame[estimator.FEATURES]).mean(axis=0) + + csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str), + "Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})}) + for name in estimator.FEATURES: + csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str) + csv.to_csv(tmp_path / "depurado.csv", index=False) + fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"]) + luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed) + theirs = _stage_five_table(tmp_path / "depurado.csv", luis) + + assert mean_combined == pytest.approx(theirs[theirs["modelo"] == "COMB"]["S"].tolist(), abs=1e-6)