157 lines
6.3 KiB
Python
157 lines
6.3 KiB
Python
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
|
|
CAP_MONTHS = 72
|
|
GRID_POINTS = 289
|
|
|
|
|
|
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:
|
|
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:
|
|
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:
|
|
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) -> tuple[list[dict], list[dict]]:
|
|
source = fitted.cohort.source
|
|
scenarios = fitted.cohort.scenarios
|
|
risk = Risk(fitted)
|
|
found = masks(fitted.cohort.frame, scenarios)
|
|
rng = np.random.default_rng(SEED)
|
|
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]
|
|
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": fitted.cohort.label,
|
|
"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)
|