Files
models/models/survival.py
T

507 lines
24 KiB
Python

"""Interval survival, shared by CaMa and CaCu: the probability of surviving each interval of
follow-up, given alive at its start, by a logistic regression and by a Bayesian network with a
tabular CPT, mixed per interval; survival to a horizon is the product of the intervals' up to it.
Each interval's models fit the patients alive at its start (`months >= start`); one censored
inside the interval counts as half a risk. The mixture weight of an interval is the one that
best predicts patients out of sample (`folds` folds), shrunk toward 50/50 when there are few
deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missing value is a
category of its own (UNKNOWN).
"""
from dataclasses import dataclass, field
from itertools import pairwise
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy.optimize import minimize_scalar
from scipy.special import gammaln
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame:
"""Whole months from each index to her death or, alive, to `end`, and whether she died;
follow-up is cut at `cap_months` (a later death counts as alive)."""
index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
died = (death.notna() & (death <= end)).to_numpy()
last = death.where(died, end)
days = (last - index).dt.days.to_numpy()
months = np.floor(days / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def band(values: pd.Series, cuts: list) -> pd.Series:
"""Values in the bands the cuts make (`<c1`, `c1-(c2-1)`, ..., `≥cn`); empty stays empty."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
@dataclass(frozen=True)
class Constant:
"""An interval where everyone at risk had the same outcome: the same probability for all."""
p: float
def predict_proba(self, X) -> np.ndarray:
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _bdeu(code, y, w, q, ess) -> float:
"""The outcome's weighted BDeu score given parent configurations `code` (of `q`)."""
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj, ajk = ess / q, ess / q / 2
return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
+ np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
def _search(X, levels, y, w, ess, max_parents) -> list[int]:
"""Greedy: the covariate that most improves the outcome's BDeu, until none does."""
parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents:
found = None
for j in range(X.shape[1]):
if j in parents or q * levels[j] > 200_000:
continue
c2 = code * levels[j] + X[:, j]
score = _bdeu(c2, y, w, q * levels[j], ess)
if score > best + 1e-9 and (found is None or score > found[0]):
found = (score, j, c2, q * levels[j])
if found is None:
break
best, j, code, q = found
parents.append(j)
return parents
def _code(X, levels, parents) -> np.ndarray:
code = np.zeros(len(X), int)
for j in parents:
code = code * levels[j] + X[:, j]
return code
class IntervalSurvival(BaseEstimator):
"""Survival by intervals (`borders`, months), LR and HBN stacked per interval.
`fit(X, months, event)` takes the categorical covariates `features`; the HBN's parents
are `parents` (feature names) or, when None, learned per interval by the BDeu score.
"""
def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
folds=5, shrink=20, seed=42): # fmt: skip
self.features = features
self.borders = borders
self.parents = parents
self.ess = ess
self.max_parents = max_parents
self.folds = folds
self.shrink = shrink
self.seed = seed
# -- coding: dummies for the LR (first level alphabetically as reference), integer codes
# (in order of first appearance) for the HBN; an unseen value takes UNKNOWN's code.
def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str)
def _encode(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
frame = self._frame(X)
columns = []
for name in self.features:
known = self.categories_[name]
codes = pd.Categorical(frame[name], categories=known).codes
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
columns.append(np.where(codes < 0, fallback, codes))
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
fitted = []
for a, b in pairwise(self.borders):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
fitted.append((Constant(1.0), ([], np.array([1.0]))))
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) # 1 = survives the interval
w = np.where(~e & (m < b), 0.5, 1.0) # censored inside it: half a risk
if y.min() == y.max():
lr = Constant(float(y[0]))
else:
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[at_risk], y, sample_weight=w)
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
return fitted
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]:
"""The parents and P(survives | parents), smoothed toward the marginal survival."""
if self.parents is None:
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
else:
parents = [list(self.features).index(p) for p in self.parents]
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
minlength=q * 2).reshape(q, 2) # fmt: skip
aj = self.ess / q
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
"""Per interval, the LR's weight in the mixture, from out-of-fold predictions."""
n = len(months)
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds
oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
for k in range(self.folds):
test, train = np.where(fold == k)[0], np.where(fold != k)[0]
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
weights = []
for j, (a, b) in enumerate(pairwise(self.borders)):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
weights.append(0.5)
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0)
p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
def loss(x, p1=p1, p2=p2, y=y, w=w):
p = np.clip(x * p1 + (1 - x) * p2, 1e-9, 1 - 1e-9)
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
shrunk = self.shrink / (self.shrink + int((y == 0).sum()))
weights.append((1 - shrunk) * best + shrunk * 0.5)
return np.array(weights)
def fit(self, X: pd.DataFrame, months, event):
frame = self._frame(X)
self.dummies_ = list(pd.get_dummies(frame, drop_first=True).columns)
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
X_dum, X_int = self._encode(X)
self.levels_ = X_int.max(axis=0) + 1
months, event = np.asarray(months, int), np.asarray(event, bool)
if len(X) >= 2 * self.folds:
self.weights_ = self._weights(X_dum, X_int, months, event)
else:
self.weights_ = np.full(len(self.borders) - 1, 0.5)
self.fitted_ = self._fit_intervals(X_dum, X_int, months, event)
return self
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""Each patient's probability of surviving each interval, by the LR and by the HBN."""
return self._predict(self.fitted_, *self._encode(X))
def survival(self, X: pd.DataFrame) -> np.ndarray:
"""Each patient's survival to the end of each interval."""
lr, hbn = self.components(X)
w = self.weights_[None, :]
return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
# ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"scenarios"] # fmt: skip
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test; ties in the order of the
hospital's record numbers, so the split (and every fold after it) is the same on every
platform the same data are loaded into."""
ordered = members.sort_values(["index_date", "record_number"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)
def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
"""Each member's age at her index (from her birth event), in bands."""
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
return band(age, list(cuts))
@dataclass(frozen=True)
class Spec:
"""Mortality by each horizon from the index (1 minus the interval survival), for the
members of a gold cohort, from their timelines (`person_id`, `index_date`, `date`, `type`,
`value_code`, `value_num`, `source_table`, `source_id`, `record_number`).
`covariates(events, members)` gives each member's `features` at her index. With
`interval_level`, each combination of the covariates seen in training gets an interval:
percentiles of the mortality of `replicas` refits on bootstrap resamples (seed `seed`)."""
name: str
cohort: str
features: tuple[str, ...]
covariates: object # Callable[[pd.DataFrame, pd.DataFrame], pd.DataFrame]
parents: tuple[str, ...] | None = None
borders: tuple[int, ...] = (0, 6, 12, 18) # months
cap_months: int = 24
interval_level: float | None = None
replicas: int = 100
seed: int = 0
method: str = "interval survival"
notes: tuple[str, ...] = () # what the technical report states about the method
# Clinical scenarios the report draws: name -> conditions (column, "<" | ">=" | "==" |
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = ()
@property
def horizons(self) -> tuple[float, ...]:
return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member: index date, record number, death date and covariates."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
found = events.groupby("person_id")[["index_date", "record_number"]].first()
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
found["death_date"] = death.reindex(found.index)
kept = [*self.features, *self.scenario_columns]
found = found.join(self.covariates(events, found)[kept])
return found.reset_index()
def _model(self) -> IntervalSurvival:
return IntervalSurvival(list(self.features), self.borders, self.parents)
def _combinations(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str).reset_index(drop=True)
def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = self._combinations(train).drop_duplicates()
frame = combinations.replace(UNKNOWN, None)
rng = np.random.default_rng(self.seed) # resamples drawn in order, refitted in parallel
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
def mortality(rows: np.ndarray) -> np.ndarray:
sample = train.iloc[rows].reset_index(drop=True)
refit = self._model().fit(sample, sample["months"], sample["event"])
return 1.0 - refit.survival(frame)
replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False)
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def train(self, events: pd.DataFrame, as_of) -> tuple:
"""Fitted on the earliest members (followed up to `as_of`), with its metrics and what
the reports draw."""
members = self.members(events)
members = members.join(
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
)
train, test = split(members, TRAIN_FRACTION)
model = self._model().fit(train, train["months"], train["event"])
model.intervals_ = self._intervals(train) if self.interval_level else {}
weights = zip(self.borders[1:], model.weights_, strict=True)
metrics = {
"n_train": float(len(train)), "n_test": float(len(test)),
"events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
} # fmt: skip
return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, its interval when kept, and
the clinical scenarios of the report she falls in (the curves her record draws)."""
members = self.members(events)
mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h)
ends = [model.intervals_.get(tuple(c), empty)
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
masks = scenario_masks(members, self.scenarios)
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
for i in range(n)] # fmt: skip
return pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
"probability": mortality.ravel(),
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
})[OUTPUT] # fmt: skip
# ---------------------------------------------------------------- reports (curves)
BOOTSTRAP = 100
BOOTSTRAP_SEED = 42
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
members = pd.concat([data["train"], data["test"]])
return {
"model": spec.name, "method": spec.method, "cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min().date()),
str(members["index_date"].max().date())],
"horizons_months": list(spec.borders[1:]),
"follow_up_cap_months": spec.cap_months,
"notes": list(spec.notes),
"metrics": metrics,
} # fmt: skip
def _curve(fitter, name: str) -> dict:
table = fitter.confidence_interval_survival_function_
return {
"months": fitter.survival_function_.index.tolist(),
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
"low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
} # fmt: skip
MIN_SCENARIO_EVENTS = 5 # fewer deaths than this: no curves for the scenario
GRID_POINTS = 200
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
"""Which members each scenario takes: all of its conditions hold (an unknown value
holds none)."""
found = {}
for name, conditions in scenarios.items():
mask = np.ones(len(members), bool)
for column, op, value in conditions:
v = members[column]
if op in ("<", ">="):
number = pd.to_numeric(v, errors="coerce")
held = number < value if op == "<" else number >= value
elif op == "in":
held = v.isin(list(value))
elif op == "==":
held = v == value
else:
raise ValueError(f"unknown condition {op!r} in scenario {name!r}")
mask &= held.fillna(False).to_numpy(bool)
found[name] = mask
return found
def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) -> dict:
from models import curves
d, c, _ = curves.life_table(months, event)
k, lam = curves.fit_weibull(d, c)
fractional = curves.fit_fractional(d, c, k, lam)
grid = np.linspace(0, cap_months, GRID_POINTS)
observed = int(months.max())
km = curves.kaplan_meier(months, event, observed)
return {
"observado_hasta": observed,
"km": {"months": list(range(observed + 1)),
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
"weibull": {"t": grid.tolist(), "S": curves.weibull(grid, k, lam).tolist(),
"k": k, "lambda": lam},
"weibull_fractional": {"t": grid.tolist(),
"S": curves.fractional(grid, k, *fractional).tolist(),
"alpha": fractional[0], "beta": fractional[1],
"lambda": fractional[2]},
} # fmt: skip
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
band, the survival of each combination of the covariates, and each clinical scenario's
curves (Kaplan-Meier, Weibull, fractional Weibull) with the model's mean survival over its
members and its band. The model's mixture is its own (the original refitted it per
scenario): the points show the model as it scores."""
from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"]
months, event = train["months"].to_numpy(), train["event"].to_numpy()
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
if event.any() and (months > 0).all():
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
# Scenarios: over every member (training first), the observed curves of those with
# enough deaths, and the model's mean survival over each, with the same bootstrap band.
members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios)
def mean_survival(rows: np.ndarray) -> tuple[np.ndarray, dict]:
sample = train.iloc[rows].reset_index(drop=True)
refit = spec._model().fit(sample, sample["months"], sample["event"])
found = refit.survival(members)
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
return found[: len(train)].mean(axis=0), by
all_months, all_event = members["months"].to_numpy(), members["event"].to_numpy(bool)
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
for m in drawn.values()] # fmt: skip
jobs += [delayed(mean_survival)(rows) for rows in samples]
done = Parallel(n_jobs=-1)(jobs)
drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
band = np.stack([r[0] for r in replicas])
point = model.survival(members)
scenarios = []
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
spread = np.array([r[1][name] for r in replicas])
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
scenarios.append({
"escenario": name,
"condiciones": [list(c) for c in spec.scenarios[name]],
"n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
"horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
**found,
"points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist()}},
"bootstrap_replicas": len(replicas),
}) # fmt: skip
skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
for n, m in masks.items() if n not in drawn] # fmt: skip
combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None))
return {
"model": spec.name,
"kind": "curves",
"curves": curves,
"predicted": {
"months": list(spec.borders[1:]),
"survival": model.survival(train).mean(axis=0).tolist(),
"low": np.percentile(band, 2.5, axis=0).tolist(),
"high": np.percentile(band, 97.5, axis=0).tolist(),
"name": "LR + HBN combinado (IC 95 % bootstrap)",
},
"weights_lr": model.weights_.tolist(),
"parents": [[spec.features[j] for j in parents] for _, (parents, _) in model.fitted_],
"combinations": [
{**row, "survival": survival[i].tolist()}
for i, row in enumerate(combinations.to_dict("records"))
],
"escenarios": scenarios,
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
}