From 07c91adbe6315ffb5033cd60e986b3e64c69a44a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 22 Nov 2026 22:59:47 -0600 Subject: [PATCH] CaMa survival figure: Weibull fits on the scenario's own deaths and the pipeline's published points, as its survival stage draws a subgroup --- models/cama/survival/live.py | 42 +++++++++++++++++++++++++++--------- tests/cama/test_survival.py | 19 ++++++++++++++++ 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/models/cama/survival/live.py b/models/cama/survival/live.py index da02269..5b04508 100644 --- a/models/cama/survival/live.py +++ b/models/cama/survival/live.py @@ -80,9 +80,27 @@ def monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarra return np.minimum.accumulate(np.exp(out), axis=1) -def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) -> dict: - """The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone) scored with `model` (the fitted - `IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything.""" +def published_points(rows: list[dict], name: str) -> dict | None: + """The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`: its model with the stage and the + treatments, with their bootstrap intervals), by series; `None` when it published none for it.""" + found = [r for r in rows if r.get("subgrupo") == name] + if not found: + return None + out = {} + for series in population.SERIES: + mine = sorted((r for r in found if r["modelo"] == series), key=lambda r: r["meses"]) + if not mine: + return None + out[series] = {"S": [float(r["S"]) for r in mine], "low": [float(r["IC_inf"]) for r in mine], + "high": [float(r["IC_sup"]) for r in mine]} + return out + + +def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None, points: dict | None = None) -> dict: + """The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone), as the pipeline's survival stage + draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths. The points + are `points` when the version published them for the subgroup (`published_points`), else the members scored with `model` + (the fitted `IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything.""" if name in (None, WHOLE): mask = np.ones(len(labelled), bool) else: @@ -97,15 +115,19 @@ def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) s = survival_settings(scenario.config["survival"]) horizons, cap = list(s.horizons), max(s.cap_months, max(s.horizons)) predicted = model.component_survival(selected[FEATURES]) - resample = np.random.default_rng(SEED).integers(0, len(selected), (REPLICAS, len(selected))) - points = {} - for series in population.SERIES: - low, high = np.percentile(predicted[series][resample].mean(axis=1), [2.5, 97.5], axis=0) - points[series] = {"S": predicted[series].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()} + if points is None: + resample = np.random.default_rng(SEED).integers(0, len(selected), (REPLICAS, len(selected))) + points = {} + for series in population.SERIES: + low, high = np.percentile(predicted[series][resample].mean(axis=1), [2.5, 97.5], axis=0) + points[series] = {"S": predicted[series].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()} followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool) - S, low, high = luis.fw.km_curva(np.minimum(followed, cap), died & (followed < cap), cap) + months, ended = np.minimum(followed, cap), died & (followed < cap) + S, low, high = luis.fw.km_curva(months, ended, cap) adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0) - classic, fractional = luis._fit_to_curve(adjusted, len(selected), s, s.ks_max_seconds) + d, c = luis.fw.tabla_eventos(months, ended) + classic = luis.fw.ajustar_weibull(d, c) + fractional = luis.fw.ajustar_ks(d, c, k_fijo=luis._fixed_k(classic, s), lam_ref=classic["lam"], max_seg=s.ks_sub_max_seconds) grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP) return {"version": population.RECORD_VERSION, "escenario": name or WHOLE, "n": int(len(selected)), "events": int((died & (followed < cap)).sum()), "median_follow_up_months": float(np.median(followed)), diff --git a/tests/cama/test_survival.py b/tests/cama/test_survival.py index 4da69d4..0a6ef28 100644 --- a/tests/cama/test_survival.py +++ b/tests/cama/test_survival.py @@ -443,6 +443,25 @@ def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(me assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"]) +def test_the_live_figure_fits_its_curves_to_the_members_deaths_and_takes_the_published_points(members_frame, production_model): + """Pins down: the Weibull curves of a scenario's figure follow its members' own deaths (close to their Kaplan-Meier, as the + pipeline's survival stage fits a subgroup), and the points are the ones the version published for the subgroup when it did. + Fails if the curves are fitted to the model's prediction instead of the data, or the published points are ignored.""" + from models.cama.survival import live + + rows = [{"modelo": m, "meses": h, "S": 0.8, "IC_inf": 0.7, "IC_sup": 0.9, "subgrupo": "Toda la cohorte"} + for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)] + published = live.published_points(rows, "Toda la cohorte") + + record = live.curves(SCENARIO, production_model, members_frame, None, published) + + km, weibull = np.asarray(record["km"]["S"]), np.asarray(record["weibull"]["S"]) + at_months = np.interp(np.arange(len(km)), record["weibull"]["t"], weibull) + assert np.abs(at_months - km).max() < 0.05 + assert record["points"]["COMB"] == {"S": [0.8] * 3, "low": [0.7] * 3, "high": [0.9] * 3} + assert live.published_points(rows, "Otro") is None + + def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch): """Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no