"""The recurrence calculator: for each clinical scenario of a cohort (a subgroup defined by covariates), the figure the dashboard shows: the Kaplan-Meier curve of the scenario's patients with its Greenwood band, the classic and the fractional Weibull fitted to it (dotted past the follow-up), and the recurrence-free probability at each horizon by the combination of the LR and the HBN of that horizon, with a bootstrap interval. Ported from `05_calculadora.py`; the Weibull routines are the survival analysis' (`models.cama.seer_survival.fractional_weibull`). """ from dataclasses import dataclass import numpy as np import pandas as pd import statsmodels.api as sm from models.cama.recurrence.factors import ORDER # noqa: F401 (the classification vocabulary is shared) from models.cama.recurrence.modeling import CohortModels from models.cama.recurrence.prep import Prepared from models.cama.seer_survival import fractional_weibull as fw 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"]}, }, } LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"} PCT_DEFINING, PCT_MAJORITY, PCT_PRESENT = 0.95, 0.50, 0.10 @dataclass(frozen=True) class CalculatorSettings: seed: int = 42 n_boot: int = 200 min_events: int = 15 cap_months: int = 72 bdeu_ess: int = 10 ks_seconds: int = 60 class _Calculator: def __init__(self, prepared: Prepared, fitted: CohortModels, s: CalculatorSettings): self.s, self.fitted, self.covariates = s, fitted, prepared.covariates df = prepared.cohort self.df, self.N = df, len(df) self.time, self.event_num = df["tiempo_meses"].values, df["evento"].values self.X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float) self.codes = {v: pd.factorize(df[v])[0] for v in self.covariates} self.levels = {v: int(self.codes[v].max()) + 1 for v in self.covariates} @staticmethod def _logit(y, X): try: return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300) except Exception: return None def _p_lr(self, train_idx, y, terms): if not terms: return np.full(self.N, y.mean()) m = self._logit(y, self.X.iloc[train_idx][terms]) return None if m is None else m.predict(sm.add_constant(self.X[terms], has_constant="add")).values def _key(self, parents, rows): k = np.zeros(len(rows), dtype=np.int64) for p in parents: k = k * self.levels[p] + self.codes[p][rows] return k def _p_hbn(self, train_idx, y, parents): if not parents: return np.full(self.N, y.mean()) q = int(np.prod([self.levels[p] for p in parents])) alpha = self.s.bdeu_ess / (2 * q) k_train = self._key(parents, train_idx) n = pd.Series(1, index=k_train).groupby(level=0).sum() n1 = pd.Series(y, index=k_train).groupby(level=0).sum() table = (n1 + alpha) / (n + 2 * alpha) return table.reindex(self._key(parents, np.arange(self.N))).fillna(y.mean()).values def _risks(self, idx, H): t, e = self.time[idx], self.event_num[idx] recurs = (e == 1) & (t <= H) ok = recurs | (t > H) train, y = idx[ok], recurs[ok].astype(int) mh = self.fitted.models[str(H)] p_lr, p_hbn = self._p_lr(train, y, mh["terminos_lr"]), self._p_hbn(train, y, mh["padres_hbn"]) return None if p_lr is None else (p_lr, p_hbn) def mean_risk(self, idx, masks, horizons): out = {n: np.full(len(horizons), np.nan) for n in masks} for j, H in enumerate(horizons): r = self._risks(idx, H) if r is None: return None combined = (r[0] + r[1]) / 2 for n, mask in masks.items(): sel = mask[idx] if sel.any(): out[n][j] = combined[idx][sel].mean() return out def scenario_masks(df: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: return {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in scenarios.items()} def _presence(share: float) -> str: if share >= PCT_DEFINING: return "definitoria" if share >= PCT_MAJORITY: return "mayoritaria" return "presente" if share >= PCT_PRESENT else "minoritaria" def calculator(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], settings: CalculatorSettings, scenarios: dict | None = None) -> tuple[list[dict], pd.DataFrame]: """The figure record of each scenario with enough recurrences, and the table of their points.""" scenarios = scenarios if scenarios is not None else SCENARIOS[name] c = _Calculator(prepared, fitted, settings) masks = scenario_masks(prepared.cohort, scenarios) everyone = np.arange(c.N) points = c.mean_risk(everyone, masks, horizons) rng = np.random.default_rng(settings.seed) boots = {n: [] for n in masks} for _ in range(settings.n_boot): r = c.mean_risk(rng.integers(0, c.N, c.N), masks, horizons) if r is None: continue for n in masks: boots[n].append(r[n]) months_int = np.floor(c.time).astype(int) event = c.event_num == 1 records, rows = [], [] for scenario, mask in masks.items(): n_sub, events = int(mask.sum()), int(prepared.cohort.loc[mask, "evento"].sum()) if n_sub == 0 or events < settings.min_events: continue m_s, e_s = months_int[mask], event[mask] d, cen = fw.tabla_eventos(m_s, e_s) classic = fw.ajustar_weibull(d, cen) fractional = fw.ajustar_ks(d, cen, k_fijo=classic["k"], lam_ref=classic["lam"], max_seg=settings.ks_seconds) observed = int(m_s.max()) S, low, high = fw.km_curva(m_s, e_s, observed) free = 1 - points[scenario] B = np.array(boots[scenario]) ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(horizons)), np.nan) grid = np.linspace(0, settings.cap_months, 289) records.append({ "cohorte": name, "cohorte_nombre": LABELS[name], "escenario": scenario, "condiciones": scenarios[scenario], "n": n_sub, "recaidas": events, "horizons_months": horizons, "observado_hasta": observed, "months_max": settings.cap_months, "km": {"months": list(range(observed + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.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": {"COMB": {"S": free.tolist(), "low": np.clip(ic[0], 0, 1).tolist(), "high": np.clip(ic[1], 0, 1).tolist()}}, "bootstrap_replicas": len(B)}) for j, H in enumerate(horizons): rows.append({"cohorte": name, "subgrupo": scenario, "n": n_sub, "recaidas": events, "horizonte_meses": H, "S_libre_LR_HBN": free[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - free[j], "S_libre_KM": S[min(H, observed)] if H <= observed else np.nan, "replicas_bootstrap": len(B)}) return records, pd.DataFrame(rows).round(4) def scenario_risk_factors(name: str, prepared: Prepared, factors: pd.DataFrame, horizons: list[int], scenarios: dict | None = None) -> tuple[pd.DataFrame, pd.DataFrame]: """Which classified risk factors, protectors and treatments make up each scenario: a category nearly all of it has defines it, most of it describes it. Returns the detail and the per-scenario summary.""" scenarios = scenarios if scenarios is not None else SCENARIOS[name] df = prepared.cohort masks = scenario_masks(df, scenarios) fr = factors[(factors["cohorte"] == name) & factors["horizonte_meses"].isin(horizons)] fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy() fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0]) details, summary = [], [] for scenario, mask in masks.items(): n_sub = int(mask.sum()) if n_sub == 0 or fr.empty: continue cond = scenarios[scenario] shares = {(v, cat): (float((df.loc[mask, v] == cat).mean()), float((df[v] == cat).mean())) for v, cat in set(zip(fr["variable"], fr["categoria"]))} det = fr.copy() det["pct_en_escenario"] = [shares[(v, cat)][0] for v, cat in zip(det["variable"], det["categoria"])] det["pct_en_cohorte"] = [shares[(v, cat)][1] for v, cat in zip(det["variable"], det["categoria"])] det["presencia"] = det["pct_en_escenario"].map(_presence) det["en_definicion"] = [cat in cond.get(v, []) for v, cat in zip(det["variable"], det["categoria"])] definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items()) det.insert(0, "escenario", scenario) det.insert(1, "definicion", definition) det.insert(2, "n_escenario", n_sub) cols = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria", "clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte", "presencia", "en_definicion"] details.append(det[det["pct_en_escenario"] >= PCT_PRESENT][cols]) for H in horizons: d = det[det["horizonte_meses"] == H] row = {"cohorte": name, "escenario": scenario, "definicion": definition, "n_escenario": n_sub, "horizonte_meses": H} for kind in ("riesgo", "protector", "tratamiento"): for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")): part = d[(d["tipo_efecto"] == kind) & (d["presencia"] == level)] row[f"{kind}_{label}"] = "; ".join( f"{v}={cat} ({k.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})" for v, cat, k, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"])) row["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum()) row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0 summary.append(row) return (pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame()), pd.DataFrame(summary)