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)"
|
||||
|
||||
Reference in New Issue
Block a user