CaMa survival: the figure for a selection of members, scored with the production model over the live cohort; the pipeline's chart wording
This commit is contained in:
@@ -176,6 +176,13 @@ class IntervalSurvival(BaseEstimator):
|
||||
"""Each member's survival to each horizon."""
|
||||
return np.cumprod(self.interval_proba(X), axis=1)
|
||||
|
||||
def component_survival(self, X: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each member's survival to each horizon by the logistic regression, by the Bayesian network and by their
|
||||
stacked combination (`survival_proba`)."""
|
||||
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
|
||||
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
|
||||
return {"LR": np.cumprod(P_lr, axis=1), "HBN": np.cumprod(P_hb, axis=1), "COMB": self.survival_proba(X)}
|
||||
|
||||
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
|
||||
mortality = 1.0 - self.survival_proba(X)
|
||||
if INDEX_COLUMN not in X.columns:
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The survival figure for a selection of members, 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.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import survival_curves as luis
|
||||
from models.cama.survival import population
|
||||
from models.cama.survival.estimator import FEATURES, survival_settings
|
||||
from models.dags.training import Scenario, dataflow
|
||||
|
||||
MIN_MEMBERS = 30
|
||||
MIN_EVENTS = 5
|
||||
REPLICAS = 200
|
||||
SEED = 42
|
||||
|
||||
|
||||
class QueryError(ValueError):
|
||||
"""The selection cannot be answered; the message says why, in the reader's language."""
|
||||
|
||||
|
||||
def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFrame:
|
||||
"""Every member of the indexed cohort with her covariates and follow-up (the scenario's `labelled_members`)."""
|
||||
dr = dataflow(*scenario.modules, config=scenario.config)
|
||||
return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"]
|
||||
|
||||
|
||||
def options(labelled: pd.DataFrame, pac_id: int | None = None) -> dict:
|
||||
"""What a reader can select: each covariate's values with their member counts, the period of the index dates and the
|
||||
smallest selection that can be answered; and, given a patient, her own value of each covariate."""
|
||||
values = {name: [{"valor": str(v), "n": int(n)} for v, n in labelled[name].fillna("NA").value_counts().sort_index().items()]
|
||||
for name in FEATURES}
|
||||
dates = pd.to_datetime(labelled["fecha_indice"])
|
||||
found = {"n": int(len(labelled)), "events": int(labelled["event"].sum()), "covariables": values,
|
||||
"periodo": {"desde": dates.min().date().isoformat(), "hasta": dates.max().date().isoformat()},
|
||||
"limites": {"miembros_min": MIN_MEMBERS, "muertes_min": MIN_EVENTS}}
|
||||
if pac_id is not None:
|
||||
mine = labelled[labelled["pac_id"] == pac_id]
|
||||
found["paciente"] = {name: str(mine.iloc[0][name]) if len(mine) and pd.notna(mine.iloc[0][name]) else "NA" for name in FEATURES} if len(mine) else None
|
||||
return found
|
||||
|
||||
|
||||
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 monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarray:
|
||||
"""Each member's survival month by month from 0 to `months`: log-linear between the horizons, which is a constant hazard
|
||||
in each interval, and past the last one with the hazard of the last interval."""
|
||||
borders = np.array([0, *horizons], float)
|
||||
log = np.log(np.clip(np.column_stack([np.ones(len(survival)), survival]), 1e-12, 1.0))
|
||||
grid = np.arange(months + 1, dtype=float)
|
||||
out = np.empty((len(survival), len(grid)))
|
||||
slope = (log[:, -1] - log[:, -2]) / (borders[-1] - borders[-2])
|
||||
for i in range(len(survival)):
|
||||
out[i] = np.where(grid > borders[-1], log[i, -1] + slope[i] * (grid - borders[-1]), np.interp(grid, borders, log[i]))
|
||||
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; "
|
||||
f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.")
|
||||
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()}
|
||||
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()},
|
||||
"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 {}}}
|
||||
@@ -83,14 +83,11 @@ subgroups = []
|
||||
# What the dashboard's survival chart says, in the clinicians' words (provisional: to be defined with them). The record a
|
||||
# training run publishes carries these, so changing one is a setting and a new run.
|
||||
[config.etiquetas]
|
||||
# The wording of the survival figure, as the SEER pipeline's own chart has it; to be defined with the clinicians.
|
||||
titulo = "Supervivencia después del primer reporte de biopsia con carcinoma invasor"
|
||||
eje_x = "Meses desde el reporte de biopsia"
|
||||
eje_y = "Probabilidad de supervivencia"
|
||||
km_crudo = "Kaplan-Meier (observada)"
|
||||
km_ajustada = "Kaplan-Meier ajustada por covariables"
|
||||
weibull = "Weibull ajustada"
|
||||
weibull_fraccional = "Weibull fraccional ajustada"
|
||||
puntos = "Modelo (LR + red bayesiana) con IC 95 %"
|
||||
LR = "Regresión logística"
|
||||
HBN = "Red bayesiana"
|
||||
COMB = "Modelo combinado"
|
||||
eje_x = "Meses desde el diagnóstico"
|
||||
eje_y = "Supervivencia S(t)"
|
||||
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
|
||||
weibull = "Weibull"
|
||||
weibull_fraccional = "Weibull fraccional"
|
||||
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
|
||||
|
||||
@@ -413,3 +413,68 @@ def test_the_production_model_predicts_what_the_pipelines_points_say(members_fra
|
||||
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
|
||||
|
||||
assert mean_combined == pytest.approx(theirs[theirs["modelo"] == "COMB"]["S"].tolist(), abs=1e-6)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def production_model(members_frame):
|
||||
"""A model fitted on the 240 members: what a version in production is when the dashboard scores a selection."""
|
||||
return IntervalSurvival(CONFIG["survival"], tuple(h / 12 for h in CONFIG["survival"]["horizons"])).fit(
|
||||
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."""
|
||||
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"]}})
|
||||
|
||||
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"]
|
||||
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"])
|
||||
|
||||
|
||||
def test_the_live_options_list_the_values_the_limits_and_the_patients_own(members_frame):
|
||||
"""Pins down: the options carry every covariate's values with their member counts, the period of the index dates, the
|
||||
smallest selection that can be answered and, for a patient, her value of each covariate. Fails if a covariate is missing
|
||||
or her values are not hers."""
|
||||
from models.cama.survival import live
|
||||
|
||||
first = int(members_frame["pac_id"].iloc[0])
|
||||
found = live.options(members_frame, first)
|
||||
|
||||
assert set(found["covariables"]) == set(FEATURES)
|
||||
assert sum(v["n"] for v in found["covariables"]["grade"]) == len(members_frame)
|
||||
assert found["paciente"]["grade"] == str(members_frame["grade"].iloc[0])
|
||||
assert live.options(members_frame, 10**9)["paciente"] is None
|
||||
|
||||
|
||||
@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."""
|
||||
from models.cama.survival import live
|
||||
|
||||
with pytest.raises(live.QueryError):
|
||||
live.curves(SCENARIO, production_model, members_frame, query)
|
||||
|
||||
|
||||
def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():
|
||||
"""Pins down: the month-by-month survival equals the model's at each horizon, starts at 1, never rises, and goes on past
|
||||
the last horizon at the last interval's rate. Fails if the interpolation misses a horizon or the curve can go up."""
|
||||
from models.cama.survival import live
|
||||
|
||||
curve = live.monthly(np.array([[0.9, 0.8, 0.6]]), [6, 12, 18], 24)[0]
|
||||
|
||||
assert curve[0] == 1.0 and curve[6] == pytest.approx(0.9) and curve[12] == pytest.approx(0.8) and curve[18] == pytest.approx(0.6)
|
||||
assert (np.diff(curve) <= 1e-12).all() and curve[24] < curve[18]
|
||||
|
||||
Reference in New Issue
Block a user