CaMa survival: the live figure is the clinical scenario's, over the production model and the live cohort

This commit is contained in:
rockdrigo
2026-11-21 13:14:06 -06:00
parent b1006a97d7
commit e99eb499d6
2 changed files with 116 additions and 62 deletions
+60 -41
View File
@@ -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", {})}