From e99eb499d65b4fc3ec90bc1cc2ffa5084ec61474 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:14:06 -0600 Subject: [PATCH] CaMa survival: the live figure is the clinical scenario's, over the production model and the live cohort --- models/cama/survival/live.py | 101 +++++++++++++++++++++-------------- tests/cama/test_survival.py | 77 ++++++++++++++++++-------- 2 files changed, 116 insertions(+), 62 deletions(-) diff --git a/models/cama/survival/live.py b/models/cama/survival/live.py index e226cf2..4415327 100644 --- a/models/cama/survival/live.py +++ b/models/cama/survival/live.py @@ -1,19 +1,20 @@ -"""The survival figure for a selection of members, scored with the model in production over the data ingested so far. +"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far. -Training and tuning happen in governance; here the production version is only applied. A reader selects members (by -covariate or by period of index date) and gets the record the training run publishes for the whole cohort (`population`), -for them: the Kaplan-Meier curve of what happened to the selected members, the survival the model predicts for them (their -mean at each horizon by the logistic regression, the Bayesian network and their combination, with a 95 % interval from -resampling the selected members), that prediction month by month, and the Weibull fits the SEER pipeline makes to it. -Nothing is fitted on the selection and nothing is stored. +Training and tuning happen in governance; here the production version is only applied. The scenarios are the subgroups of +the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one +share a figure, and a patient sees the figure of each scenario she belongs to. The record is the one the training run +publishes for the whole cohort (`population`), for the scenario's members: the Kaplan-Meier curve of what happened to them +with its Greenwood band, the survival the model predicts for them (their mean at each horizon by the logistic regression, the +Bayesian network and their combination, with a 95 % interval from resampling the members), and the Weibull fits the SEER +pipeline makes to that prediction. Nothing is fitted on the scenario and nothing is stored. """ -from datetime import date from types import SimpleNamespace import numpy as np import pandas as pd +from models.cama.seer_survival import scenarios from models.cama.seer_survival import survival_curves as luis from models.cama.survival import population from models.cama.survival.estimator import FEATURES, IntervalSurvival, survival_settings @@ -23,10 +24,11 @@ MIN_MEMBERS = 30 MIN_EVENTS = 5 REPLICAS = 200 SEED = 42 +WHOLE = "Toda la cohorte" class QueryError(ValueError): - """The selection cannot be answered; the message says why, in the reader's language.""" + """The scenario cannot be answered; the message says why, in the reader's language.""" def rehydrate(model) -> IntervalSurvival: @@ -44,24 +46,34 @@ def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFr return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"] -def _selection(labelled: pd.DataFrame, filters: dict, period: dict) -> pd.DataFrame: - keep = np.ones(len(labelled), bool) - for name, wanted in (filters or {}).items(): - if name not in FEATURES: - raise QueryError(f"No se puede filtrar por «{name}».") - if not isinstance(wanted, list) or not all(isinstance(v, str) for v in wanted): - raise QueryError(f"Los valores de «{name}» deben ser una lista de textos.") - if wanted: - keep &= labelled[name].fillna("NA").astype(str).isin(wanted).to_numpy() - index = pd.to_datetime(labelled["fecha_indice"]) - for key, op in (("desde", "ge"), ("hasta", "le")): - if (period or {}).get(key): - try: - limit = pd.Timestamp(date.fromisoformat(period[key])) - except (TypeError, ValueError) as error: - raise QueryError(f"La fecha «{key}» del periodo no es válida.") from error - keep &= (index >= limit).to_numpy() if op == "ge" else (index <= limit).to_numpy() - return labelled[keep].reset_index(drop=True) +def molecular_subtype(labelled: pd.DataFrame) -> pd.Series: + """The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and + negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario.""" + hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO") + hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"]) + her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"}) + subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido") + return pd.Series(subtype, index=labelled.index) + + +def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]: + """Each scenario's mask over the members. The age and the subtype are the hospital's; stage and surgery are not reported + yet, so a scenario that needs them has no member.""" + raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy()}, index=labelled.index) + return scenarios.masks(raw) + + +def _answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool: + return int(mask.sum()) >= MIN_MEMBERS and int(labelled["event"].to_numpy()[mask].sum()) >= MIN_EVENTS + + +def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]: + """The scenarios `pac_id` belongs to and that have enough members to draw; the whole cohort when she is in none.""" + row = np.flatnonzero(labelled["pac_id"].to_numpy() == pac_id) + if len(row) == 0: + raise QueryError("La paciente no está en la cohorte del modelo.") + found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and _answerable(labelled, mask)] + return found or [WHOLE] def monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarray: @@ -77,31 +89,38 @@ 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, query: dict) -> dict: - """The `curvas` record of the selected members scored with `model` (the fitted `IntervalSurvival`), with the selection - that produced it. `QueryError` when the selection is too small to say anything.""" - selected = _selection(labelled, query.get("filtros"), query.get("periodo")) - if len(selected) < MIN_MEMBERS or int(selected["event"].sum()) < MIN_EVENTS: - raise QueryError(f"La selección tiene {len(selected)} pacientes y {int(selected['event'].sum())} defunciones; " +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.""" + if name in (None, WHOLE): + mask = np.ones(len(labelled), bool) + else: + masks = scenario_masks(labelled) + if name not in masks: + raise QueryError(f"No hay un escenario clínico «{name}».") + mask = masks[name] + if not _answerable(labelled, mask): + raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; " f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.") + selected = labelled[mask].reset_index(drop=True) 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 name in population.SERIES: - low, high = np.percentile(predicted[name][resample].mean(axis=1), [2.5, 97.5], axis=0) - points[name] = {"S": predicted[name].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()} + 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) adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0) classic, fractional = luis._fit_to_curve(adjusted, len(selected), s, s.ks_max_seconds) grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP) - return {"version": population.RECORD_VERSION, "n": int(len(selected)), "events": int((died & (followed < cap)).sum()), - "median_follow_up_months": float(np.median(followed)), "horizons_months": horizons, "months_max": cap, - "bootstrap_replicas": REPLICAS, "km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()}, + 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)), + "horizons_months": horizons, "months_max": cap, "bootstrap_replicas": REPLICAS, + "km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()}, "km_adjusted": {"months": list(range(len(adjusted))), "S": adjusted.tolist()}, "weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()}, "weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()}, - "points": points, "etiquetas": scenario.config.get("etiquetas", {}), - "seleccion": {"filtros": query.get("filtros") or {}, "periodo": query.get("periodo") or {}}} + "points": points, "etiquetas": scenario.config.get("etiquetas", {})} diff --git a/tests/cama/test_survival.py b/tests/cama/test_survival.py index aa86bd1..fd9cf1a 100644 --- a/tests/cama/test_survival.py +++ b/tests/cama/test_survival.py @@ -422,36 +422,71 @@ def production_model(members_frame): members_frame[FEATURES], members_frame[["months", "event"]]) -def test_the_live_figure_scores_the_selected_members_with_the_production_model(members_frame, production_model): - """Pins down: the record is for the selected members, its points are the model's mean survival for them at the model's - horizons with an interval around it, and nothing is refitted (the same selection twice gives the same record). Fails if - a filter is ignored, or the selection changes the model's horizons.""" +def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(members_frame, production_model, monkeypatch): + """Pins down: the record of a scenario is for its members only (their count and deaths), its points are the model's mean + survival for them at the model's horizons with an interval around it, and nothing is refitted (the same scenario twice gives + the same record). Fails if the scenario's mask is ignored, or the scenario changes the model's horizons.""" from models.cama.survival import live - everyone = live.curves(SCENARIO, production_model, members_frame, {}) - grade3 = live.curves(SCENARIO, production_model, members_frame, {"filtros": {"grade": ["G3"]}}) - again = live.curves(SCENARIO, production_model, members_frame, {"filtros": {"grade": ["G3"]}}) + young = np.arange(len(members_frame)) < 120 + monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Primeras 120": young}) - assert everyone["n"] == len(members_frame) and everyone["horizons_months"] == [6, 12, 18] - assert 0 < grade3["n"] < everyone["n"] and grade3["points"] == again["points"] - comb = grade3["points"]["COMB"] + everyone = live.curves(SCENARIO, production_model, members_frame, None) + first = live.curves(SCENARIO, production_model, members_frame, "Primeras 120") + again = live.curves(SCENARIO, production_model, members_frame, "Primeras 120") + + assert everyone["n"] == len(members_frame) and everyone["escenario"] == "Toda la cohorte" and everyone["horizons_months"] == [6, 12, 18] + assert first["n"] == 120 and first["escenario"] == "Primeras 120" and first["points"] == again["points"] + comb = first["points"]["COMB"] assert all(lo <= s <= hi for lo, s, hi in zip(comb["low"], comb["S"], comb["high"])) - assert comb["S"][0] < everyone["points"]["COMB"]["S"][0] # grade 3 does worse than everyone - assert len(grade3["km_adjusted"]["S"]) == grade3["months_max"] + 1 and len(grade3["weibull_fractional"]["S"]) == len(grade3["weibull"]["S"]) + assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"]) -@pytest.mark.parametrize("query", [ - {"filtros": {"nope": ["x"]}}, - {"filtros": {"grade": ["G1"], "er": ["NEGATIVO"], "her2": ["H3"]}}, - {"periodo": {"desde": "no es fecha"}}, -]) -def test_a_selection_that_cannot_be_answered_says_why(members_frame, production_model, query): - """Pins down: an unknown filter, a selection too small to say anything and an invalid date are each a `QueryError` with - a message. Fails if any of them runs and draws a meaningless figure or fails with an unreadable error.""" +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 + scenario is left with nothing.""" + from models.cama.survival import live + + first, last = int(members_frame["pac_id"].iloc[0]), int(members_frame["pac_id"].iloc[-1]) + inside = np.arange(len(members_frame)) < 100 + tiny = np.arange(len(members_frame)) < 3 + monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Grande": inside, "Diminuto": tiny}) + + assert live.patient_scenarios(members_frame, first) == ["Grande"] # in both; the tiny one has too few to draw + assert live.patient_scenarios(members_frame, last) == ["Toda la cohorte"] # in neither + with pytest.raises(live.QueryError): + live.patient_scenarios(members_frame, 10**9) + + +def test_the_scenarios_use_the_hospitals_age_and_subtype_and_none_that_needs_a_stage(members_frame): + """Pins down: the scenario masks use the age in years and a subtype derived from the receptors (hormone receptors and + HER2 3+ / 0-1+), and a scenario that needs the stage or the surgery, which the hospital does not report, has no member. + Fails if a stage scenario includes everyone, or the subtype ignores the receptors.""" + from models.cama.seer_survival import scenarios + from models.cama.survival import live + + n = len(members_frame) + frame = members_frame.assign(er=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "POSITIVO"], n), + pr=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "NEGATIVO"], n), + her2=np.resize(["H1", "H3", "H0", "H2"], n)) + found = live.molecular_subtype(frame).iloc[:4].tolist() + masks = live.scenario_masks(frame) + + assert found == ["HR+/HER2-", "HR-/HER2+", "HR-/HER2-", "Desconocido"] # HER2 2+ is equivocal: unknown + assert set(masks) == set(scenarios.SCENARIOS) + assert not masks["Estadio IV"].any() and not masks["Triple negativo (HR−/HER2−) · estadio 0–II"].any() + + +@pytest.mark.parametrize("name", ["No existe", "Estadio IV"]) +def test_a_scenario_that_cannot_be_answered_says_why(members_frame, production_model, name): + """Pins down: an unknown scenario and one with too few members to say anything (every stage scenario, with the stage not + reported) are each a `QueryError` with a message. Fails if either runs and draws a meaningless figure or fails with an + unreadable error.""" from models.cama.survival import live with pytest.raises(live.QueryError): - live.curves(SCENARIO, production_model, members_frame, query) + live.curves(SCENARIO, production_model, members_frame, name) def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():