Files
models/models/cama/recurrence/modeling.py
T
alberto 24534606f1 C1a: code only, no comments, no Markdown
Remove 212 Python docstrings and 118 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files.

Preserve the existing executable statements and lint pragmas. Use pass for class bodies that previously consisted of only a docstring.
2026-12-01 16:55:32 -06:00

249 lines
8.5 KiB
Python

import warnings
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.structure_score import BDeu
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
from models.factors import variable_of
SEED = 42
TEST_SIZE = 0.3
ESS = 10
MAX_PARENTS = 6
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
MAX_STEPS = 200
COX_PENALIZER = 0.05
COX_MIN_COUNT = 10
N_BOOTSTRAP = {"site": 40}
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
X = sm.add_constant(X, has_constant=has_constant)
return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def stepwise(X: pd.DataFrame, y) -> list[str]:
included = []
for _ in range(MAX_STEPS):
changed, best, best_p = False, None, ALPHA_IN
for c in X.columns:
if c in included:
continue
m = 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 and (m := logit(y, X[included])) is not None:
p = m.pvalues.drop("const")
if p.max() > ALPHA_OUT:
included.remove(p.idxmax())
changed = True
if not changed:
break
return included
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
X = encode(pd.concat([train, test]), covariates)
X_train = X.loc[train.index]
X_train = X_train.loc[:, X_train.nunique() > 1]
y = train["y"]
candidates = [
c
for c in X_train.columns
if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER
]
terms = stepwise(X_train[candidates], y) if candidates else []
if not terms:
return [], np.full(len(test), y.mean())
m = logit(y, X_train[terms])
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
return terms, m.predict(X_test).to_numpy()
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
table = frame[covariates].astype(str)
table["outcome"] = frame["y"].astype(int).astype(str)
return table
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS:
best, gain = None, 0.0
for c in [c for c in covariates if c not in chosen]:
g = score.local_score("outcome", (*chosen, c)) - current
if g > gain:
best, gain = c, g
if best is None:
break
chosen.append(best)
current += gain
return chosen
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
q = q or int(np.prod([table[p].nunique() for p in chosen]))
a = ESS / (2 * q)
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
return {
(k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
for k, r in counts.iterrows()
}
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
rate = (train["outcome"] == "1").mean()
if not chosen:
return np.full(len(test), rate)
table = cpt(train, chosen)
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
@dataclass(frozen=True)
class Split:
terms: list[str]
parents: list[str]
auc_lr: float
auc_hbn: float
def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split:
train, test = train_test_split(
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
)
terms, p_lr = lr(train, test, covariates)
bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
chosen = parents(bn_train, covariates)
p_hbn = hbn(bn_train, bn_test, chosen)
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
def _replicate(frame, covariates, rows, b) -> Split | None:
try:
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
except Exception:
return None
def c_index(cohort: Cohort) -> float:
time_event = ["tiempo_meses", "evento"]
X = pd.get_dummies(
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
).astype(float)
X = X.loc[:, X.nunique() > 1]
train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"])
n = len(train)
keep = [
c
for c in X.columns
if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT
]
cox = CoxPHFitter(penalizer=COX_PENALIZER)
cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5})
risk = cox.predict_partial_hazard(test[keep])
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
@dataclass
class Horizon:
n: int
events: int
split: Split
replicates: list[Split] = field(default_factory=list)
@property
def aucs(self) -> np.ndarray:
return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2)
def selection(self, covariates: list[str]) -> dict[str, float] | None:
if not self.replicates:
return None
counts = {}
for r in self.replicates:
for v in {variable_of(t, covariates) for t in r.terms}:
counts[v] = counts.get(v, 0) + 1
return {v: k / len(self.replicates) for v, k in counts.items()}
@dataclass
class CohortFit:
cohort: Cohort
c_index: float
horizons: dict[int, Horizon]
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS}
tasks = []
for (s, h), frame in frames.items():
rng = np.random.default_rng(SEED)
rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))]
tasks += [
((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b))
for b, r in enumerate(rows)
]
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks))
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
out = {}
for s, cohort in cohorts.items():
horizons = {}
for h in HORIZONS:
frame = frames[(s, h)]
reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
horizons[h] = Horizon(
len(frame),
int(frame["y"].sum()),
results[(s, h, "split")],
[r for r in reps if r is not None],
)
out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
return out
def tables(fitted: CohortFit) -> dict[int, dict]:
found = {}
for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h)
covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
prior = float(frame["y"].mean())
entry = {
"lr_prior": prior,
"lr_terms": terms,
"lr_constant": 0.0,
"lr_coefficients": [],
"hbn_parents": chosen,
"hbn_prior": prior,
"hbn_cpt": {},
}
if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None:
entry["lr_constant"] = float(m.params["const"])
entry["lr_coefficients"] = [float(m.params[t]) for t in terms]
if chosen:
entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen)
found[h] = entry
return found