117 lines
6.8 KiB
Python
117 lines
6.8 KiB
Python
"""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. 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 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, molecular_subtype, survival_settings
|
|
from models.dags.training import Scenario, dataflow
|
|
|
|
MIN_MEMBERS = 30
|
|
MIN_EVENTS = 5
|
|
REPLICAS = 200
|
|
SEED = 42
|
|
WHOLE = "Toda la cohorte"
|
|
|
|
|
|
class QueryError(ValueError):
|
|
"""The scenario cannot be answered; the message says why, in the reader's language."""
|
|
|
|
|
|
def rehydrate(model) -> IntervalSurvival:
|
|
"""The fitted model as the current `IntervalSurvival` code runs it. A version's saved model carries its class as it was
|
|
when it was trained; its fitted state (`fitted_`, `weights_`, the codings) is what makes it that version, so that state
|
|
is put in the current class and its methods are the code's."""
|
|
current = IntervalSurvival.__new__(IntervalSurvival)
|
|
current.__dict__.update(model.__dict__)
|
|
return current
|
|
|
|
|
|
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 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:
|
|
"""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, 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 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, "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", {})}
|