Files
models/models/factors.py
T

179 lines
8.0 KiB
Python

"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models.
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes
1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least
FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its
Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's
direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three
criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get
their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations,
not effects. Each clinical scenario then lists the classified factors nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import false_discovery_control
from models.curves import life_table
ALPHA = 0.05
FREQ_MIN = 0.80
Z = 1.96
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
ORDER = {
"riesgo robusto": 0,
"protector robusto": 1,
"riesgo sugerente": 2,
"protector sugerente": 3,
"no concluyente": 4,
}
UNKNOWN_CLASS = "no aplica (categoria desconocida)"
# Scenario presence: the share of the scenario's patients in the category.
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria")
def variable_of(term: str, covariates: list[str]) -> str:
"""The covariate a dummy belongs to (the longest name it starts with)."""
found = [c for c in covariates if term.startswith(c + "_")]
return max(found, key=len) if found else term
def km_at(months, event, horizon) -> tuple[float, float]:
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
d, _, n = life_table(months, event)
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
last = min(horizon, len(d) - 1) + 1
S = float(np.prod(q[:last]))
return S, S * float(np.sqrt(np.sum(v[:last])))
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
"""Logistic GLM on every category but each covariate's reference (constant and
duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p."""
X = pd.get_dummies(data[variables]).astype(float)
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = np.exp(m.conf_int().loc[X.columns])
return pd.DataFrame(
{
"termino": X.columns,
name: np.exp(m.params[X.columns].to_numpy()),
"IC95_inf": ci[0].to_numpy(),
"IC95_sup": ci[1].to_numpy(),
"p": m.pvalues[X.columns].to_numpy(),
}
)
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
survival columns)."""
table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
]
table["referencia"] = table["variable"].map(reference)
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
category, ref, delta_name = names
rows = []
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
sa, ea = km_at(months[a], event[a], horizon)
sb, eb = km_at(months[b], event[b], horizon)
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
rows.append({
"n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
"delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
}) # fmt: skip
return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
"delta_IC95_inf", "delta_IC95_sup"])],
axis=1) # fmt: skip
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
for the criteria `evaluated`."""
risk = tab[or_name] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1))
tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1)
robust = min(3, len(evaluated))
tab["clasificacion"] = [
UNKNOWN_CLASS
if cat == unknown
else f"{d} robusto"
if c1 and k >= robust
else f"{d} sugerente"
if k >= 2
else "no concluyente"
for cat, d, c1, k in zip(
tab["categoria"],
tab["direccion"],
tab["c1_or"],
tab["criterios_cumplidos"],
strict=True,
)
]
return tab
def presence(share: float) -> str:
if share >= DEFINING:
return "definitoria"
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
def listing(part: pd.DataFrame) -> str:
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
`asociacion`."""
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join(
f"{v}={c} ({s}, {p:.0%})"
for v, c, s, p in zip(
part["variable"], part["categoria"], strength, part["share"], strict=True
)
)
def classified(factors: pd.DataFrame) -> pd.DataFrame:
"""The factors a scenario can list (classified ones and treatments), with `tipo_efecto`:
riesgo, protector or tratamiento."""
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
)
return found.assign(tipo_efecto=kind)
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
"""What one scenario's patients (`mask` over `frame`) have of the `classified` factors:
the listings by kind and presence, and how many risk factors describe it."""
share = [
float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True)
]
detail = found.assign(share=share, presence=[presence(s) for s in share])
row = {}
for k in ("riesgo", "protector", "tratamiento"):
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
row[f"{k}_{label}"] = listing(
detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)]
)
included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING)
row["n_factores_riesgo_incluidos"] = int(included.sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
return row