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.
This commit is contained in:
2026-12-01 16:55:32 -06:00
parent e42f6a34b2
commit 24534606f1
32 changed files with 88 additions and 760 deletions
+2 -47
View File
@@ -1,12 +1,3 @@
"""Per horizon, two models of recurrence by then: a logistic regression (LR) on the dummies a
stepwise selection keeps, and a Bayesian network (HBN) whose outcome's parents a greedy BDeu
search picks, predicting by its conditional probability table. Each is validated on a
stratified 70/30 split of the horizon's cohort (AUC) and on bootstrap resamples of it (each
replicate its own 70/30 split); a penalized Cox model's C-index rates the whole follow-up.
Resamples are drawn in order from one seeded generator and fitted in parallel, so every
replicate is the same however many workers run them."""
import warnings
from dataclasses import dataclass, field
@@ -25,27 +16,21 @@ from models.factors import variable_of
SEED = 42
TEST_SIZE = 0.3
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
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 # a Cox dummy needs this many patients on each side
COX_MIN_COUNT = 10
N_BOOTSTRAP = {"site": 40}
# ---------------------------------------------------------------- logistic regression
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
"""Dummies (each covariate's alphabetically first level is the reference), the
non-constant ones; a term is `{covariate}_{level}`."""
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"):
"""Maximum-likelihood logistic regression with an intercept, or None when it fails."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
@@ -56,8 +41,6 @@ def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
def stepwise(X: pd.DataFrame, y) -> list[str]:
"""Forward (the smallest Wald p < ALPHA_IN enters) then backward (the largest p >
ALPHA_OUT leaves) until nothing changes; the terms in the order they entered."""
included = []
for _ in range(MAX_STEPS):
changed, best, best_p = False, None, ALPHA_IN
@@ -81,8 +64,6 @@ def stepwise(X: pd.DataFrame, y) -> list[str]:
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
"""The terms selected on `train` (univariate prefilter, then stepwise) and the test
rows' predicted probabilities (the training rate when no term is selected)."""
X = encode(pd.concat([train, test]), covariates)
X_train = X.loc[train.index]
X_train = X_train.loc[:, X_train.nunique() > 1]
@@ -100,9 +81,6 @@ def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
return terms, m.predict(X_test).to_numpy()
# ---------------------------------------------------------------- Bayesian network
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
table = frame[covariates].astype(str)
table["outcome"] = frame["y"].astype(int).astype(str)
@@ -110,8 +88,6 @@ def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
"""Greedy: the covariate whose addition most raises the outcome's BDeu score, while
any does (up to MAX_PARENTS); the parents in the order chosen."""
score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS:
@@ -128,8 +104,6 @@ def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
"""P(recurrence | parents) for each configuration seen, smoothed by ESS / (2 q) per cell;
`q`, the number of configurations, defaults to the levels seen in `table`."""
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")
@@ -140,8 +114,6 @@ def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tu
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
"""The test rows' probabilities by the CPT of `train`; unseen configurations (or no
parents) get the training rate."""
rate = (train["outcome"] == "1").mean()
if not chosen:
return np.full(len(test), rate)
@@ -149,13 +121,8 @@ def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarra
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
# ---------------------------------------------------------------- one split, one cohort
@dataclass(frozen=True)
class Split:
"""The two models' selection and AUC on one 70/30 split."""
terms: list[str]
parents: list[str]
auc_lr: float
@@ -174,8 +141,6 @@ def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> S
def _replicate(frame, covariates, rows, b) -> Split | None:
"""Bootstrap replicate `b`: the split (seed SEED + b) of the resample `rows`; None when
any fit fails (the replicate is then not counted)."""
try:
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
except Exception:
@@ -183,8 +148,6 @@ def _replicate(frame, covariates, rows, b) -> Split | None:
def c_index(cohort: Cohort) -> float:
"""Harrell's C of a ridge-penalized Cox model on the whole follow-up, by a 70/30 split
stratified by event; dummies with fewer than COX_MIN_COUNT patients on a side are left out."""
time_event = ["tiempo_meses", "evento"]
X = pd.get_dummies(
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
@@ -205,9 +168,6 @@ def c_index(cohort: Cohort) -> float:
@dataclass
class Horizon:
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
covariate entered the LR and the HBN)."""
n: int
events: int
split: Split
@@ -218,7 +178,6 @@ class Horizon:
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:
"""Share of the replicates whose final LR has a term of each covariate."""
if not self.replicates:
return None
counts = {}
@@ -236,8 +195,6 @@ class CohortFit:
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
"""Every cohort's split fits, bootstrap replicates and C-index, in one pool of workers.
Each horizon's resamples come from a fresh generator seeded SEED."""
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():
@@ -268,8 +225,6 @@ def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, Co
def tables(fitted: CohortFit) -> dict[int, dict]:
"""What the saved model keeps per horizon: the split's LR terms refitted on the whole
horizon cohort, and the split's HBN parents with their CPT on it."""
found = {}
for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h)