136 lines
7.2 KiB
Python
136 lines
7.2 KiB
Python
"""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)
|