Files
models/models/factors.py
T
Roberto Treviño 41508efeb6 ISSSTELEON models
2026-11-29 18:11:48 -06:00

187 lines
6.1 KiB
Python

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.8
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)"
DEFINING, MAJORITY, PRESENT = (0.95, 0.5, 0.1)
DESCRIBING = ("definitoria", "mayoritaria")
def variable_of(term: str, covariates: list[str]) -> str:
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]:
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:
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:
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,
}
)
return pd.concat(
[
table,
pd.DataFrame(
rows,
columns=[
"n_categoria",
category,
ref,
delta_name,
"delta_IC95_inf",
"delta_IC95_sup",
],
),
],
axis=1,
)
def classify(
tab: pd.DataFrame,
or_name: str,
delta_name: str,
unknown: str,
evaluated: tuple[str, ...] = CRITERIA,
) -> pd.DataFrame:
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:
strength = np.where(
part["tipo_efecto"] == "tratamiento",
"asociacion",
part["clasificacion"].str.split().str[-1],
)
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:
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:
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