Files
models/models/cama/recurrence/calculator.py
T

212 lines
9.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The recurrence calculator: for clinical scenarios of each cohort, the mean recurrence-free
probability the LR + HBN average gives its patients at each horizon, with a 95 % interval from
refits on resamples of the whole cohort, next to the scenario's observed survival (Kaplan-Meier)
and its classic and fractional Weibull curves.
The models are refitted on the whole cohort (and on each resample) with the terms and parents
the split chose; the HBN's pseudo-count counts every level of the cohort, seen in the
(re)sample or not."""
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
RESAMPLES = 200
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
CAP_MONTHS = 72 # the Weibull curves' extent
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
# Each scenario: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
} # fmt: skip
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
return {
name: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in cond.items()])
for name, cond in scenarios.items()
}
@dataclass
class Risk:
"""The cohort coded once: dummies for the LR, integer codes for the HBN."""
fitted: CohortFit
def __post_init__(self):
frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates
self.n = len(frame)
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()}
self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()
def _key(self, chosen, rows) -> np.ndarray:
key = np.zeros(len(rows), dtype=np.int64)
for p in chosen:
key = key * self.levels[p] + self.codes[p][rows]
return key
def _combined(self, rows, horizon) -> np.ndarray | None:
"""Every patient's (LR + HBN) / 2, fitted on `rows`; None when the LR fails."""
t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon)
known = recurred | (t > horizon)
train, y = rows[known], recurred[known].astype(int)
split = self.fitted.horizons[horizon].split
p_lr = p_hbn = np.full(self.n, y.mean())
if split.terms:
m = logit(y, self.X.iloc[train][split.terms].reset_index(drop=True), "add")
if m is None:
return None
p_lr = m.predict(sm.add_constant(self.X[split.terms], has_constant="add")).to_numpy()
if split.parents:
q = int(np.prod([self.levels[p] for p in split.parents]))
a = ESS / (2 * q)
key = self._key(split.parents, train)
table = (pd.Series(y, index=key).groupby(level=0).sum() + a) / (
pd.Series(1, index=key).groupby(level=0).sum() + 2 * a
)
everyone = self._key(split.parents, np.arange(self.n))
p_hbn = table.reindex(everyone).fillna(y.mean()).to_numpy()
return (p_lr + p_hbn) / 2
def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None:
"""Per scenario, the mean risk at each horizon over its patients in `rows` (repeats
counted); None when a refit fails."""
out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks}
for j, h in enumerate(HORIZONS):
combined = self._combined(rows, h)
if combined is None:
return None
for name, mask in scenario_masks.items():
inside = mask[rows]
if inside.any():
out[name][j] = combined[rows][inside].mean()
return out
def _curves(months, event, observed):
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)
return {
"km": dict(
zip(("S", "low", "high"), curves.kaplan_meier(months, event, observed), strict=True)
),
"weibull": curves.weibull(grid, k, lam),
"weibull_fractional": curves.fractional(grid, k, *fractional),
"grid": grid,
}
def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]:
"""The figure record of each scenario with enough recurrences, and its table rows."""
source = fitted.cohort.source
scenarios = SCENARIOS[source] if scenarios is None else scenarios
risk = Risk(fitted)
found = masks(fitted.cohort.frame, scenarios)
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)]
months = np.floor(risk.time).astype(int)
event = risk.event == 1
drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS}
jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()]
jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples] # the long ones first
done = Parallel(n_jobs=-1)(jobs)
fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :]
replicas = [r for r in resampled if r is not None]
records, rows = [], []
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
free = 1 - point[name]
risks = np.array([r[name] for r in replicas])
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0)
observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum())
km, grid = drawn_curves["km"], drawn_curves["grid"].tolist()
records.append(
{
"cohorte": source,
"cohorte_nombre": LABELS[source],
"escenario": name,
"condiciones": scenarios[name],
"n": n,
"recaidas": events,
"horizons_months": list(HORIZONS),
"observado_hasta": observed,
"months_max": CAP_MONTHS,
"km": {
"months": list(range(observed + 1)),
**{k: v.tolist() for k, v in km.items()},
},
"weibull": {"t": grid, "S": drawn_curves["weibull"].tolist()},
"weibull_fractional": {"t": grid, "S": drawn_curves["weibull_fractional"].tolist()},
"points": {
"COMB": {
"S": free.tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist(),
}
},
"bootstrap_replicas": len(replicas),
}
)
for j, h in enumerate(HORIZONS):
rows.append(
{
"cohorte": source,
"subgrupo": name,
"n": n,
"recaidas": events,
"horizonte_meses": h,
"S_libre_LR_HBN": free[j],
"IC95_inf": low[j],
"IC95_sup": high[j],
"riesgo_recurrencia": 1 - free[j],
"S_libre_KM": km["S"][min(h, observed)] if h <= observed else np.nan,
"replicas_bootstrap": len(replicas),
}
)
return records, rows