Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1b9afb22ea | |||
| 3fdc59df6d | |||
| 9fe1f86c8b | |||
| 0804937578 | |||
| e99eb499d6 | |||
| b1006a97d7 | |||
| 997aebd068 | |||
| b8936522be | |||
| ec430c3ee3 | |||
| 0cf3e60341 |
@@ -0,0 +1,223 @@
|
||||
"""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)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,135 @@
|
||||
"""The risk factors of the recurrence models: a category is a risk factor (or a protector) from four criteria, as in the
|
||||
survival analysis: the multivariable OR, its stability in the bootstrap, the Markov blanket of the Bayesian network and the
|
||||
survival difference; treatments are reported apart, never classified. Ported from `04_factores_riesgo.py`.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
|
||||
from models.cama.recurrence.modeling import CohortModels
|
||||
from models.cama.recurrence.prep import Prepared
|
||||
|
||||
ORDER = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
|
||||
COLUMNS = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
|
||||
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
|
||||
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
|
||||
"criterios_cumplidos", "clasificacion"]
|
||||
|
||||
|
||||
def benjamini_hochberg(p) -> np.ndarray:
|
||||
p = np.asarray(p, float)
|
||||
order = np.argsort(p)
|
||||
adjusted = np.empty_like(p)
|
||||
m, previous = len(p), 1.0
|
||||
for rank, i in zip(range(m, 0, -1), order[::-1]):
|
||||
previous = min(previous, p[i] * m / rank)
|
||||
adjusted[i] = previous
|
||||
return adjusted
|
||||
|
||||
|
||||
def _variable_of(term: str, variables: list[str]) -> str:
|
||||
return next(v for v in sorted(variables, key=len, reverse=True) if term.startswith(v + "_"))
|
||||
|
||||
|
||||
def _km_at(m, e, h):
|
||||
T = int(m.max()) + 2
|
||||
d, c = np.bincount(m[e], minlength=T), np.bincount(m[~e], minlength=T)
|
||||
at_risk = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
q = np.where(at_risk > 0, 1 - d / np.maximum(at_risk, 1), 1.0)
|
||||
v = np.where((at_risk > 0) & (at_risk > d), d / (np.maximum(at_risk, 1) * np.maximum(at_risk - d, 1)), 0.0)
|
||||
h = min(h, T - 1)
|
||||
S = np.prod(q[:h + 1])
|
||||
return S, S * np.sqrt(np.sum(v[:h + 1]))
|
||||
|
||||
|
||||
def _at_horizon(name: str, prepared: Prepared, fitted: CohortModels, H: int, alpha: float, freq_min: float) -> pd.DataFrame:
|
||||
total, variables, treatment = prepared.cohort, prepared.covariates, prepared.treatment
|
||||
intrinsic = [v for v in variables if v not in treatment]
|
||||
recurs = (total["evento"] == 1) & (total["tiempo_meses"] <= H)
|
||||
free = total["tiempo_meses"] > H
|
||||
km_data = total.copy()
|
||||
coh = total[recurs | free].reset_index(drop=True)
|
||||
data = coh[variables].astype(str)
|
||||
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
|
||||
months = np.floor(np.minimum(km_data["tiempo_meses"].values, H + 1)).astype(int)
|
||||
event = ((km_data["evento"] == 1) & (km_data["tiempo_meses"] <= H)).values
|
||||
km_data = km_data[variables].astype(str)
|
||||
|
||||
def reference(v):
|
||||
return data[v].value_counts().idxmax()
|
||||
|
||||
def fit_or(model_vars):
|
||||
X = pd.get_dummies(data[model_vars], drop_first=False).astype(float)
|
||||
refs = {v: f"{v}_{reference(v)}" for v in model_vars}
|
||||
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
X = X.loc[:, ~X.T.duplicated()]
|
||||
model = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ci = model.conf_int()
|
||||
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(model.params[X.columns].values),
|
||||
"IC95_inf": np.exp(ci.loc[X.columns, 0].values), "IC95_sup": np.exp(ci.loc[X.columns, 1].values),
|
||||
"p": model.pvalues[X.columns].values})
|
||||
|
||||
def delta_s(v, cat, ref):
|
||||
a, b = (km_data[v] == cat).values, (km_data[v] == ref).values
|
||||
Sa, ea = _km_at(months[a], event[a], H)
|
||||
Sb, eb = _km_at(months[b], event[b], H)
|
||||
d, se = Sa - Sb, np.sqrt(ea ** 2 + eb ** 2)
|
||||
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
|
||||
"delta_IC95_inf": d - 1.96 * se, "delta_IC95_sup": d + 1.96 * se})
|
||||
|
||||
def complete(t, model_vars):
|
||||
t = t.copy()
|
||||
t["variable"] = [_variable_of(x, model_vars) for x in t["termino"]]
|
||||
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
|
||||
t["referencia"] = [reference(v) for v in t["variable"]]
|
||||
t["p_ajustado_BH"] = benjamini_hochberg(t["p"])
|
||||
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
|
||||
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
|
||||
|
||||
tab = complete(fit_or(intrinsic), intrinsic)
|
||||
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < alpha)
|
||||
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
|
||||
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
|
||||
mh = fitted.models.get(str(H), {})
|
||||
n_rep, selection = mh.get("n_replicas", 0), mh.get("seleccion_lr", {})
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: selection.get(v, 0) / n_rep if n_rep else np.nan)
|
||||
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= freq_min
|
||||
tab["en_manta_markov"] = tab["variable"].isin(set(mh.get("padres_hbn", [])))
|
||||
tab["c3_manta_markov"] = tab["en_manta_markov"]
|
||||
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
|
||||
|
||||
def classify(r):
|
||||
if r["categoria"] == "Desconocido":
|
||||
return "no aplica (categoria desconocida)"
|
||||
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
|
||||
return f"{r['direccion']} robusto"
|
||||
if r["criterios_cumplidos"] >= 2:
|
||||
return f"{r['direccion']} sugerente"
|
||||
return "no concluyente"
|
||||
|
||||
tab["clasificacion"] = tab.apply(classify, axis=1)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
if treatment:
|
||||
tr = fit_or(intrinsic + treatment)
|
||||
tr["_v"] = [_variable_of(t, intrinsic + treatment) for t in tr["termino"]]
|
||||
tr = tr[tr["_v"].isin(treatment) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
|
||||
tr = complete(tr, treatment)
|
||||
tr["tipo"] = "tratamiento"
|
||||
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
tab = pd.concat([tab, tr], ignore_index=True)
|
||||
tab["cohorte"], tab["horizonte_meses"] = name, H
|
||||
return tab
|
||||
|
||||
|
||||
def risk_factors(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], alpha: float = 0.05,
|
||||
freq_min: float = 0.80) -> pd.DataFrame:
|
||||
"""The classified categories of each horizon, risk factors first, as `factores_riesgo_recurrencia.csv`."""
|
||||
new = pd.concat([_at_horizon(name, prepared, fitted, H, alpha, freq_min) for H in horizons], ignore_index=True)
|
||||
new["_t"] = (new["tipo"] != "factor de riesgo").astype(int)
|
||||
new["_o"] = new["clasificacion"].map(ORDER).fillna(5)
|
||||
return new.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[COLUMNS].round(4)
|
||||
@@ -0,0 +1,153 @@
|
||||
"""CaMa's recurrence analysis as a scenario: the dataflow from the two external cohorts to the registered model, its results and
|
||||
its routines. Each node is one stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery
|
||||
(`models.dags.training.train`) saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the
|
||||
dashboard shows are in `population["recurrencia"]`.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
|
||||
from models.cama.recurrence import calculator as calc
|
||||
from models.cama.recurrence import factors as fac
|
||||
from models.cama.recurrence import modeling
|
||||
from models.cama.recurrence.prep import FILES, PREPARE, Prepared
|
||||
from models.cama.recurrence.source import data_folder
|
||||
from models.cama.recurrence.steps import run_steps # noqa: F401 (the CLI's own steps: not a node)
|
||||
|
||||
COHORTS = ("metabric", "scanb")
|
||||
|
||||
|
||||
def prepared(recurrence: dict) -> dict[str, Prepared]:
|
||||
"""Each cohort as one table of categories with its covariates (`prep`)."""
|
||||
folder = data_folder(recurrence["data_dir"])
|
||||
return {name: PREPARE[name](str(folder / FILES[name]), recurrence["v_max"]) for name in COHORTS}
|
||||
|
||||
|
||||
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
|
||||
"""The LR and the HBN at each horizon of each cohort, with their AUC (`modeling`)."""
|
||||
base = {k: recurrence[k] for k in ("seed", "bdeu_ess", "max_parents", "alpha_in", "alpha_out", "alpha_prefilter")}
|
||||
return {name: modeling.fit_cohort(name, prepared[name], list(recurrence["horizons"]),
|
||||
modeling.FitSettings(n_bootstrap=recurrence[f"n_bootstrap_{name}"], **base)) for name in COHORTS}
|
||||
|
||||
|
||||
def factors_table(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> pd.DataFrame:
|
||||
"""The classified risk factors of both cohorts at each horizon (`factors`)."""
|
||||
return pd.concat([fac.risk_factors(n, prepared[n], fits[n], list(recurrence["horizons"]), recurrence["alpha"], recurrence["freq_min"])
|
||||
for n in COHORTS], ignore_index=True)
|
||||
|
||||
|
||||
def calculators(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict[str, tuple[list[dict], pd.DataFrame]]:
|
||||
"""The figure of each scenario of each cohort and the table of their points (`calculator`)."""
|
||||
s = calc.CalculatorSettings(seed=recurrence["seed"], n_boot=recurrence["n_boot_calc"], min_events=recurrence["min_events"],
|
||||
cap_months=recurrence["cap_months"], bdeu_ess=recurrence["bdeu_ess"], ks_seconds=recurrence["ks_seconds"])
|
||||
return {n: calc.calculator(n, prepared[n], fits[n], list(recurrence["horizons"]), s) for n in COHORTS}
|
||||
|
||||
|
||||
def scenario_factors(prepared: dict[str, Prepared], factors_table: pd.DataFrame, recurrence: dict) -> dict[str, pd.DataFrame]:
|
||||
"""The risk factors that make up each scenario (`calculator.scenario_risk_factors`): the summary of both cohorts."""
|
||||
summaries = [calc.scenario_risk_factors(n, prepared[n], factors_table, list(recurrence["horizons"]))[1] for n in COHORTS]
|
||||
return {"resumen": pd.concat(summaries, ignore_index=True)}
|
||||
|
||||
|
||||
class RecurrenceModel:
|
||||
"""The recurrence models of one cohort fitted on all of it: at each horizon the logistic regression on the terms the
|
||||
stepwise chose and the Bayesian network's table over the parents it chose. `predict_proba(X)` is the recurrence probability
|
||||
at each horizon, the mean of the two models; `X` has the cohort's covariates as categories (the unknown, "Desconocido")."""
|
||||
|
||||
def __init__(self, cohort: str, horizons: list[int], covariates: list[str], tables: dict):
|
||||
self.cohort, self.horizons, self.covariates, self.tables_ = cohort, horizons, covariates, tables
|
||||
|
||||
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
|
||||
out = np.zeros((len(X), len(self.horizons)))
|
||||
for j, H in enumerate(self.horizons):
|
||||
t = self.tables_[str(H)]
|
||||
p_lr = np.full(len(X), t["lr_prior"])
|
||||
if t["lr_terms"]:
|
||||
dummies = pd.get_dummies(X[self.covariates].astype(str)).astype(float).reindex(columns=t["lr_terms"], fill_value=0.0)
|
||||
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + dummies.values @ np.asarray(t["lr_coefficients"]))))
|
||||
parents, cpt = t["hbn_parents"], t["hbn_cpt"]
|
||||
p_hbn = np.full(len(X), t["hbn_prior"]) if not parents else np.array(
|
||||
[cpt.get(tuple(row), t["hbn_prior"]) for row in X[parents].astype(str).values])
|
||||
out[:, j] = (p_lr + p_hbn) / 2
|
||||
return out
|
||||
|
||||
|
||||
def _tables(prepared: Prepared, fitted: modeling.CohortModels, horizons: list[int], bdeu_ess: int) -> dict:
|
||||
"""What `RecurrenceModel` keeps from the fit on the whole cohort, per horizon."""
|
||||
f = modeling._Fitter(prepared, modeling.FitSettings(bdeu_ess=bdeu_ess))
|
||||
tables = {}
|
||||
for H in horizons:
|
||||
coh = f.at_horizon(H)
|
||||
mh = fitted.models[str(H)]
|
||||
terms, parents = mh["terminos_lr"], mh["padres_hbn"]
|
||||
entry = {"lr_prior": float(coh["y"].mean()), "lr_terms": terms, "lr_constant": 0.0, "lr_coefficients": [],
|
||||
"hbn_parents": parents, "hbn_prior": float(coh["y"].mean()), "hbn_cpt": {}}
|
||||
if terms:
|
||||
X = f.encode(coh)[terms]
|
||||
model = f.logit(coh["y"], X)
|
||||
if model is not None:
|
||||
entry["lr_constant"], entry["lr_coefficients"] = float(model.params["const"]), [float(model.params[t]) for t in terms]
|
||||
if parents:
|
||||
table = f.bn_table(coh)
|
||||
alpha = bdeu_ess / (2 * int(np.prod([table[p].nunique() for p in parents])))
|
||||
g = table.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
||||
entry["hbn_cpt"] = {(k if isinstance(k, tuple) else (k,)): float((r.n1 + alpha) / (r.n + 2 * alpha)) for k, r in g.iterrows()}
|
||||
tables[str(H)] = entry
|
||||
return tables
|
||||
|
||||
|
||||
def fitted_model(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> RecurrenceModel:
|
||||
"""The model that is saved: METABRIC's, the larger of the two cohorts' external references for the covariates both share."""
|
||||
return RecurrenceModel("metabric", list(recurrence["horizons"]), prepared["metabric"].covariates,
|
||||
_tables(prepared["metabric"], fits["metabric"], list(recurrence["horizons"]), recurrence["bdeu_ess"]))
|
||||
|
||||
|
||||
def metrics(fits: dict[str, modeling.CohortModels]) -> dict:
|
||||
"""Numbers only: each cohort's AUC by internal validation and by bootstrap, per horizon and model, and its Cox C-index."""
|
||||
found = {}
|
||||
for name, fit in fits.items():
|
||||
for _, r in fit.auc.iterrows():
|
||||
if r["horizonte_meses"] == "completo":
|
||||
found[f"{name}.c_index_cox"] = float(r["AUC_validacion_interna"])
|
||||
continue
|
||||
tag = f"{name}.auc_{r['modelo']}_{int(r['horizonte_meses'])}m"
|
||||
found[tag] = float(r["AUC_validacion_interna"])
|
||||
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
|
||||
return found
|
||||
|
||||
|
||||
def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict:
|
||||
"""The five routine records the registry's promotion reads (ML-01a)."""
|
||||
return {
|
||||
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
|
||||
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
|
||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "METABRIC y SCAN-B (externas)"},
|
||||
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
|
||||
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.items()}},
|
||||
"METODO_ANALITICO": {"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
|
||||
"horizontes_meses": recurrence["horizons"], "alfa_entrada": recurrence["alpha_in"], "alfa_salida": recurrence["alpha_out"],
|
||||
"ess_bdeu": recurrence["bdeu_ess"], "maximo_de_padres": recurrence["max_parents"], "cox_penalizado": 0.05,
|
||||
"combinacion": "promedio de la LR y la HBN"},
|
||||
"BALANCE_CLASES": {"aplica": False, "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea"},
|
||||
"CONFIANZA_SALIDA": {"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap",
|
||||
"replicas": {"metabric": recurrence["n_bootstrap_metabric"], "scanb": recurrence["n_bootstrap_scanb"], "calculadora": recurrence["n_boot_calc"]},
|
||||
"eventos_minimos_por_escenario": recurrence["min_events"]},
|
||||
}
|
||||
|
||||
|
||||
def population(calculators: dict, fits: dict[str, modeling.CohortModels], factors_table: pd.DataFrame, scenario_factors: dict,
|
||||
recurrence: dict) -> dict:
|
||||
"""What the version publishes under `analisis/`: `recurrencia`, the figure of each scenario of each cohort the dashboard
|
||||
draws, and `recurrencia_desarrollo`, the tables behind them."""
|
||||
figures = [r for n in COHORTS for r in calculators[n][0]]
|
||||
points = pd.concat([calculators[n][1] for n in COHORTS], ignore_index=True)
|
||||
auc = pd.concat([fits[n].auc for n in COHORTS], ignore_index=True)
|
||||
|
||||
def table(df: pd.DataFrame) -> dict:
|
||||
df = df.replace([np.inf, -np.inf], np.nan).astype(object)
|
||||
return {"columnas": [str(c) for c in df.columns], "filas": df.where(df.notna(), None).to_dict("records")}
|
||||
|
||||
return {"recurrencia": {"version": 1, "horizons_months": list(recurrence["horizons"]), "escenarios": figures},
|
||||
"recurrencia_desarrollo": {"version": 1, "tablas": {"auc": table(auc), "factores_riesgo": table(factors_table),
|
||||
"calculadora": table(points), "escenarios_resumen": table(scenario_factors["resumen"])}}}
|
||||
@@ -0,0 +1,33 @@
|
||||
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, from two external cohorts (METABRIC and SCAN-B).
|
||||
# Trained from governance on the files in `data/`; the scenarios' figures are what the dashboard shows. Its covariates are the
|
||||
# cohorts' own; the hospital's patient is placed in the scenarios her covariates meet.
|
||||
domain = "cama"
|
||||
scenario = "recurrence"
|
||||
cohort = "cama/externa"
|
||||
outcome = "recurrencia"
|
||||
external = true # trained on files, not on a dbt cohort of the platform
|
||||
modules = ["models.cama.recurrence.model"]
|
||||
description = """\
|
||||
Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
|
||||
regresión logística y una red bayesiana por horizonte, entrenadas en dos cohortes externas (METABRIC y SCAN-B). Pendiente \
|
||||
de validación clínica."""
|
||||
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
|
||||
|
||||
[config.recurrence]
|
||||
data_dir = "" # empty: the `data/` folder of this package
|
||||
horizons = [12, 36, 60] # months
|
||||
v_max = 0.80 # Cramér's V from which of two covariates the one with more unknowns is dropped
|
||||
seed = 42
|
||||
bdeu_ess = 10
|
||||
max_parents = 6
|
||||
alpha_in = 0.10
|
||||
alpha_out = 0.15
|
||||
alpha_prefilter = 0.10
|
||||
alpha = 0.05 # the risk factors' significance
|
||||
freq_min = 0.80 # the bootstrap's stability criterion
|
||||
n_bootstrap_metabric = 100
|
||||
n_bootstrap_scanb = 40
|
||||
n_boot_calc = 200 # replicas of each scenario's interval
|
||||
min_events = 15 # recurrences a scenario needs to be drawn
|
||||
cap_months = 72 # the figure's time axis
|
||||
ks_seconds = 60 # time budget of each fractional Weibull fit
|
||||
@@ -0,0 +1,194 @@
|
||||
"""The recurrence models of one cohort: at each horizon the logistic regression (stepwise) and the Bayesian network (the
|
||||
BDeu-greedy parents of the outcome), their AUC by internal validation and by bootstrap, how often each covariate enters the
|
||||
bootstrap's regressions and the parents, and the penalised Cox model's concordance. Ported from `03_modelado.py` without its
|
||||
figures. The selected terms and parents of each horizon are what the risk factors and the calculator read.
|
||||
"""
|
||||
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from lifelines import CoxPHFitter
|
||||
from lifelines.utils import concordance_index
|
||||
from pgmpy.estimators import BDeu
|
||||
from sklearn.metrics import roc_auc_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.recurrence.prep import Prepared
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FitSettings:
|
||||
seed: int = 42
|
||||
n_bootstrap: int = 100
|
||||
bdeu_ess: int = 10
|
||||
max_parents: int = 6
|
||||
alpha_in: float = 0.10
|
||||
alpha_out: float = 0.15
|
||||
alpha_prefilter: float = 0.10
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class CohortModels:
|
||||
models: dict[str, dict] # by horizon: the LR terms, the HBN parents and how often each entered the bootstrap
|
||||
auc: pd.DataFrame
|
||||
c_index: float
|
||||
|
||||
|
||||
class _Fitter:
|
||||
def __init__(self, prepared: Prepared, settings: FitSettings):
|
||||
self.covariates, self.s, self.total = prepared.covariates, settings, prepared.cohort
|
||||
|
||||
def encode(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
|
||||
return X.loc[:, X.nunique() > 1]
|
||||
|
||||
@staticmethod
|
||||
def logit(y, X):
|
||||
try:
|
||||
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def prefilter(self, X, y) -> list[str]:
|
||||
keep = []
|
||||
for c in X.columns:
|
||||
m = self.logit(y, X[[c]])
|
||||
if m is not None and m.pvalues[c] < self.s.alpha_prefilter:
|
||||
keep.append(c)
|
||||
return keep
|
||||
|
||||
def stepwise(self, X, y) -> list[str]:
|
||||
included = []
|
||||
for _ in range(200):
|
||||
changed, best, best_p = False, None, self.s.alpha_in
|
||||
for c in [c for c in X.columns if c not in included]:
|
||||
m = self.logit(y, X[included + [c]])
|
||||
if m is not None and m.pvalues[c] < best_p:
|
||||
best, best_p = c, m.pvalues[c]
|
||||
if best is not None:
|
||||
included.append(best)
|
||||
changed = True
|
||||
if included:
|
||||
m = self.logit(y, X[included])
|
||||
if m is not None:
|
||||
p = m.pvalues.drop("const")
|
||||
if p.max() > self.s.alpha_out:
|
||||
included.remove(p.idxmax())
|
||||
changed = True
|
||||
if not changed:
|
||||
break
|
||||
return included
|
||||
|
||||
def lr(self, train: pd.DataFrame, test: pd.DataFrame):
|
||||
X_all = self.encode(pd.concat([train, test]))
|
||||
X_tr, X_te = X_all.loc[train.index], X_all.loc[test.index]
|
||||
X_tr = X_tr.loc[:, X_tr.nunique() > 1]
|
||||
X_te = X_te[X_tr.columns]
|
||||
candidates = self.prefilter(X_tr, train["y"])
|
||||
selected = self.stepwise(X_tr[candidates], train["y"]) if candidates else []
|
||||
if not selected:
|
||||
return None, [], np.full(len(test), train["y"].mean())
|
||||
model = self.logit(train["y"], X_tr[selected])
|
||||
return model, selected, model.predict(sm.add_constant(X_te[selected], has_constant="add")).values
|
||||
|
||||
def variable_of(self, term: str) -> str:
|
||||
return next((c for c in sorted(self.covariates, key=len, reverse=True) if term.startswith(c + "_")), term)
|
||||
|
||||
def parents(self, train: pd.DataFrame) -> list[str]:
|
||||
score = BDeu(train, equivalent_sample_size=self.s.bdeu_ess)
|
||||
parents, current = [], score.local_score("outcome", [])
|
||||
while len(parents) < self.s.max_parents:
|
||||
best, gain = None, 0
|
||||
for c in self.covariates:
|
||||
if c in parents:
|
||||
continue
|
||||
g = score.local_score("outcome", parents + [c]) - current
|
||||
if g > gain:
|
||||
best, gain = c, g
|
||||
if best is None:
|
||||
break
|
||||
parents.append(best)
|
||||
current += gain
|
||||
return parents
|
||||
|
||||
def hbn(self, train: pd.DataFrame, test: pd.DataFrame, parents: list[str]) -> np.ndarray:
|
||||
if not parents:
|
||||
return np.full(len(test), (train["outcome"] == "1").mean())
|
||||
q = int(np.prod([train[p].nunique() for p in parents]))
|
||||
alpha = self.s.bdeu_ess / (2 * q)
|
||||
g = train.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
||||
overall = (train["outcome"] == "1").mean()
|
||||
table = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
|
||||
return np.array([table.get(k, overall) for k in map(tuple, test[parents].values)])
|
||||
|
||||
def bn_table(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
t = df[self.covariates].astype(str).copy()
|
||||
t["outcome"] = df["y"].astype(int).astype(str)
|
||||
return t
|
||||
|
||||
def at_horizon(self, H: int) -> pd.DataFrame:
|
||||
recurs = (self.total["evento"] == 1) & (self.total["tiempo_meses"] <= H)
|
||||
free = self.total["tiempo_meses"] > H
|
||||
d = self.total[recurs | free].reset_index(drop=True)
|
||||
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
|
||||
return d
|
||||
|
||||
|
||||
def fit_cohort(name: str, prepared: Prepared, horizons: list[int], settings: FitSettings) -> CohortModels:
|
||||
"""The LR and the HBN at each horizon, their AUC and the bootstrap's, and the Cox model's concordance."""
|
||||
warnings.filterwarnings("ignore")
|
||||
f, s = _Fitter(prepared, settings), settings
|
||||
total = prepared.cohort
|
||||
cox_df = pd.get_dummies(total[["tiempo_meses", "evento"] + f.covariates], columns=f.covariates, drop_first=True).astype(float)
|
||||
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
|
||||
tr, te = train_test_split(cox_df, test_size=0.3, random_state=s.seed, stratify=cox_df["evento"])
|
||||
ok = [c for c in tr.columns if c in ("tiempo_meses", "evento") or 10 <= tr[c].sum() <= len(tr) - 10]
|
||||
tr, te = tr[ok], te[ok]
|
||||
cox = CoxPHFitter(penalizer=0.05).fit(tr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
|
||||
c_index = float(concordance_index(te["tiempo_meses"], -cox.predict_partial_hazard(te), te["evento"]))
|
||||
|
||||
rows, models = [], {}
|
||||
for H in horizons:
|
||||
coh = f.at_horizon(H)
|
||||
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=s.seed, stratify=coh["y"])
|
||||
train, test = coh.loc[tr_idx], coh.loc[te_idx]
|
||||
_, selected, p_lr = f.lr(train, test)
|
||||
auc_lr = roc_auc_score(test["y"], p_lr)
|
||||
bn_train, bn_test = f.bn_table(train), f.bn_table(test)
|
||||
parents = f.parents(bn_train)
|
||||
auc_hbn = roc_auc_score(test["y"], f.hbn(bn_train, bn_test, parents))
|
||||
rng = np.random.default_rng(s.seed)
|
||||
aucs, count_lr, count_hbn, n_rep = [], {}, {}, 0
|
||||
for b in range(s.n_bootstrap):
|
||||
boot = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
|
||||
try:
|
||||
b_train, b_test = train_test_split(boot, test_size=0.3, random_state=s.seed + b, stratify=boot["y"])
|
||||
m, _, p = f.lr(b_train, b_test)
|
||||
a_lr = roc_auc_score(b_test["y"], p)
|
||||
bt, be = f.bn_table(b_train), f.bn_table(b_test)
|
||||
pa = f.parents(bt)
|
||||
a_h = roc_auc_score(b_test["y"], f.hbn(bt, be, pa))
|
||||
except Exception:
|
||||
continue
|
||||
aucs.append((a_lr, a_h))
|
||||
n_rep += 1
|
||||
if m is not None:
|
||||
for v in {f.variable_of(t) for t in m.params.drop("const").index}:
|
||||
count_lr[v] = count_lr.get(v, 0) + 1
|
||||
for v in pa:
|
||||
count_hbn[v] = count_hbn.get(v, 0) + 1
|
||||
aucs = np.array(aucs) if aucs else np.full((1, 2), np.nan)
|
||||
for j, (label, auc) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
|
||||
rows.append({"cohorte": name, "horizonte_meses": H, "modelo": label, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
|
||||
"AUC_validacion_interna": auc, "AUC_bootstrap_medio": np.nanmean(aucs[:, j]),
|
||||
"AUC_bootstrap_IC95_inf": np.nanpercentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.nanpercentile(aucs[:, j], 97.5),
|
||||
"replicas_bootstrap": n_rep})
|
||||
models[str(H)] = {"terminos_lr": list(selected), "padres_hbn": parents, "n_replicas": n_rep,
|
||||
"seleccion_lr": count_lr, "seleccion_hbn": count_hbn,
|
||||
"arcos_hbn": [[p, "outcome"] for p in parents]}
|
||||
rows.append({"cohorte": name, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(total),
|
||||
"recurrencias": int(total["evento"].sum()), "AUC_validacion_interna": c_index})
|
||||
return CohortModels(models, pd.DataFrame(rows).round(4), c_index)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""A hospital patient in the recurrence analysis' terms: her covariates as the external cohorts name them, and the scenarios
|
||||
(subgroups defined by covariates) she belongs to. What the hospital does not report (nodes, subtype, surgery...) is not given, so
|
||||
a scenario that needs it does not include her."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence import prep
|
||||
|
||||
POSITIVE = {"POSITIVO": "Positive", "NEGATIVO": "Negative"}
|
||||
HER2 = {"H3": "Positive", "H0": "Negative", "H1": "Negative"} # 2+ is equivocal: not given
|
||||
|
||||
|
||||
def _bin(value, cuts: list, labels: list) -> str | None:
|
||||
if value is None or pd.isna(value):
|
||||
return None
|
||||
return str(pd.cut([float(value)], cuts, labels=labels, right=False)[0])
|
||||
|
||||
|
||||
def covariates_of(row: pd.Series) -> dict[str, str]:
|
||||
"""The covariates of one labelled member (`models.cama.survival.live.members`) that the cohorts also have."""
|
||||
found = {
|
||||
"Edad": _bin(row.get("age_years"), prep.AGE_CUTS, prep.AGE_LABELS),
|
||||
"Tamano_tumor": _bin(row.get("size_mm"), prep.SIZE_CUTS, prep.SIZE_LABELS),
|
||||
"Grado_histologico": {"G1": "1", "G2": "2", "G3": "3"}.get(row.get("grade")),
|
||||
"Receptor_estrogeno": POSITIVE.get(row.get("er")),
|
||||
"Receptor_progesterona": POSITIVE.get(row.get("pr")),
|
||||
"HER2": HER2.get(row.get("her2")),
|
||||
}
|
||||
return {k: v for k, v in found.items() if v is not None}
|
||||
|
||||
|
||||
def matching(scenarios: list[dict], covariates: dict[str, str]) -> list[dict]:
|
||||
"""The scenarios whose every condition her covariates meet, the larger first within each cohort."""
|
||||
met = [s for s in scenarios if all(var in covariates and covariates[var] in values for var, values in s["condiciones"].items())]
|
||||
return sorted(met, key=lambda s: (s["cohorte"], -s["n"]))
|
||||
@@ -0,0 +1,108 @@
|
||||
"""The recurrence analysis' data: the two external cohorts (METABRIC and SCAN-B) as one table each, the covariates as
|
||||
categories with the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped. Ported
|
||||
from `01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import chi2_contingency
|
||||
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
AGE_CUTS, AGE_LABELS = [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]
|
||||
SIZE_CUTS, SIZE_LABELS = [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]
|
||||
NODE_CUTS, NODE_LABELS = [0, 1, 4, 1e3], ["0", "1-3", "4+"]
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Prepared:
|
||||
cohort: pd.DataFrame # paciente, tiempo_meses, evento and the covariates
|
||||
covariates: list[str]
|
||||
treatment: list[str]
|
||||
eliminated: list[str]
|
||||
|
||||
|
||||
def _unknown(s: pd.Series) -> pd.Series:
|
||||
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
|
||||
|
||||
|
||||
def _cut(s: pd.Series, cuts: list, labels: list) -> pd.Series:
|
||||
return _unknown(pd.cut(s, cuts, labels=labels, right=False).astype("object"))
|
||||
|
||||
|
||||
def cramer_v(a: pd.Series, b: pd.Series) -> float:
|
||||
table = pd.crosstab(a, b)
|
||||
chi2 = chi2_contingency(table, correction=False)[0]
|
||||
k = min(table.shape) - 1
|
||||
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
|
||||
|
||||
|
||||
def _drop_collinear(out: pd.DataFrame, covariates: list[str], treatment: list[str], v_max: float) -> tuple[list[str], list[str]]:
|
||||
"""Of each pair of non-treatment covariates with V at or above `v_max`, the one with more unknowns goes."""
|
||||
covariates, eliminated = list(covariates), []
|
||||
candidates = [c for c in covariates if c not in treatment]
|
||||
pairs = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]), reverse=True)
|
||||
for v, a, b in pairs:
|
||||
if v < v_max:
|
||||
break
|
||||
if a in eliminated or b in eliminated:
|
||||
continue
|
||||
drop = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
|
||||
eliminated.append(drop)
|
||||
covariates.remove(drop)
|
||||
return covariates, eliminated
|
||||
|
||||
|
||||
def _finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
|
||||
covariates = [c for c in out.columns if c not in fixed]
|
||||
covariates, eliminated = _drop_collinear(out, covariates, treatment, v_max)
|
||||
return Prepared(out[[*fixed, *covariates]], covariates, [c for c in treatment if c in covariates], eliminated)
|
||||
|
||||
|
||||
def prepare_metabric(path: str, v_max: float) -> Prepared:
|
||||
d = pd.read_csv(path, sep="\t")
|
||||
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
|
||||
out = pd.DataFrame({"paciente": d["Patient ID"]})
|
||||
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
|
||||
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
|
||||
out["Edad"] = _cut(d["Age at Diagnosis"], AGE_CUTS, AGE_LABELS)
|
||||
out["Tamano_tumor"] = _cut(d["Tumor Size"], SIZE_CUTS, SIZE_LABELS)
|
||||
out["Ganglios_positivos"] = _cut(d["Lymph nodes examined positive"], NODE_CUTS, NODE_LABELS)
|
||||
out["Grado_histologico"] = _unknown(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
|
||||
mutations = d["Mutation Count"]
|
||||
q = mutations.quantile([1 / 3, 2 / 3]).values
|
||||
out["Carga_mutacional"] = _cut(mutations, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
|
||||
for name, column in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
|
||||
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
|
||||
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
|
||||
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
|
||||
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
|
||||
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
|
||||
out[name] = _unknown(d[column])
|
||||
return _finish(out, ["paciente", "tiempo_meses", "evento"], ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], v_max)
|
||||
|
||||
|
||||
def prepare_scanb(path: str, v_max: float) -> Prepared:
|
||||
d = pd.read_csv(path, sep="\t", low_memory=False)
|
||||
d = d[d["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
|
||||
out = pd.DataFrame({"paciente": d["PatientName"]})
|
||||
out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH
|
||||
out["evento"] = d["RFI_event"].astype(int)
|
||||
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
|
||||
out["Edad"] = _cut(d["Age_5year_bin"].astype(float) - 2, AGE_CUTS, AGE_LABELS)
|
||||
out["Tamano_tumor"] = _cut(d["TumorSize_mm"], SIZE_CUTS, SIZE_LABELS)
|
||||
out["Ganglios_positivos"] = _unknown(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
|
||||
out["Grado_histologico"] = _unknown(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
|
||||
for name, column in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
|
||||
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
|
||||
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
|
||||
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
|
||||
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
|
||||
out[name] = _unknown(d[column])
|
||||
return _finish(out, ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
||||
["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], v_max)
|
||||
|
||||
|
||||
PREPARE = {"metabric": prepare_metabric, "scanb": prepare_scanb}
|
||||
FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""The recurrence analysis' training data: two files on disk, not a cohort of the platform. It takes the part of a cohort source
|
||||
(`models.io.storage.CohortSource`) for the training run: the reference the version is traced to, which is the hash of the files."""
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence.prep import FILES
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG
|
||||
from models.io.registry import REFERENCE_SOURCE
|
||||
|
||||
PACKAGE_DATA = Path(__file__).parent / "data"
|
||||
URL = "cama/externa/metabric+scanb"
|
||||
|
||||
|
||||
def data_folder(configured: str) -> Path:
|
||||
return Path(configured) if configured else PACKAGE_DATA
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExternalCohorts:
|
||||
"""The METABRIC and SCAN-B files of a folder."""
|
||||
|
||||
folder: Path = PACKAGE_DATA
|
||||
armado_id: int | None = None
|
||||
|
||||
def sha256(self) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for name in sorted(FILES.values()):
|
||||
digest.update((self.folder / name).read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
def frame(self) -> pd.DataFrame:
|
||||
return pd.DataFrame()
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
return {"url": URL, "files": ",".join(sorted(FILES.values())), "sha256": self.sha256()}
|
||||
|
||||
def reference(self) -> dict[str, str]:
|
||||
return {COHORT_URL_TAG: URL, COHORT_SOURCE_TAG: REFERENCE_SOURCE, COHORT_BUILD_TAG: self.sha256()}
|
||||
@@ -0,0 +1,31 @@
|
||||
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
|
||||
def run_steps(args: argparse.Namespace) -> int:
|
||||
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
|
||||
from models.__main__ import _promote_step
|
||||
from models.cama.recurrence.source import ExternalCohorts, data_folder
|
||||
from models.dags.training import Scenario, find_trained, train
|
||||
|
||||
if args.export or args.estimate or args.store or args.version:
|
||||
print("cama/recurrence trains on its external cohorts: only --train and --promote apply", file=sys.stderr)
|
||||
return 2
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
source = ExternalCohorts(data_folder(scenario.config["recurrence"]["data_dir"]))
|
||||
environment = args.environment.upper()
|
||||
version = find_trained(scenario, source, environment)
|
||||
if args.train:
|
||||
if version:
|
||||
print(f"already trained: version {version}, from {source.lineage()['sha256'][:12]}")
|
||||
else:
|
||||
version = train(scenario, source, environment)
|
||||
print(f"trained: version {version}, from {source.lineage()['sha256'][:12]}")
|
||||
if args.promote:
|
||||
if not version:
|
||||
print(f"no {environment} version trained: use --train", file=sys.stderr)
|
||||
return 1
|
||||
return _promote_step(args, version)
|
||||
return 0
|
||||
@@ -151,64 +151,7 @@ xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty
|
||||
|
||||
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
|
||||
|
||||
# Subgroups: every condition present must hold. her2 = "pos" | "neg"; triple_negative (HR-/HER2-); age_min (>=) and
|
||||
# age_max (<) in years; stages (0..4); conservative (conservative surgery).
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
|
||||
her2 = "pos"
|
||||
age_min = 60
|
||||
stages = [3, 4]
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
|
||||
her2 = "pos"
|
||||
age_max = 60
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio IV"
|
||||
stages = [4]
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio I"
|
||||
stages = [1]
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 75 años"
|
||||
age_min = 75
|
||||
[[survival.subgroups]]
|
||||
name = "< 45 años"
|
||||
age_max = 45
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
age_max = 45
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · estadio 0–II · cirugía conservadora"
|
||||
her2 = "pos"
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · estadio 0–II"
|
||||
age_max = 45
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2−"
|
||||
her2 = "neg"
|
||||
age_max = 45
|
||||
[[survival.subgroups]]
|
||||
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
|
||||
triple_negative = true
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
age_min = 65
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
# The subgroups of the survival curves, and the risk factors of each, are the clinical scenarios of `scenarios.py`.
|
||||
|
||||
[risk_factors]
|
||||
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
|
||||
|
||||
@@ -53,11 +53,12 @@ STAGES = [
|
||||
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,),
|
||||
("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
|
||||
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"),
|
||||
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "settings.py", "run.py")),
|
||||
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "scenarios.py", "settings.py", "run.py")),
|
||||
Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
|
||||
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
|
||||
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"),
|
||||
("risk_factors.py", "risk_factor_stats.py", "settings.py", "run.py")),
|
||||
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv",
|
||||
"escenarios_factores_riesgo.csv", "escenarios_resumen.csv"),
|
||||
("risk_factors.py", "risk_factor_stats.py", "scenarios.py", "settings.py", "run.py")),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import risk_factor_stats as stats
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival.settings import RiskFactorSettings
|
||||
|
||||
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
@@ -233,3 +234,73 @@ def risk_criteria(risk_classification: Classification, risk_bootstrap_frequency:
|
||||
"horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
|
||||
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
|
||||
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the risk factors of each clinical scenario
|
||||
|
||||
PCT_DEFINING = 0.95 # the category is in at least this share of the scenario: it defines it
|
||||
PCT_MAJORITY = 0.50
|
||||
PCT_PRESENT = 0.10
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class ScenarioFactors:
|
||||
details: pd.DataFrame # per scenario and classified category: its share of the scenario and of the cohort
|
||||
summary: pd.DataFrame # per scenario: the risk factors, protectors and treatments that define it or are most of it
|
||||
|
||||
|
||||
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 risk_scenario_masks(risk_natural: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each clinical scenario's mask over the natural population (`scenarios.masks`), on its raw columns."""
|
||||
return scenarios.masks(risk_natural.drop(columns=[c for c in ("Age_group", "Tumor_group") if c in risk_natural.columns]))
|
||||
|
||||
|
||||
def risk_scenario_factors(risk_classification: Classification, risk_treatment_associations: pd.DataFrame | None,
|
||||
risk_data: pd.DataFrame, risk_scenario_masks: dict[str, np.ndarray]) -> ScenarioFactors:
|
||||
"""Which of the classified risk factors, protectors and treatment associations make up each clinical scenario: a
|
||||
category that is nearly all of a scenario defines it, one that is most of it describes it."""
|
||||
table = risk_classification.table
|
||||
classified = table[table["clasificacion"].str.contains("robusto|sugerente")].copy()
|
||||
classified["tipo"] = classified["clasificacion"].str.split().str[0]
|
||||
if risk_treatment_associations is not None and len(risk_treatment_associations):
|
||||
treatment = risk_treatment_associations.copy()
|
||||
treatment["clasificacion"], treatment["tipo"] = "tratamiento (no se clasifica)", "tratamiento"
|
||||
classified = pd.concat([classified, treatment], ignore_index=True)
|
||||
details, summary = [], []
|
||||
for name, mask in risk_scenario_masks.items():
|
||||
size = int(mask.sum())
|
||||
if size == 0:
|
||||
continue
|
||||
definition = scenarios.describe(scenarios.SCENARIOS[name]) if name in scenarios.SCENARIOS else ""
|
||||
rows = []
|
||||
for _, r in classified.iterrows():
|
||||
share = float((risk_data[r["variable"]][mask] == r["categoria"]).mean())
|
||||
rows.append({"escenario": name, "definicion": definition, "n_escenario": size,
|
||||
"tipo": r["tipo"], "variable": r["variable"], "categoria": r["categoria"], "clasificacion": r["clasificacion"],
|
||||
"OR_muerte": r["OR_muerte"], "IC95_inf": r["IC95_inf"], "IC95_sup": r["IC95_sup"], "delta_S18": r["delta_S18"],
|
||||
"pct_en_escenario": share, "pct_en_cohorte": float((risk_data[r["variable"]] == r["categoria"]).mean()),
|
||||
"presencia": _presence(share)})
|
||||
found = pd.DataFrame(rows, columns=["escenario", "definicion", "n_escenario", "tipo", "variable", "categoria", "clasificacion",
|
||||
"OR_muerte", "IC95_inf", "IC95_sup", "delta_S18", "pct_en_escenario", "pct_en_cohorte", "presencia"])
|
||||
details.append(found[found["pct_en_escenario"] >= PCT_PRESENT])
|
||||
|
||||
def listed(kind, levels):
|
||||
part = found[(found["tipo"] == kind) & (found["presencia"].isin(levels))]
|
||||
return "; ".join(f"{a}={b} ({c.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
|
||||
for a, b, c, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
|
||||
|
||||
row = {"escenario": name, "definicion": definition, "n_escenario": size}
|
||||
for kind in ("riesgo", "protector", "tratamiento"):
|
||||
row[f"{kind}_definitorios"] = listed(kind, ["definitoria"])
|
||||
row[f"{kind}_mayoritarios"] = listed(kind, ["mayoritaria"])
|
||||
row["n_factores_riesgo_incluidos"] = int(((found["tipo"] == "riesgo") & found["presencia"].isin(["definitoria", "mayoritaria"])).sum())
|
||||
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
|
||||
summary.append(row)
|
||||
return ScenarioFactors(pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame(), pd.DataFrame(summary))
|
||||
|
||||
@@ -193,13 +193,15 @@ def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv:
|
||||
inputs = {"natural_csv": str(natural_csv),
|
||||
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.csv"),
|
||||
"hbn_arcs_csv": str(hbn_arcs_csv or out / "hbn_arcos.csv"), "risk_factors": settings.risk_factors}
|
||||
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria"],
|
||||
inputs=inputs)
|
||||
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria",
|
||||
"risk_scenario_factors"], inputs=inputs)
|
||||
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
|
||||
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
|
||||
if r["risk_treatment_associations"] is not None:
|
||||
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
|
||||
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"])
|
||||
r["risk_scenario_factors"].details.to_csv(out / "escenarios_factores_riesgo.csv", index=False)
|
||||
r["risk_scenario_factors"].summary.to_csv(out / "escenarios_resumen.csv", index=False)
|
||||
return r
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The clinical scenarios of the survival analysis: the subgroups whose curves stage 5 draws and whose risk factors stage 6
|
||||
lists. Each is a set of conditions over the cohort's raw columns (age, stage, molecular subtype, surgery); the columns are
|
||||
found by keyword, so a cohort without one of them has no patient in the scenarios that need it. Ported from
|
||||
`escenarios_clinicos.py`.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def find_col(df: pd.DataFrame, keywords) -> str | None:
|
||||
for col in df.columns:
|
||||
d = col.lower().replace("_", " ")
|
||||
if any(k in d for k in keywords):
|
||||
return col
|
||||
return None
|
||||
|
||||
|
||||
def _age(v) -> float:
|
||||
m = re.search(r"\d+", str(v))
|
||||
return float(m.group()) if m else np.nan
|
||||
|
||||
|
||||
def _stage(v) -> float:
|
||||
u = str(v).upper().replace("STAGE", "").strip()
|
||||
if u.startswith("0") or u == "IS":
|
||||
return 0
|
||||
for prefix, value in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
|
||||
if u.startswith(prefix):
|
||||
return value
|
||||
return np.nan
|
||||
|
||||
|
||||
def _age_column(df: pd.DataFrame) -> str | None:
|
||||
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
|
||||
if not candidates:
|
||||
return None
|
||||
return sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
|
||||
|
||||
|
||||
def values_by_axis(df: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
|
||||
col_subtype = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
|
||||
col_surgery = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
|
||||
col_age = _age_column(df)
|
||||
n = len(df)
|
||||
return {
|
||||
"edad": df[col_age].map(_age).astype(float) if col_age else pd.Series(np.nan, index=df.index),
|
||||
"estadio": df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index),
|
||||
"subtipo": df[col_subtype].astype(str) if col_subtype else pd.Series([""] * n, index=df.index),
|
||||
"cirugia": df[col_surgery].astype(str).str.lower() if col_surgery else pd.Series([""] * n, index=df.index),
|
||||
}
|
||||
|
||||
|
||||
AGE_BELOW = lambda x: ("edad", "<", x)
|
||||
AGE_FROM = lambda x: ("edad", ">=", x)
|
||||
STAGE_0_II = ("estadio", "en", [0, 1, 2])
|
||||
STAGE_III_IV = ("estadio", "en", [3, 4])
|
||||
HER2_POS = ("subtipo", "contiene", "HER2+")
|
||||
HER2_NEG = ("subtipo", "contiene", "HER2-")
|
||||
TRIPLE_NEG = ("subtipo", "contiene", "HR-/HER2-")
|
||||
CONSERVATIVE = ("cirugia", "contiene", "conserv")
|
||||
|
||||
SCENARIOS = {
|
||||
"HER2+ · ≥60 años · estadio III–IV (Alto)": [HER2_POS, AGE_FROM(60), STAGE_III_IV],
|
||||
"HER2+ · <60 años · estadio 0–II (Bajo)": [HER2_POS, AGE_BELOW(60), STAGE_0_II],
|
||||
"Estadio IV": [("estadio", "en", [4])],
|
||||
"Estadio I": [("estadio", "en", [1])],
|
||||
"≥ 75 años": [AGE_FROM(75)],
|
||||
"< 45 años": [AGE_BELOW(45)],
|
||||
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": [AGE_BELOW(45), HER2_NEG, STAGE_0_II, CONSERVATIVE],
|
||||
"HER2− · estadio 0–II · cirugía conservadora": [HER2_NEG, STAGE_0_II, CONSERVATIVE],
|
||||
"HER2+ · estadio 0–II · cirugía conservadora": [HER2_POS, STAGE_0_II, CONSERVATIVE],
|
||||
"Jóvenes (<45) · estadio 0–II": [AGE_BELOW(45), STAGE_0_II],
|
||||
"Jóvenes (<45) · HER2−": [AGE_BELOW(45), HER2_NEG],
|
||||
"Triple negativo (HR−/HER2−) · estadio 0–II": [TRIPLE_NEG, STAGE_0_II],
|
||||
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": [AGE_FROM(65), HER2_NEG, STAGE_0_II, CONSERVATIVE],
|
||||
}
|
||||
|
||||
STAGE_LABEL = {0: "0", 1: "I", 2: "II", 3: "III", 4: "IV"}
|
||||
|
||||
|
||||
def describe(conditions) -> str:
|
||||
parts = []
|
||||
for axis, op, value in conditions:
|
||||
if axis == "edad":
|
||||
parts.append(f"edad {op} {value:g}")
|
||||
elif axis == "estadio":
|
||||
parts.append("estadio " + "/".join(STAGE_LABEL[v] for v in value))
|
||||
elif axis == "subtipo":
|
||||
parts.append(f"subtipo {value}")
|
||||
elif axis == "cirugia":
|
||||
parts.append("cirugía conservadora")
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def masks(df: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each scenario's mask over the cohort: every condition must hold."""
|
||||
values = values_by_axis(df)
|
||||
out = {}
|
||||
for name, conditions in SCENARIOS.items():
|
||||
mask = pd.Series(True, index=df.index)
|
||||
for axis, op, value in conditions:
|
||||
s = values[axis]
|
||||
if op == "<":
|
||||
mask &= (s < value).fillna(False)
|
||||
elif op == ">=":
|
||||
mask &= (s >= value).fillna(False)
|
||||
elif op == "en":
|
||||
mask &= s.isin(value)
|
||||
else:
|
||||
mask &= s.str.contains(value, regex=False)
|
||||
out[name] = mask.values.astype(bool)
|
||||
return out
|
||||
@@ -148,7 +148,6 @@ class SurvivalSettings:
|
||||
ks_sub_max_seconds: int
|
||||
xlim_sub: tuple[float, ...]
|
||||
ylim_sub: dict
|
||||
subgroups: tuple[dict, ...]
|
||||
|
||||
@property
|
||||
def file_suffix(self) -> str:
|
||||
@@ -212,6 +211,5 @@ def load(path: Path = TOML) -> Settings:
|
||||
categorization=_group(CategorizationSettings, raw["categorization"]),
|
||||
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
|
||||
modeling=_group(ModelingSettings, raw["modeling"]),
|
||||
survival=_group(SurvivalSettings, {**raw["survival"],
|
||||
"subgroups": tuple(raw["survival"]["subgroups"])}),
|
||||
survival=_group(SurvivalSettings, raw["survival"]),
|
||||
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
|
||||
|
||||
@@ -16,6 +16,7 @@ from matplotlib.figure import Figure
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
from models.cama.seer_survival import fractional_weibull as fw
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival import survival_models as sm
|
||||
from models.cama.seer_survival.settings import SurvivalSettings
|
||||
|
||||
@@ -322,50 +323,9 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.
|
||||
|
||||
# ---------------------------------------------------------------- subgroups
|
||||
|
||||
def _stage(v):
|
||||
u = str(v).upper().replace("STAGE", "").strip()
|
||||
if u.startswith("0") or u == "IS":
|
||||
return 0
|
||||
for prefix, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
|
||||
if u.startswith(prefix):
|
||||
return val
|
||||
return np.nan
|
||||
|
||||
|
||||
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]:
|
||||
"""Each subgroup's mask over the cohort: every condition of its spec must hold."""
|
||||
df = sv_frame.df
|
||||
n = len(df)
|
||||
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else _find_col(df, ["estadio", "stage"])
|
||||
col_sub = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else _find_col(df, ["subtipo", "subtype"])
|
||||
col_surg = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else _find_col(df, ["quirurg", "surg"])
|
||||
age = df["_edad"].values.astype(float)
|
||||
stage = (df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index)).values.astype(float)
|
||||
sub = df[col_sub].astype(str) if col_sub else None
|
||||
flags = {"her2neg": sub.str.contains("HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"triple_negative": sub.str.contains("HR-/HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"her2pos": sub.str.contains("HER2+", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"conservative": (df[col_surg].astype(str).str.lower().str.contains("conserv").values
|
||||
if col_surg else np.zeros(n, bool))}
|
||||
masks = {}
|
||||
for spec in survival.subgroups:
|
||||
mask = np.ones(n, bool)
|
||||
if spec.get("her2") == "pos":
|
||||
mask &= flags["her2pos"]
|
||||
if spec.get("her2") == "neg":
|
||||
mask &= flags["her2neg"]
|
||||
if spec.get("triple_negative"):
|
||||
mask &= flags["triple_negative"]
|
||||
if spec.get("conservative"):
|
||||
mask &= flags["conservative"]
|
||||
if "age_min" in spec:
|
||||
mask &= age >= spec["age_min"]
|
||||
if "age_max" in spec:
|
||||
mask &= age < spec["age_max"]
|
||||
if "stages" in spec:
|
||||
mask &= np.isin(stage, spec["stages"])
|
||||
masks[spec["name"]] = mask
|
||||
return masks
|
||||
"""Each clinical scenario's mask over the cohort (`scenarios.masks`): every condition of the scenario must hold."""
|
||||
return scenarios.masks(sv_frame.df)
|
||||
|
||||
|
||||
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
|
||||
|
||||
@@ -16,6 +16,8 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.survival.estimator import molecular_subtype
|
||||
|
||||
|
||||
UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat")
|
||||
# What the dashboard reads: the file written by a stage, under the name it is published with.
|
||||
@@ -24,6 +26,7 @@ TABLES = {
|
||||
"metricas_diferenciacion.csv": "metricas_diferenciacion", "auc_validacion_interna.csv": "auc_validacion_interna",
|
||||
"seleccion_bootstrap.csv": "seleccion_bootstrap", "auc_bootstrap.csv": "auc_bootstrap",
|
||||
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
|
||||
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
|
||||
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
|
||||
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
|
||||
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
|
||||
@@ -49,6 +52,7 @@ def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame:
|
||||
("Receptor_estrogeno_cat", "er"), ("Receptor_progesterona_cat", "pr"),
|
||||
("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")):
|
||||
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy()
|
||||
frame["Subtipo_molecular_cat"] = molecular_subtype(lm).to_numpy() # the scenarios of stage 5 and 6 read the subtype
|
||||
for column in UNAVAILABLE:
|
||||
frame[column] = "Desconocido"
|
||||
return frame
|
||||
|
||||
@@ -34,6 +34,16 @@ DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above
|
||||
EPOCH = pd.Timestamp("1970-01-01")
|
||||
|
||||
|
||||
def molecular_subtype(labelled: pd.DataFrame) -> pd.Series:
|
||||
"""The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and
|
||||
negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario."""
|
||||
hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO")
|
||||
hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"])
|
||||
her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"})
|
||||
subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido")
|
||||
return pd.Series(subtype, index=labelled.index)
|
||||
|
||||
|
||||
def survival_settings(table: dict) -> SurvivalSettings:
|
||||
"""`SurvivalSettings` from a `[config.survival]` table: lists become tuples, an unknown key is an error."""
|
||||
return SurvivalSettings(**{key: tuple(value) if isinstance(value, list) else value for key, value in table.items()})
|
||||
@@ -110,7 +120,7 @@ def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings: Su
|
||||
"""The pipeline's `Cohort` of these members, with the categories and dummy columns it was coded by."""
|
||||
X_dum, X_int, categories, dummy_columns = encode(features)
|
||||
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
|
||||
X_int.max(axis=0) + 1, [0, *settings.horizons], None)
|
||||
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
|
||||
return cohort, categories, dummy_columns
|
||||
|
||||
|
||||
@@ -176,6 +186,13 @@ class IntervalSurvival(BaseEstimator):
|
||||
"""Each member's survival to each horizon."""
|
||||
return np.cumprod(self.interval_proba(X), axis=1)
|
||||
|
||||
def component_survival(self, X: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each member's survival to each horizon by the logistic regression, by the Bayesian network and by their
|
||||
stacked combination (`survival_proba`)."""
|
||||
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
|
||||
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
|
||||
return {"LR": np.cumprod(P_lr, axis=1), "HBN": np.cumprod(P_hb, axis=1), "COMB": self.survival_proba(X)}
|
||||
|
||||
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
|
||||
mortality = 1.0 - self.survival_proba(X)
|
||||
if INDEX_COLUMN not in X.columns:
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
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.dags.training import Scenario, dataflow
|
||||
|
||||
MIN_MEMBERS = 30
|
||||
MIN_EVENTS = 5
|
||||
REPLICAS = 200
|
||||
SEED = 42
|
||||
WHOLE = "Toda la cohorte"
|
||||
|
||||
|
||||
class QueryError(ValueError):
|
||||
"""The scenario cannot be answered; the message says why, in the reader's language."""
|
||||
|
||||
|
||||
def rehydrate(model) -> IntervalSurvival:
|
||||
"""The fitted model as the current `IntervalSurvival` code runs it. A version's saved model carries its class as it was
|
||||
when it was trained; its fitted state (`fitted_`, `weights_`, the codings) is what makes it that version, so that state
|
||||
is put in the current class and its methods are the code's."""
|
||||
current = IntervalSurvival.__new__(IntervalSurvival)
|
||||
current.__dict__.update(model.__dict__)
|
||||
return current
|
||||
|
||||
|
||||
def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFrame:
|
||||
"""Every member of the indexed cohort with her covariates and follow-up (the scenario's `labelled_members`)."""
|
||||
dr = dataflow(*scenario.modules, config=scenario.config)
|
||||
return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"]
|
||||
|
||||
|
||||
def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each scenario's mask over the members. The age and the subtype are the hospital's; stage and surgery are not reported
|
||||
yet, so a scenario that needs them has no member."""
|
||||
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy()}, index=labelled.index)
|
||||
return scenarios.masks(raw)
|
||||
|
||||
|
||||
def answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool:
|
||||
return int(mask.sum()) >= MIN_MEMBERS and int(labelled["event"].to_numpy()[mask].sum()) >= MIN_EVENTS
|
||||
|
||||
|
||||
def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
|
||||
"""The scenarios `pac_id` belongs to and that have enough members to draw; the whole cohort when she is in none."""
|
||||
row = np.flatnonzero(labelled["pac_id"].to_numpy() == pac_id)
|
||||
if len(row) == 0:
|
||||
raise QueryError("La paciente no está en la cohorte del modelo.")
|
||||
found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and answerable(labelled, mask)]
|
||||
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 curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) -> dict:
|
||||
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone) scored with `model` (the fitted
|
||||
`IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything."""
|
||||
if name in (None, WHOLE):
|
||||
mask = np.ones(len(labelled), bool)
|
||||
else:
|
||||
masks = scenario_masks(labelled)
|
||||
if name not in masks:
|
||||
raise QueryError(f"No hay un escenario clínico «{name}».")
|
||||
mask = masks[name]
|
||||
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}.")
|
||||
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])
|
||||
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)
|
||||
S, low, high = luis.fw.km_curva(np.minimum(followed, cap), died & (followed < cap), cap)
|
||||
adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0)
|
||||
classic, fractional = luis._fit_to_curve(adjusted, len(selected), s, s.ks_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,
|
||||
"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", {})}
|
||||
@@ -33,23 +33,26 @@ observacion_previa_minima_dias = 0
|
||||
|
||||
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with its settings.
|
||||
[config.desarrollo]
|
||||
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort.
|
||||
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort,
|
||||
# with the pipeline's own budgets (`models/cama/seer_survival/model.toml`). The bootstrap and the proposals stop at their
|
||||
# time caps and use what they have. One adaptation: `exclude_censored_years` is off, because this follow-up is short and
|
||||
# would leave every year out of the outcome.
|
||||
enabled = true
|
||||
null_perm = 20
|
||||
n_bootstrap = 20
|
||||
bootstrap_max_seconds = 240
|
||||
bootstrap_restarts = 2
|
||||
n_splits_proposals = 2
|
||||
proposals_max_seconds = 120
|
||||
restarts = 4
|
||||
null_perm = 100
|
||||
n_bootstrap = 60
|
||||
bootstrap_max_seconds = 2700
|
||||
bootstrap_restarts = 3
|
||||
n_splits_proposals = 5
|
||||
proposals_max_seconds = 3600
|
||||
restarts = 10
|
||||
|
||||
[config.survival]
|
||||
age_mode = "categorizada"
|
||||
include_age = true
|
||||
age_cuts = [45, 60, 75]
|
||||
hbn_fixed_parents = [] # empty = learn the network's parents by the BDeu score
|
||||
hbn_age_parent = false
|
||||
hbn_parents = "reaprender"
|
||||
hbn_fixed_parents = ["histologic_type", "age_group"] # the SEER pipeline's expert parents that this data has (its stage and treatment are not reported yet); empty = learn them by the BDeu score
|
||||
hbn_age_parent = false # the grouped age is already in `hbn_fixed_parents`
|
||||
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
|
||||
covariates = []
|
||||
horizons = [6, 12, 18] # months
|
||||
censoring = "riesgo" # a model per interval using all the follow-up
|
||||
@@ -57,7 +60,7 @@ combine = true # one LR + HBN indicator, per-interval stacking
|
||||
show_individual = false
|
||||
stack_folds = 5
|
||||
stack_shrink = 20
|
||||
n_boot = 200
|
||||
n_boot = 100
|
||||
n_boot_sub = 100
|
||||
seed = 42
|
||||
hbn_ess = 1000
|
||||
@@ -71,24 +74,19 @@ inset_zoom = false
|
||||
inset_months = 18
|
||||
cap_months = 24 # follow-up is cut here: a later death counts as alive
|
||||
min_events_sub = 5
|
||||
ks_max_seconds = 30
|
||||
ks_sub_max_seconds = 30
|
||||
ks_max_seconds = 120
|
||||
ks_sub_max_seconds = 180
|
||||
xlim_sub = []
|
||||
ylim_sub = {}
|
||||
subgroups = []
|
||||
|
||||
# What the dashboard's survival chart says, in the clinicians' words (provisional: to be defined with them). The record a
|
||||
# training run publishes carries these, so changing one is a setting and a new run.
|
||||
[config.etiquetas]
|
||||
# The wording of the survival figure, as the SEER pipeline's own chart has it; to be defined with the clinicians.
|
||||
titulo = "Supervivencia después del primer reporte de biopsia con carcinoma invasor"
|
||||
eje_x = "Meses desde el reporte de biopsia"
|
||||
eje_y = "Probabilidad de supervivencia"
|
||||
km_crudo = "Kaplan-Meier (observada)"
|
||||
km_ajustada = "Kaplan-Meier ajustada por covariables"
|
||||
weibull = "Weibull ajustada"
|
||||
weibull_fraccional = "Weibull fraccional ajustada"
|
||||
puntos = "Modelo (LR + red bayesiana) con IC 95 %"
|
||||
LR = "Regresión logística"
|
||||
HBN = "Red bayesiana"
|
||||
COMB = "Modelo combinado"
|
||||
nota = "Datos simulados. Sin validación clínica."
|
||||
eje_x = "Meses desde el diagnóstico"
|
||||
eje_y = "Supervivencia S(t)"
|
||||
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
|
||||
weibull = "Weibull"
|
||||
weibull_fraccional = "Weibull fraccional"
|
||||
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
|
||||
|
||||
@@ -13,75 +13,76 @@ the clinicians' wording is a setting, not code.
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import fractional_weibull as fw
|
||||
from models.cama.seer_survival import survival_curves as luis
|
||||
from models.cama.seer_survival import survival_models as sm
|
||||
from models.cama.seer_survival.settings import SurvivalSettings
|
||||
from models.cama.survival.estimator import interval_cohort
|
||||
from models.cama.survival.estimator import FEATURES, UNKNOWN
|
||||
|
||||
SERIES = ("LR", "HBN", "COMB")
|
||||
GRID_STEP = 0.25 # months between the points of a fitted curve
|
||||
RECORD_VERSION = 1
|
||||
|
||||
|
||||
def curve_cohort(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
|
||||
"""The members, coded as the interval models take them."""
|
||||
return interval_cohort(labelled_members, labelled_members[["months", "event"]], survival_settings)[0]
|
||||
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
|
||||
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts as
|
||||
alive) and the covariates as categories."""
|
||||
s, lm = survival_settings, labelled_members
|
||||
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
|
||||
df["meses_int"] = df["meses"].astype(int)
|
||||
if s.cap_months:
|
||||
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
|
||||
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
|
||||
for name in FEATURES:
|
||||
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
|
||||
return luis.SurvivalFrame(df, list(FEATURES), None, [])
|
||||
|
||||
|
||||
def km_curve(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> dict:
|
||||
"""Kaplan-Meier from the index to `months_max`, with the Greenwood 95 % interval on the log-log scale."""
|
||||
horizon = max(survival_settings.months_max, max(survival_settings.horizons))
|
||||
S, low, high = fw.km_curva(labelled_members["months"].to_numpy(int), labelled_members["event"].to_numpy(bool), horizon)
|
||||
return {"months": list(range(horizon + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()}
|
||||
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
|
||||
"""The members coded as the stage-5 models take them (`survival_curves.sv_cohort`)."""
|
||||
return luis.sv_cohort(survival_frame, survival_settings)
|
||||
|
||||
|
||||
def adjusted_km(curve_cohort: sm.Cohort, km_curve: dict, survival_settings: SurvivalSettings) -> np.ndarray:
|
||||
"""The covariate-adjusted survival curve, month by month (direct standardization over the members)."""
|
||||
return sm.adjusted_curve(curve_cohort, np.arange(len(curve_cohort.months)), km_curve["months"][-1],
|
||||
survival_settings.adjust_step)
|
||||
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
|
||||
"""Kaplan-Meier with the Greenwood interval (`survival_curves.sv_km`)."""
|
||||
return luis.sv_km(survival_frame, survival_settings)
|
||||
|
||||
|
||||
def km_curve(km_raw: luis.KaplanMeier) -> dict:
|
||||
"""Kaplan-Meier from the index to `months_max`, with its interval, as the record carries it."""
|
||||
return {"months": list(range(km_raw.T + 1)), "S": km_raw.S.tolist(), "low": km_raw.lo.tolist(), "high": km_raw.hi.tolist()}
|
||||
|
||||
|
||||
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
|
||||
"""The covariate-adjusted survival curve, month by month (`survival_curves.sv_adjusted`)."""
|
||||
return luis.sv_adjusted(curve_cohort, km_raw, survival_settings)
|
||||
|
||||
|
||||
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
|
||||
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR."""
|
||||
everyone = np.ones(len(curve_cohort.months), bool)
|
||||
return sm.stacking_weights(curve_cohort, survival_settings, everyone,
|
||||
*sm.out_of_fold(curve_cohort, survival_settings, len(curve_cohort.months)))
|
||||
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR (`sv_weights_cohort`)."""
|
||||
return luis.sv_weights_cohort(curve_cohort, luis.sv_oof(curve_cohort, survival_settings), survival_settings)
|
||||
|
||||
|
||||
def point_estimates(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> dict:
|
||||
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member."""
|
||||
lr, hbn, combined, _ = sm.estimate_combined(curve_cohort, survival_settings, np.arange(len(curve_cohort.months)), None,
|
||||
population_weights["w_LR"].to_numpy())
|
||||
return {"LR": lr, "HBN": hbn, "COMB": combined}
|
||||
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
|
||||
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member (`sv_points`)."""
|
||||
return luis.sv_points(curve_cohort, population_weights, survival_settings)
|
||||
|
||||
|
||||
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> np.ndarray:
|
||||
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample."""
|
||||
s, n = survival_settings, len(curve_cohort.months)
|
||||
rng = np.random.default_rng(s.seed)
|
||||
weights = population_weights["w_LR"].to_numpy()
|
||||
rows = []
|
||||
for _ in range(s.n_boot):
|
||||
r = sm.estimate_combined(curve_cohort, s, rng.integers(0, n, n), None, weights)
|
||||
rows.append(np.concatenate([r[0], r[1], r[2]]))
|
||||
return np.array(rows) if rows else np.full((1, len(SERIES) * len(s.horizons)), np.nan)
|
||||
def point_estimates(luis_points: luis.Points) -> dict:
|
||||
return {"LR": luis_points.lr, "HBN": luis_points.hbn, "COMB": luis_points.combined}
|
||||
|
||||
|
||||
def _fixed_k(classic: dict, survival_settings: SurvivalSettings) -> float:
|
||||
return classic["k"] if survival_settings.k_ident == "clasico" else float(survival_settings.k_ident)
|
||||
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
|
||||
survival_settings: SurvivalSettings) -> np.ndarray:
|
||||
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample, the
|
||||
HBN's parents kept or learned again as `hbn_parents` says (`sv_bootstrap`)."""
|
||||
return luis.sv_bootstrap(curve_cohort, population_weights, luis_points, survival_settings)
|
||||
|
||||
|
||||
def weibull_fits(adjusted_km: np.ndarray, curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> dict:
|
||||
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
|
||||
"""The classic and the fractional Weibull fitted to the adjusted curve as if it came from as many members as the
|
||||
cohort has, evaluated on a grid of months, with their parameters."""
|
||||
S, n = adjusted_km, len(curve_cohort.months)
|
||||
d = np.concatenate([np.maximum(n * (S[:-1] - S[1:]), 0.0), [0.0, 0.0]])
|
||||
c = np.zeros(len(d))
|
||||
c[len(S) - 1] = n * S[-1]
|
||||
classic = fw.ajustar_weibull(d, c)
|
||||
fractional = fw.ajustar_ks(d, c, k_fijo=_fixed_k(classic, survival_settings), lam_ref=classic["lam"],
|
||||
max_seg=survival_settings.ks_max_seconds)
|
||||
grid = np.arange(0, len(S) - 1 + GRID_STEP, GRID_STEP)
|
||||
cohort has (`survival_curves._fit_to_curve`), evaluated on a grid of months, with their parameters."""
|
||||
classic, fractional = luis._fit_to_curve(adjusted_km, len(survival_frame.df), survival_settings, survival_settings.ks_max_seconds)
|
||||
grid = np.arange(0, len(adjusted_km) - 1 + GRID_STEP, GRID_STEP)
|
||||
parameters = lambda fit: {key: float(fit[key]) for key in ("k", "alpha", "beta", "lam", "nll") if key in fit}
|
||||
return {"t": grid.tolist(), "classic": np.asarray(classic["S"](grid), float).tolist(),
|
||||
"fractional": np.asarray(fractional["S"](grid), float).tolist(),
|
||||
|
||||
@@ -38,6 +38,7 @@ seer-survival = [
|
||||
"networkx>=3.0",
|
||||
"mpmath>=1.3",
|
||||
"matplotlib>=3.8",
|
||||
"lifelines>=0.28", # the recurrence analysis' penalised Cox model (`models.cama.recurrence`)
|
||||
]
|
||||
# The population curves of a CaMa training run (`models.cama.survival.population`): the fractional Weibull's series.
|
||||
survival-curves = [
|
||||
@@ -67,6 +68,7 @@ dev = [
|
||||
"scipy>=1.11",
|
||||
"statsmodels>=0.14",
|
||||
"pgmpy>=1.0",
|
||||
"lifelines>=0.28",
|
||||
"networkx>=3.0",
|
||||
"mpmath>=1.3",
|
||||
"matplotlib>=3.8",
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""CaMa's recurrence analysis (`models.cama.recurrence`): the two external cohorts as Luis's preparation reads them, the whole
|
||||
dataflow over small synthetic cohorts with the same columns (the figures of the scenarios, the tables, the routines the registry
|
||||
asks for and the saved model), and the model's prediction. Fixtures: `files`, METABRIC- and SCAN-B-shaped files of 700 patients
|
||||
each whose recurrence depends on grade, size and estrogen receptor, in a temporary folder.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cama.recurrence import prep
|
||||
from models.cama.recurrence.model import RecurrenceModel
|
||||
from models.cama.recurrence.source import PACKAGE_DATA, ExternalCohorts
|
||||
from models.dags.training import Scenario, dataflow
|
||||
|
||||
N = 700
|
||||
|
||||
|
||||
def _risk(rng, grade, size, er_positive):
|
||||
return 0.012 * np.exp(0.8 * (grade - 2) + 0.5 * (size > 30) - 0.5 * er_positive)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def files(tmp_path_factory) -> Path:
|
||||
"""Two files shaped like METABRIC's TSV and SCAN-B's metadata, recurrence exponential in months and faster with a high grade,
|
||||
a large tumor and no estrogen receptor; 10 % of the SCAN-B rows are men, which the preparation leaves out."""
|
||||
rng = np.random.default_rng(5)
|
||||
folder = tmp_path_factory.mktemp("externas")
|
||||
grade = rng.choice([1, 2, 3], N, p=[0.2, 0.45, 0.35])
|
||||
size = rng.gamma(4, 7, N)
|
||||
er = rng.random(N) < 0.7
|
||||
months = rng.exponential(1 / _risk(rng, grade, size, er))
|
||||
followed = np.minimum(months, rng.uniform(30, 150, N))
|
||||
event = months <= followed
|
||||
common = lambda: rng.choice(["Positive", "Negative"], N, p=[0.5, 0.5])
|
||||
pd.DataFrame({
|
||||
"Patient ID": [f"M{i}" for i in range(N)], "Relapse Free Status": np.where(event, "1:Recurred", "0:Not Recurred"),
|
||||
"Relapse Free Status (Months)": followed, "Age at Diagnosis": rng.normal(60, 12, N).clip(25, 90), "Tumor Size": size,
|
||||
"Lymph nodes examined positive": rng.integers(0, 9, N), "Neoplasm Histologic Grade": grade.astype(float),
|
||||
"Mutation Count": rng.integers(1, 12, N), "ER Status": np.where(er, "Positive", "Negative"), "PR Status": common(),
|
||||
"HER2 Status": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
|
||||
"Pam50 + Claudin-low subtype": rng.choice(["LumA", "LumB", "Basal", "Her2"], N), "Cancer Type Detailed": rng.choice(["Ductal", "Lobular"], N),
|
||||
"Cellularity": rng.choice(["High", "Moderate", "Low"], N), "Inferred Menopausal State": rng.choice(["Post", "Pre"], N),
|
||||
"Integrative Cluster": rng.choice(list("12345"), N), "Primary Tumor Laterality": rng.choice(["Left", "Right"], N),
|
||||
"Type of Breast Surgery": rng.choice(["MASTECTOMY", "BREAST CONSERVING"], N), "Chemotherapy": rng.choice(["YES", "NO"], N),
|
||||
"Radio Therapy": rng.choice(["YES", "NO"], N), "Hormone Therapy": rng.choice(["YES", "NO"], N),
|
||||
}).to_csv(folder / prep.FILES["metabric"], sep="\t", index=False)
|
||||
days = followed * prep.DAYS_PER_MONTH
|
||||
pd.DataFrame({
|
||||
"PatientName": [f"S{i}" for i in range(N)], "Gender": np.where(rng.random(N) < 0.1, "M", "F"), "RFI_event": event.astype(int),
|
||||
"RFI_days": days, "OS_event": rng.integers(0, 2, N), "Age_5year_bin": rng.choice([42, 47, 52, 57, 62, 67, 72, 77], N),
|
||||
"TumorSize_mm": size, "NodeMetSpec": rng.choice(["NodeNegative", "1to3", "4toX"], N), "NHG": np.array(["Grade1", "Grade2", "Grade3"])[grade - 1],
|
||||
"ER": np.where(er, "Positive", "Negative"), "PR": common(), "HER2": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
|
||||
"Ki67": rng.choice(["High", "Low"], N), "ClinicalSubtype": rng.choice(["Luminal A", "Basal-like", "Luminal B HER2-"], N),
|
||||
"Histology": rng.choice(["Ductal", "Lobular"], N), "MenopauseStatus_bin": rng.choice(["Post", "Pre"], N), "Laterality": rng.choice(["Left", "Right"], N),
|
||||
"tnm_ClinicalStage": rng.choice(["I", "II", "III"], N), "SurgeryType": rng.choice(["Mastectomy", "Lumpectomy"], N),
|
||||
"Chemotherapy": rng.choice(["Yes", "No"], N), "Radiation": rng.choice(["Yes", "No"], N), "Endocrine": rng.choice(["Yes", "No"], N),
|
||||
"AntiHER2": rng.choice(["Yes", "No"], N),
|
||||
}).to_csv(folder / prep.FILES["scanb"], sep="\t", index=False)
|
||||
return folder
|
||||
|
||||
|
||||
def test_the_real_cohorts_are_read_as_the_preparation_scripts_read_them():
|
||||
"""Pins down: METABRIC gives 2,380 patients with time and status of recurrence (964 recurrences) and SCAN-B 8,847 women, with
|
||||
the covariates as categories (the unknowns one more) and a redundant covariate dropped from each. Fails if a column is read
|
||||
differently, a patient with no follow-up is kept, or the collinearity rule drops other covariates."""
|
||||
metabric = prep.prepare_metabric(str(PACKAGE_DATA / prep.FILES["metabric"]), 0.80)
|
||||
scanb = prep.prepare_scanb(str(PACKAGE_DATA / prep.FILES["scanb"]), 0.80)
|
||||
|
||||
assert (len(metabric.cohort), int(metabric.cohort["evento"].sum())) == (2380, 964)
|
||||
assert len(scanb.cohort) == 8847 and "Gender" not in scanb.cohort
|
||||
assert metabric.eliminated == ["HER2"] and "HER2" not in metabric.covariates
|
||||
assert set(scanb.eliminated) == {"Receptor_estrogeno", "HER2", "Receptor_progesterona"}
|
||||
assert set(metabric.cohort["Edad"]) <= {"<45", "45-59", "60-74", "75+", "Desconocido"}
|
||||
assert metabric.treatment == ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
|
||||
|
||||
|
||||
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(files):
|
||||
"""Pins down: the dataflow over small cohorts gives a figure for each scenario with enough recurrences (the Kaplan-Meier with
|
||||
its band, both Weibull and the combined recurrence-free probability at each horizon with its interval), the tables behind
|
||||
them, the five routines the registry asks for and a model whose probabilities are in [0, 1]. Fails if a stage stops
|
||||
feeding the next, the figures lose a curve or a routine is missing."""
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
config = {"recurrence": {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2,
|
||||
"n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}}
|
||||
dr = dataflow(*scenario.modules, config=config)
|
||||
|
||||
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"])
|
||||
|
||||
figures = r["population"]["recurrencia"]["escenarios"]
|
||||
assert figures and {f["cohorte"] for f in figures} <= {"metabric", "scanb"}
|
||||
one = figures[0]
|
||||
assert set(one) >= {"escenario", "condiciones", "n", "recaidas", "km", "weibull", "weibull_fractional", "points"}
|
||||
comb = one["points"]["COMB"]
|
||||
assert len(comb["S"]) == 2 and all(lo <= s <= hi + 1e-9 for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
|
||||
assert len(one["km"]["S"]) == len(one["km"]["low"]) == one["observado_hasta"] + 1
|
||||
assert {"auc", "factores_riesgo", "calculadora", "escenarios_resumen"} <= set(r["population"]["recurrencia_desarrollo"]["tablas"])
|
||||
assert set(r["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
|
||||
assert r["metrics"] and all(isinstance(v, float) for v in r["metrics"].values())
|
||||
assert len(r["prepared"]["scanb"].cohort) < N # the men are left out
|
||||
model: RecurrenceModel = r["fitted_model"]
|
||||
p = model.predict_proba(r["prepared"]["metabric"].cohort.head(50))
|
||||
assert p.shape == (50, 2) and ((p >= 0) & (p <= 1)).all()
|
||||
|
||||
|
||||
def test_the_external_cohorts_are_the_versions_reference_and_the_files_are_hashed(files):
|
||||
"""Pins down: the reference the version is traced to is the hash of the two files, as a reference source and not a platform
|
||||
build, and a different file is a different reference. Fails if a change in the data does not change the reference (a retrain
|
||||
would then be skipped) or the version cannot be promoted for want of a cohort link."""
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
|
||||
from models.io.registry import REFERENCE_SOURCE
|
||||
|
||||
source = ExternalCohorts(files)
|
||||
before = source.reference()[COHORT_BUILD_TAG]
|
||||
(files / prep.FILES["metabric"]).write_text((files / prep.FILES["metabric"]).read_text() + "\n")
|
||||
|
||||
assert source.reference()[COHORT_SOURCE_TAG] == REFERENCE_SOURCE and len(before) == 64
|
||||
assert ExternalCohorts(files).reference()[COHORT_BUILD_TAG] != before
|
||||
|
||||
|
||||
def test_a_version_trains_registers_and_publishes_its_figures(files, mlflow_tracking):
|
||||
"""Pins down: training the scenario on its files registers a PROD version that carries the figures the dashboard draws
|
||||
(`analisis/recurrencia.json`), the tables, the routines, the metrics and the saved model, linked to the files' hash, so that
|
||||
only the human reports stand between it and promotion. Fails if the version cannot be saved, loses its figures, or fails a
|
||||
promotion check that is not the reports."""
|
||||
import dataclasses
|
||||
import json
|
||||
|
||||
from models.dags.training import train
|
||||
from models.io.registry import registry
|
||||
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
|
||||
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
|
||||
scenario = dataclasses.replace(scenario, config={"recurrence": tiny})
|
||||
|
||||
version = train(scenario, ExternalCohorts(files), "PROD")
|
||||
|
||||
_, figures = registry.artifact("cama", "recurrence", version, "analisis/recurrencia.json")
|
||||
_, tables = registry.artifact("cama", "recurrence", version, "analisis/recurrencia_desarrollo.json")
|
||||
assert json.loads(figures)["escenarios"] and "auc" in json.loads(tables)["tablas"]
|
||||
checks = {c.code: c.passed for c in registry.checks("cama", "recurrence", version)}
|
||||
assert all(checks[code] for code in ("ML-02", "ML-03", "ML-01a", "ML-01b"))
|
||||
assert not checks["MLD-01b"] and not checks["MLD-03"] # the reports are the human gate
|
||||
|
||||
|
||||
def test_the_cli_trains_and_leaves_the_version_waiting_for_its_reports(files, mlflow_tracking, monkeypatch, capsys):
|
||||
"""Pins down: `models run cama recurrence --train --promote` (what a governance job runs) trains the version, says "trained", then
|
||||
refuses to promote it for want of its reports with the message the job reads ("not promoted, missing") and exit code 1; run
|
||||
again it finds the version already trained. Fails if the entry point cannot run (a missing import), trains twice, or
|
||||
promotes without the human reports."""
|
||||
import argparse
|
||||
import dataclasses
|
||||
|
||||
from models.cama.recurrence.steps import run_steps
|
||||
|
||||
scenario = Scenario.load("cama", "recurrence")
|
||||
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
|
||||
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
|
||||
monkeypatch.setattr(Scenario, "load", classmethod(lambda cls, domain, name: dataclasses.replace(scenario, config={"recurrence": tiny})))
|
||||
args = argparse.Namespace(export=False, estimate=False, store=False, version=None, train=True, promote=True, environment="prod",
|
||||
domain="cama", scenario="recurrence")
|
||||
|
||||
first = run_steps(args)
|
||||
out = capsys.readouterr()
|
||||
second = run_steps(args)
|
||||
again = capsys.readouterr()
|
||||
|
||||
assert first == 1 and "trained: version 1" in out.out and "not promoted, missing" in out.err
|
||||
assert second == 1 and "already trained: version 1" in again.out
|
||||
@@ -9,6 +9,7 @@ import pytest
|
||||
|
||||
from models.cama.seer_survival import (balancing_stats, categorization_stats as cs, fractional_weibull as fw, hbn,
|
||||
lr_selection, pipeline, risk_factor_stats as rf, survival_models as sm)
|
||||
from models.cama.seer_survival import risk_factors, scenarios
|
||||
from models.cama.seer_survival.settings import load
|
||||
|
||||
|
||||
@@ -20,7 +21,7 @@ def test_every_stage_has_its_settings():
|
||||
assert "Biología + tratamiento" in {s.categorization.age_final}
|
||||
assert set(s.categorization.proposals) >= {"P1_actual", "P6_clinico_fijo", "P7_cuantiles"}
|
||||
assert s.modeling.canonical_map["Age_group"] == "Edad"
|
||||
assert len(s.survival.subgroups) == 13 and s.survival.combine_active and s.survival.months_max == 24
|
||||
assert len(scenarios.SCENARIOS) == 13 and s.survival.combine_active and s.survival.months_max == 24
|
||||
assert s.risk_factors.treatment == ("Tratamiento_quirurgico", "Radioterapia", "Quimioterapia")
|
||||
|
||||
|
||||
@@ -264,3 +265,37 @@ def test_treatment_associations_are_none_when_no_treatment_variable_varies():
|
||||
follow = risk_factors.FollowUp(death=pd.Series(rng.integers(0, 2, n)), months=pd.Series(rng.uniform(1, 20, n)),
|
||||
event=pd.Series(rng.integers(0, 2, n)))
|
||||
assert risk_factors.risk_treatment_associations(data, follow, ["Grado"], ["Radioterapia"], load().risk_factors) is None
|
||||
|
||||
|
||||
def test_a_scenario_holds_the_patients_who_meet_every_condition_and_none_without_the_column():
|
||||
"""Pins down: a scenario's mask is the patients who meet all its conditions over the raw columns (age from the age column,
|
||||
stage, subtype and surgery by keyword), and a cohort without a column has nobody in the scenarios that need it. Fails if
|
||||
a condition is dropped, an age edge moves, or a missing column makes a scenario include everyone."""
|
||||
raw = pd.DataFrame({"Age recode": ["30-34 years", "60-64 years", "75-79 years", "60-64 years"],
|
||||
"Stage": ["IIA", "IIIB", "IV", "I"], "Subtype (HER2+)": ["HER2+", "HER2+", "HER2-", "HER2+"]})
|
||||
found = scenarios.masks(raw)
|
||||
|
||||
assert found["< 45 años"].tolist() == [True, False, False, False]
|
||||
assert found["≥ 75 años"].tolist() == [False, False, True, False]
|
||||
assert found["Estadio IV"].tolist() == [False, False, True, False]
|
||||
assert found["HER2+ · ≥60 años · estadio III–IV (Alto)"].tolist() == [False, True, False, False]
|
||||
assert not found["HER2− · estadio 0–II · cirugía conservadora"].any() # no surgery column: nobody
|
||||
assert not scenarios.masks(raw[["Age recode"]])["Estadio I"].any() # no stage column: nobody
|
||||
|
||||
|
||||
def test_the_risk_factors_of_a_scenario_are_the_classified_categories_most_of_it_shares():
|
||||
"""Pins down: a classified risk factor that nearly all of a scenario has is listed as defining it, a protector that most
|
||||
has as most of it, and one that few have is left out. Fails if the shares are taken over the cohort instead of the
|
||||
scenario, or a category under the presence floor is listed."""
|
||||
table = pd.DataFrame({"variable": ["Grado", "Grado", "Subtipo"], "categoria": ["G3", "G1", "A"], "clasificacion": ["riesgo robusto", "protector sugerente", "riesgo robusto"],
|
||||
"OR_muerte": [2.0, 0.5, 3.0], "IC95_inf": [1.2, 0.3, 1.1], "IC95_sup": [3.0, 0.9, 5.0], "delta_S18": [-0.1, 0.05, -0.2]})
|
||||
data = pd.DataFrame({"Grado": ["G3"] * 10 + ["G1"] * 6 + ["G3"] * 4, "Subtipo": ["A"] * 1 + ["B"] * 19})
|
||||
mask = np.array([True] * 10 + [False] * 10) # the scenario: the first ten, all grade 3 and one of subtype A
|
||||
classification = risk_factors.Classification(table, ["c1"])
|
||||
|
||||
found = risk_factors.risk_scenario_factors(classification, None, data, {"Grado 3": mask})
|
||||
|
||||
row = found.summary.iloc[0]
|
||||
assert "Grado=G3" in row["riesgo_definitorios"] and row["n_factores_riesgo_incluidos"] == 1
|
||||
assert set(found.details["variable"]) == {"Grado", "Subtipo"} # subtype A is 10 % of the scenario: present
|
||||
assert found.details[found.details["categoria"] == "G1"].empty # no scenario member has G1
|
||||
|
||||
+180
-2
@@ -292,7 +292,7 @@ def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking)
|
||||
def development_record(cohort_frame):
|
||||
"""The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget."""
|
||||
config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
|
||||
"proposals_max_seconds": 20, "restarts": 1}}
|
||||
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}}
|
||||
dr = dataflow(*SCENARIO.modules, config=config)
|
||||
return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"]
|
||||
|
||||
@@ -326,7 +326,7 @@ def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_coh
|
||||
"ki67_group": rng.choice(["<14", "14-19", "≥20"], n)})
|
||||
members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24)
|
||||
settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
|
||||
"proposals_max_seconds": 20, "restarts": 1}
|
||||
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}
|
||||
|
||||
r = dev.development(members, settings)["desarrollo"]
|
||||
|
||||
@@ -335,3 +335,181 @@ def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_coh
|
||||
arcs = r["tablas"]["hbn_arcos"]
|
||||
assert arcs["columnas"] == list(arcs["filas"][0]) and len(arcs["columnas"]) > 1
|
||||
assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())
|
||||
|
||||
|
||||
def _stage_five_table(csv_path, survival):
|
||||
"""The table of the SEER pipeline's stage 5 for the main curve (`sv_table`): its own nodes over a CSV of the cohort."""
|
||||
from hamilton import driver
|
||||
|
||||
from models.cama.seer_survival import survival_curves
|
||||
|
||||
dr = driver.Builder().with_modules(survival_curves).build()
|
||||
return dr.execute(["sv_table"], inputs={"depurated_csv": str(csv_path), "survival": survival})["sv_table"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def members_frame(cohort_frame):
|
||||
"""The 240 indexed members, labelled (covariates, follow-up, death), as the figure's nodes take them."""
|
||||
return dataflow(*SCENARIO.modules, config=SCENARIO.config).execute(
|
||||
["labelled_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["labelled_members"]
|
||||
|
||||
|
||||
def test_the_published_figure_is_the_seer_pipelines_stage_five_on_the_same_members(members_frame, tmp_path):
|
||||
"""Pins down: the Kaplan-Meier curve, the adjusted curve, the stacking weights, the points of LR, HBN and their
|
||||
combination and their bootstrap interval in the published record are those that `models.cama.seer_survival`'s own stage 5
|
||||
(`run_survival`, on a CSV of the same members and the same settings) gives. Fails if the record's code path stops being
|
||||
the pipeline's, which would make the dashboard's figure another model's."""
|
||||
import dataclasses
|
||||
|
||||
from models.cama.survival import estimator
|
||||
|
||||
survival = {**CONFIG["survival"], "n_boot": 6, "ks_max_seconds": 5}
|
||||
config = {**CONFIG, "survival": survival}
|
||||
ours = dataflow(*SCENARIO.modules, config=config).execute(
|
||||
["population_curves"], inputs={"source_cohort": pd.DataFrame(), "cohort_lineage": {}},
|
||||
overrides={"labelled_members": members_frame})["population_curves"]["curvas"]
|
||||
|
||||
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
|
||||
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
|
||||
for name in estimator.FEATURES:
|
||||
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
|
||||
csv.to_csv(tmp_path / "depurado.csv", index=False)
|
||||
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
|
||||
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
|
||||
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
|
||||
|
||||
for model in ("LR", "HBN", "COMB"):
|
||||
rows = theirs[theirs["modelo"] == model]
|
||||
assert ours["points"][model]["S"] == pytest.approx(rows["S"].tolist(), abs=1e-9)
|
||||
assert ours["points"][model]["low"] == pytest.approx(rows["IC_inf"].tolist(), abs=1e-9)
|
||||
assert ours["points"][model]["high"] == pytest.approx(rows["IC_sup"].tolist(), abs=1e-9)
|
||||
km = theirs[theirs["modelo"] == "COMB"]
|
||||
assert [ours["km"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_crudo"].tolist(), abs=1e-9)
|
||||
assert [ours["km_adjusted"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_ajustada"].tolist(), abs=1e-9)
|
||||
|
||||
|
||||
def test_the_production_model_predicts_what_the_pipelines_points_say(members_frame, tmp_path):
|
||||
"""Pins down: the `IntervalSurvival` a version in production is (the model that scores each patient) gives, averaged over
|
||||
the members it was fitted on, the survival at each horizon that the pipeline's stage 5 gives for LR, HBN and their
|
||||
combination, exactly (the same data, the same settings). Fails if the model that scores patients drifts from the model whose
|
||||
figure is published."""
|
||||
import dataclasses
|
||||
|
||||
from models.cama.survival import estimator
|
||||
from models.cama.survival.estimator import IntervalSurvival
|
||||
|
||||
survival = {**CONFIG["survival"], "n_boot": 0}
|
||||
model = IntervalSurvival(survival, tuple(h / 12 for h in survival["horizons"])).fit(
|
||||
members_frame[estimator.FEATURES], members_frame[["months", "event"]])
|
||||
mean_combined = model.survival_proba(members_frame[estimator.FEATURES]).mean(axis=0)
|
||||
|
||||
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
|
||||
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
|
||||
for name in estimator.FEATURES:
|
||||
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
|
||||
csv.to_csv(tmp_path / "depurado.csv", index=False)
|
||||
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
|
||||
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
|
||||
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
|
||||
|
||||
assert mean_combined == pytest.approx(theirs[theirs["modelo"] == "COMB"]["S"].tolist(), abs=1e-6)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def production_model(members_frame):
|
||||
"""A model fitted on the 240 members: what a version in production is when the dashboard scores a selection."""
|
||||
return IntervalSurvival(CONFIG["survival"], tuple(h / 12 for h in CONFIG["survival"]["horizons"])).fit(
|
||||
members_frame[FEATURES], members_frame[["months", "event"]])
|
||||
|
||||
|
||||
def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(members_frame, production_model, monkeypatch):
|
||||
"""Pins down: the record of a scenario is for its members only (their count and deaths), its points are the model's mean
|
||||
survival for them at the model's horizons with an interval around it, and nothing is refitted (the same scenario twice gives
|
||||
the same record). Fails if the scenario's mask is ignored, or the scenario changes the model's horizons."""
|
||||
from models.cama.survival import live
|
||||
|
||||
young = np.arange(len(members_frame)) < 120
|
||||
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Primeras 120": young})
|
||||
|
||||
everyone = live.curves(SCENARIO, production_model, members_frame, None)
|
||||
first = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
|
||||
again = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
|
||||
|
||||
assert everyone["n"] == len(members_frame) and everyone["escenario"] == "Toda la cohorte" and everyone["horizons_months"] == [6, 12, 18]
|
||||
assert first["n"] == 120 and first["escenario"] == "Primeras 120" and first["points"] == again["points"]
|
||||
comb = first["points"]["COMB"]
|
||||
assert all(lo <= s <= hi for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
|
||||
assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"])
|
||||
|
||||
|
||||
def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch):
|
||||
"""Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole
|
||||
cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no
|
||||
scenario is left with nothing."""
|
||||
from models.cama.survival import live
|
||||
|
||||
first, last = int(members_frame["pac_id"].iloc[0]), int(members_frame["pac_id"].iloc[-1])
|
||||
inside = np.arange(len(members_frame)) < 100
|
||||
tiny = np.arange(len(members_frame)) < 3
|
||||
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Grande": inside, "Diminuto": tiny})
|
||||
|
||||
assert live.patient_scenarios(members_frame, first) == ["Grande"] # in both; the tiny one has too few to draw
|
||||
assert live.patient_scenarios(members_frame, last) == ["Toda la cohorte"] # in neither
|
||||
with pytest.raises(live.QueryError):
|
||||
live.patient_scenarios(members_frame, 10**9)
|
||||
|
||||
|
||||
def test_the_scenarios_use_the_hospitals_age_and_subtype_and_none_that_needs_a_stage(members_frame):
|
||||
"""Pins down: the scenario masks use the age in years and a subtype derived from the receptors (hormone receptors and
|
||||
HER2 3+ / 0-1+), and a scenario that needs the stage or the surgery, which the hospital does not report, has no member.
|
||||
Fails if a stage scenario includes everyone, or the subtype ignores the receptors."""
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.survival import live
|
||||
|
||||
n = len(members_frame)
|
||||
frame = members_frame.assign(er=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "POSITIVO"], n),
|
||||
pr=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "NEGATIVO"], n),
|
||||
her2=np.resize(["H1", "H3", "H0", "H2"], n))
|
||||
found = live.molecular_subtype(frame).iloc[:4].tolist()
|
||||
masks = live.scenario_masks(frame)
|
||||
|
||||
assert found == ["HR+/HER2-", "HR-/HER2+", "HR-/HER2-", "Desconocido"] # HER2 2+ is equivocal: unknown
|
||||
assert set(masks) == set(scenarios.SCENARIOS)
|
||||
assert not masks["Estadio IV"].any() and not masks["Triple negativo (HR−/HER2−) · estadio 0–II"].any()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["No existe", "Estadio IV"])
|
||||
def test_a_scenario_that_cannot_be_answered_says_why(members_frame, production_model, name):
|
||||
"""Pins down: an unknown scenario and one with too few members to say anything (every stage scenario, with the stage not
|
||||
reported) are each a `QueryError` with a message. Fails if either runs and draws a meaningless figure or fails with an
|
||||
unreadable error."""
|
||||
from models.cama.survival import live
|
||||
|
||||
with pytest.raises(live.QueryError):
|
||||
live.curves(SCENARIO, production_model, members_frame, name)
|
||||
|
||||
|
||||
def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():
|
||||
"""Pins down: the month-by-month survival equals the model's at each horizon, starts at 1, never rises, and goes on past
|
||||
the last horizon at the last interval's rate. Fails if the interpolation misses a horizon or the curve can go up."""
|
||||
from models.cama.survival import live
|
||||
|
||||
curve = live.monthly(np.array([[0.9, 0.8, 0.6]]), [6, 12, 18], 24)[0]
|
||||
|
||||
assert curve[0] == 1.0 and curve[6] == pytest.approx(0.9) and curve[12] == pytest.approx(0.8) and curve[18] == pytest.approx(0.6)
|
||||
assert (np.diff(curve) <= 1e-12).all() and curve[24] < curve[18]
|
||||
|
||||
|
||||
def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(members_frame, production_model):
|
||||
"""Pins down: the fitted state of a model, put in an object of a class without the current methods (what loading a saved
|
||||
model from before a code change gives), scores the same as the model itself once rehydrated. Fails if the live figure
|
||||
depends on the class a version was saved with, which makes every older version unusable after a change."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from models.cama.survival import live
|
||||
|
||||
stale = SimpleNamespace(**production_model.__dict__)
|
||||
again = live.rehydrate(stale).component_survival(members_frame[FEATURES])
|
||||
|
||||
for name, expected in production_model.component_survival(members_frame[FEATURES]).items():
|
||||
assert again[name] == pytest.approx(expected)
|
||||
|
||||
Reference in New Issue
Block a user