|
|
|
@@ -1,12 +1,11 @@
|
|
|
|
|
"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far.
|
|
|
|
|
"""The survival figure of a clinical scenario over the data ingested so far, as the SEER pipeline's survival stage draws a subgroup.
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
Training and tuning happen in governance; here the production version's results are only shown. 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, or the whole cohort's when she is in none. The
|
|
|
|
|
record has the Kaplan-Meier curve of what happened to the scenario's members with its Greenwood band, the classic and fractional
|
|
|
|
|
Weibull fitted to their deaths, and the pipeline's LR, HBN and combined survival at each horizon with their bootstrap intervals:
|
|
|
|
|
the survival stage's points for the scenario (`development.subgroup_points`), never a model of this module's.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from types import SimpleNamespace
|
|
|
|
@@ -17,14 +16,13 @@ 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.cama.survival.development import WHOLE_COHORT
|
|
|
|
|
from models.cama.survival.estimator import 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"
|
|
|
|
|
WHOLE = WHOLE_COHORT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class QueryError(ValueError):
|
|
|
|
@@ -67,23 +65,10 @@ def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
|
|
|
|
|
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 published_points(rows: list[dict], name: str) -> dict | None:
|
|
|
|
|
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`: its model with the stage and the
|
|
|
|
|
treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
|
|
|
|
|
found = [r for r in rows if r.get("subgrupo") == name]
|
|
|
|
|
def published_points(rows: list[dict], name: str | None) -> dict | None:
|
|
|
|
|
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`, or `cohorte_puntos` for `WHOLE`:
|
|
|
|
|
its model with the stage and the treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
|
|
|
|
|
found = [r for r in rows if r.get("subgrupo") == (name or WHOLE)]
|
|
|
|
|
if not found:
|
|
|
|
|
return None
|
|
|
|
|
out = {}
|
|
|
|
@@ -96,11 +81,11 @@ def published_points(rows: list[dict], name: str) -> dict | None:
|
|
|
|
|
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None, points: dict | None = None) -> dict:
|
|
|
|
|
def curves(scenario: Scenario, labelled: pd.DataFrame, name: str | None, points: dict | None) -> dict:
|
|
|
|
|
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone), as the pipeline's survival stage
|
|
|
|
|
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths. The points
|
|
|
|
|
are `points` when the version published them for the subgroup (`published_points`), else the members scored with `model`
|
|
|
|
|
(the fitted `IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything."""
|
|
|
|
|
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths, with the
|
|
|
|
|
stage's `points` for it (`published_points`). `QueryError` for an unknown scenario, one with too few members to say
|
|
|
|
|
anything, or one the stage has no points for yet."""
|
|
|
|
|
if name in (None, WHOLE):
|
|
|
|
|
mask = np.ones(len(labelled), bool)
|
|
|
|
|
else:
|
|
|
|
@@ -111,29 +96,22 @@ def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None,
|
|
|
|
|
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}.")
|
|
|
|
|
if points is None:
|
|
|
|
|
raise QueryError("El modelo todavía no tiene la supervivencia de este escenario; se calcula en el siguiente recálculo de indicadores.")
|
|
|
|
|
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])
|
|
|
|
|
if points is None:
|
|
|
|
|
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)
|
|
|
|
|
months, ended = np.minimum(followed, cap), died & (followed < cap)
|
|
|
|
|
S, low, high = luis.fw.km_curva(months, ended, cap)
|
|
|
|
|
adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0)
|
|
|
|
|
d, c = luis.fw.tabla_eventos(months, ended)
|
|
|
|
|
classic = luis.fw.ajustar_weibull(d, c)
|
|
|
|
|
fractional = luis.fw.ajustar_ks(d, c, k_fijo=luis._fixed_k(classic, s), lam_ref=classic["lam"], max_seg=s.ks_sub_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,
|
|
|
|
|
"events": int(ended.sum()), "median_follow_up_months": float(np.median(followed)),
|
|
|
|
|
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": int(s.n_boot if name in (None, WHOLE) else s.n_boot_sub),
|
|
|
|
|
"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", {})}
|
|
|
|
|