From cc5cfd1792782b74cb9e07e56244b79dafd7a681 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 4 Dec 2026 09:12:15 -0600 Subject: [PATCH] Limpiar los avisos de estilo --- .../bayes_development/prevalence_gibbs.py | 175 +++++++++++++----- models/cacu/development_firth.py | 4 +- models/cacu/development_selection.py | 137 +++++++++----- models/cacu/features.py | 14 +- models/cacu/pim.py | 28 ++- models/cacu/reports.py | 33 ++-- models/cacu/specs.py | 10 +- models/definitions.py | 15 +- models/jobs.py | 3 +- models/survival.py | 35 +++- tests/test_cacu_bayes_prevalence.py | 58 ++++-- tests/test_cacu_development_selection.py | 85 +++++---- tests/test_cacu_hpv_required.py | 5 +- tests/test_cacu_models.py | 11 +- tests/test_cacu_prediction_inputs.py | 20 +- tests/test_pim_variance_availability.py | 13 +- 16 files changed, 440 insertions(+), 206 deletions(-) diff --git a/models/cacu/bayes_development/prevalence_gibbs.py b/models/cacu/bayes_development/prevalence_gibbs.py index 9b9ec74..6e725b2 100644 --- a/models/cacu/bayes_development/prevalence_gibbs.py +++ b/models/cacu/bayes_development/prevalence_gibbs.py @@ -1,32 +1,43 @@ -"""The prevalence part of Klausch's BayesPIM as a conjugate Gibbs sampler, for cross-sectional screening data. +"""The prevalence part of Klausch's BayesPIM as a conjugate Gibbs sampler, for cross-sectional\ + screening data. -Klausch, Lissenberg-Witte and Coupé (2026), Stat Med 45(8-9):e70433, doi:10.1002/sim.70433. Their R package needs -follow-up times to initialise the incidence part, so it cannot fit a sample with one test per woman (2026 sample of +Klausch, Lissenberg-Witte and Coupé (2026), Stat Med 45(8-9):e70433, doi:10.1002/sim.70433.\ + Their R package needs +follow-up times to initialise the incidence part, so it cannot fit a sample with one test per\ + woman (2026 sample of Modelo-cacu, issue 0120). With no follow-up only the prevalence part is informed, and it is this: - z_i ~ N(x_i beta, 1), g_i = 1[z_i > 0] true state at the test (probit, Albert and Chib 1993) + z_i ~ N(x_i beta, 1), g_i = 1[z_i > 0] true state at the test (probit, Albert\ + and Chib 1993) y_i | g_i, r_i = 1 ~ Bernoulli(kappa g_i) the test: specificity 1, sensitivity kappa r_i = 0 no test (or no result): g_i is only augmented Every full conditional is a standard distribution, so each step is an exact draw: g (Bernoulli, z integrated out), z (truncated normal), beta (normal), kappa (beta). -The extension proposed in chapter 19 (selection of who gets the test, the arc g -> r) adds a second probit, +The extension proposed in chapter 19 (selection of who gets the test, the arc g -> r) adds a\ + second probit, w_i ~ N(u_i gamma + gamma_g arc_i g_i, 1), r_i = 1[w_i > 0] -with arc_i = 1 where the hospital protocol does not refer the woman's cell (referral there is clinical suspicion or -persistence). It keeps conjugacy: w is another truncated normal, (gamma, gamma_g) another normal regression with the -augmented g as a column, and g gains the factor P(r_i | g = 1) / P(r_i | g = 0). With one test per woman gamma_g is +with arc_i = 1 where the hospital protocol does not refer the woman's cell (referral there is\ + clinical suspicion or +persistence). It keeps conjugacy: w is another truncated normal, (gamma, gamma_g) another\ + normal regression with the +augmented g as a column, and g gains the factor P(r_i | g = 1) / P(r_i | g = 0). With one test\ + per woman gamma_g is weakly identified and needs an informative prior. """ + from __future__ import annotations import numpy as np from scipy.stats import norm, truncnorm -def normal_posterior(X: np.ndarray, z: np.ndarray, b0: np.ndarray, B0inv: np.ndarray) -> tuple[np.ndarray, np.ndarray]: +def normal_posterior( + X: np.ndarray, z: np.ndarray, b0: np.ndarray, B0inv: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: """beta | z for a regression with unit-variance errors and prior N(b0, B0): N(m, V) with V = (X'X + B0^-1)^-1 and m = V (X'z + B0^-1 b0). Returns m and the Cholesky factor of V.""" V = np.linalg.inv(X.T @ X + B0inv) @@ -42,44 +53,69 @@ def draw_latent(mean: np.ndarray, positive: np.ndarray, rng: np.random.Generator def prob_g(p: np.ndarray, r: np.ndarray, y: np.ndarray, kappa: float, odds_r=1.0) -> np.ndarray: - """P(g_i = 1 | beta, kappa, data) with z_i integrated out: prior odds p / (1 - p) times the likelihood ratio of + """P(g_i = 1 | beta, kappa, data) with z_i integrated out: prior odds p / (1 - p) times\ + the likelihood ratio of what was observed of woman i, P(data | g = 1) / P(data | g = 0): * tested positive: infinite (specificity 1: only a diseased woman tests positive), so g = 1; * tested negative: (1 - kappa) / 1 (a diseased woman is missed with probability 1 - kappa); * untested: 1 (nothing observed). - `odds_r` is the extra ratio P(r_i | g = 1) / P(r_i | g = 0) of the referral arc; 1 without it.""" + `odds_r` is the extra ratio P(r_i | g = 1) / P(r_i | g = 0) of the referral arc; 1 without\ + it.""" lr = np.where(r == 1, np.where(y == 1, np.inf, 1.0 - kappa), 1.0) * odds_r odds = p / (1.0 - p) * lr - with np.errstate(invalid="ignore"): # inf / inf in the branch that np.where drops + with np.errstate(invalid="ignore"): # inf / inf in the branch that np.where drops return np.where(np.isinf(odds), 1.0, odds / (1.0 + odds)) -def draw_kappa(g: np.ndarray, r: np.ndarray, y: np.ndarray, a: float, b: float, rng: np.random.Generator) -> float: - """kappa | g, y ~ Beta(a + detected, b + missed), counting only tested women whose (augmented) g is 1.""" +def draw_kappa( + g: np.ndarray, r: np.ndarray, y: np.ndarray, a: float, b: float, rng: np.random.Generator +) -> float: + """kappa | g, y ~ Beta(a + detected, b + missed), counting only tested women whose\ + (augmented) g is 1.""" diseased = (r == 1) & (g == 1) detected = int((y[diseased] == 1).sum()) return rng.beta(a + detected, b + int(diseased.sum()) - detected) def referral_odds(eta_r: np.ndarray, gamma_g: float, arc: np.ndarray, r: np.ndarray) -> np.ndarray: - """The arc g -> r: P(r_i | g_i = 1) / P(r_i | g_i = 0) when r_i = 1[w_i > 0], w_i ~ N(eta_r_i + gamma_g arc_i g_i, 1). - For a tested woman it is Phi(eta + gamma_g) / Phi(eta); for an untested one, the same with the survival - function. Where arc_i = 0 (the protocol refers her cell) both are equal and the ratio is 1. Logs for stability.""" + """The arc g -> r: P(r_i | g_i = 1) / P(r_i | g_i = 0) when r_i = 1[w_i > 0], w_i ~\ + N(eta_r_i + gamma_g arc_i g_i, 1). + For a tested woman it is Phi(eta + gamma_g) / Phi(eta); for an untested one, the same with\ + the survival + function. Where arc_i = 0 (the protocol refers her cell) both are equal and the ratio is\ + 1. Logs for stability.""" shifted = eta_r + gamma_g * arc log1 = np.where(r == 1, norm.logcdf(shifted), norm.logsf(shifted)) log0 = np.where(r == 1, norm.logcdf(eta_r), norm.logsf(eta_r)) return np.exp(log1 - log0) -def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None, - iterations: int = 4000, warmup: int = 2000, seed: int = 0) -> dict: - """One chain. X carries the intercept column; r = 1 if the test was done with a result, y its result (ignored - where r = 0). Prior beta ~ N(b0, B0), kappa ~ Beta(kappa_ab). Returns the kept draws of beta and kappa. +def gibbs( + X: np.ndarray, + r, + y, + b0, + B0, + kappa_ab=(1.0, 1.0), + U=None, + arc=None, + d0=None, + D0=None, + iterations: int = 4000, + warmup: int = 2000, + seed: int = 0, +) -> dict: + """One chain. X carries the intercept column; r = 1 if the test was done with a result, y\ + its result (ignored + where r = 0). Prior beta ~ N(b0, B0), kappa ~ Beta(kappa_ab). Returns the kept draws of\ + beta and kappa. - With `U` (the referral design, with its intercept), the arc g -> r is added: w_i ~ N(U_i gamma + gamma_g arc_i g_i, - 1), r_i = 1[w_i > 0], with `arc` = 1 where the protocol does not refer the woman's cell (the arc acts) and + With `U` (the referral design, with its intercept), the arc g -> r is added: w_i ~ N(U_i\ + gamma + gamma_g arc_i g_i, + 1), r_i = 1[w_i > 0], with `arc` = 1 where the protocol does not refer the woman's cell\ + (the arc acts) and delta = (gamma, gamma_g) ~ N(d0, D0), gamma_g last. Its draws are returned as "delta".""" rng = np.random.default_rng(seed) r, y = np.asarray(r, int), np.asarray(y, float) @@ -94,16 +130,16 @@ def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0 eta = X @ beta p = np.clip(norm.cdf(eta), 1e-12, 1 - 1e-12) odds_r = referral_odds(U @ delta[:-1], delta[-1], arc, r) if with_arc else 1.0 - g = rng.random(len(r)) < prob_g(p, r, y, kappa, odds_r) # 1. g | beta, delta, kappa, data - z = draw_latent(eta, g, rng) # 2. z | g, beta - m, L = normal_posterior(X, z, b0, B0inv) # 3. beta | z + g = rng.random(len(r)) < prob_g(p, r, y, kappa, odds_r) # 1. g | beta, delta, kappa, data + z = draw_latent(eta, g, rng) # 2. z | g, beta + m, L = normal_posterior(X, z, b0, B0inv) # 3. beta | z beta = m + L @ rng.standard_normal(len(m)) if with_arc: - D = np.column_stack([U, g * arc]) # 4. the referral design, with g as a column - w = draw_latent(D @ delta, r == 1, rng) # w | r, g, delta - m, L = normal_posterior(D, w, d0, D0inv) # delta | w, g + D = np.column_stack([U, g * arc]) # 4. the referral design, with g as a column + w = draw_latent(D @ delta, r == 1, rng) # w | r, g, delta + m, L = normal_posterior(D, w, d0, D0inv) # delta | w, g delta = m + L @ rng.standard_normal(len(m)) - kappa = draw_kappa(g, r, y, *kappa_ab, rng) # 5. kappa | g, y + kappa = draw_kappa(g, r, y, *kappa_ab, rng) # 5. kappa | g, y if it >= warmup: kept["beta"].append(beta) kept["kappa"].append(kappa) @@ -113,35 +149,45 @@ def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0 def split_rhat(draws: np.ndarray) -> float: - """Split R-hat of one scalar (Gelman et al., BDA3, section 11.4): `draws` has shape (chains, iterations). Each - chain is cut in half, and the spread between the halves' means is compared with the spread within them.""" + """Split R-hat of one scalar (Gelman et al., BDA3, section 11.4): `draws` has shape\ + (chains, iterations). Each + chain is cut in half, and the spread between the halves' means is compared with the spread\ + within them.""" half = draws.shape[1] // 2 - parts = np.concatenate([draws[:, :half], draws[:, half:2 * half]]) + parts = np.concatenate([draws[:, :half], draws[:, half : 2 * half]]) within = parts.var(axis=1, ddof=1).mean() between = half * parts.mean(axis=1).var(ddof=1) return float(np.sqrt(((half - 1) / half * within + between / half) / within)) def patterns(X, r, y, U=None, arc=None) -> dict: - """Women with the same covariates and the same observation share their likelihood term: the distinct rows and + """Women with the same covariates and the same observation share their likelihood term:\ + the distinct rows and how many women each one stands for (y = -1 marks an untested row).""" cols = [X, r[:, None], np.nan_to_num(y, nan=-1.0)[:, None]] if U is not None: cols += [U, np.asarray(arc, float)[:, None]] rows, counts = np.unique(np.column_stack(cols), axis=0, return_counts=True) p = X.shape[1] - out = {"X": rows[:, :p], "r": rows[:, p].astype(int), "y": rows[:, p + 1], "n": counts.astype(float)} + out = { + "X": rows[:, :p], + "r": rows[:, p].astype(int), + "y": rows[:, p + 1], + "n": counts.astype(float), + } if U is not None: - out["U"], out["arc"] = rows[:, p + 2:-1], rows[:, -1] + out["U"], out["arc"] = rows[:, p + 2 : -1], rows[:, -1] return out def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None): - """The same model with g summed out of the likelihood, so that NUTS samples only continuous parameters: + """The same model with g summed out of the likelihood, so that NUTS samples only\ + continuous parameters: P(data_i) = P(g=1) P(r_i | g=1) P(y_i | g=1) + P(g=0) P(r_i | g=0) P(y_i | g=0) - with P(y=1 | g=0) = 0 (specificity 1), so a tested positive keeps only the first term. Without `U` the test is + with P(y=1 | g=0) = 0 (specificity 1), so a tested positive keeps only the first term.\ + Without `U` the test is taken as done at random given x, and P(r | g) drops out, as in the Gibbs.""" import pymc as pm import pytensor.tensor as pt @@ -149,19 +195,23 @@ def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, d = patterns(np.asarray(X, float), np.asarray(r, int), np.asarray(y, float), U, arc) positive = (d["r"] == 1) & (d["y"] == 1) negative = (d["r"] == 1) & (d["y"] == 0) - log_phi = lambda v: pm.logcdf(pm.Normal.dist(0.0, 1.0), v) # log Phi(v), stable in the tails + + def log_phi(v): + # log Phi(v), stable in the tails + return pm.logcdf(pm.Normal.dist(0.0, 1.0), v) + with pm.Model() as model: beta = pm.MvNormal("beta", mu=np.asarray(b0, float), cov=np.asarray(B0, float)) kappa = pm.Beta("kappa", *kappa_ab) eta = pt.as_tensor(d["X"]) @ beta - log_g1, log_g0 = log_phi(eta), log_phi(-eta) # log P(g=1), log P(g=0) + log_g1, log_g0 = log_phi(eta), log_phi(-eta) # log P(g=1), log P(g=0) log_r1 = log_r0 = 0.0 if U is not None: delta = pm.MvNormal("delta", mu=np.asarray(d0, float), cov=np.asarray(D0, float)) eta_r = pt.as_tensor(d["U"]) @ delta[:-1] - sign = np.where(d["r"] == 1, 1.0, -1.0) # P(r=1) = Phi(.), P(r=0) = Phi(-.) + sign = np.where(d["r"] == 1, 1.0, -1.0) # P(r=1) = Phi(.), P(r=0) = Phi(-.) log_r1, log_r0 = log_phi(sign * (eta_r + delta[-1] * d["arc"])), log_phi(sign * eta_r) - log_y1 = pt.switch(negative, pt.log1p(-kappa), 0.0) # a diseased woman missed: 1 - kappa + log_y1 = pt.switch(negative, pt.log1p(-kappa), 0.0) # a diseased woman missed: 1 - kappa diseased = log_g1 + log_r1 + log_y1 healthy = log_g0 + log_r0 loglik = pt.switch(positive, diseased + pt.log(kappa), pt.logaddexp(diseased, healthy)) @@ -169,22 +219,49 @@ def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, return model -def nuts(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None, draws: int = 1000, - tune: int = 1000, chains: int = 4, seed: int = 0, cores: int | None = None) -> dict: - """NUTS on `pymc_model`. Returns the draws with the chains stacked (as in `gibbs`), the max split R-hat over the +def nuts( + X, + r, + y, + b0, + B0, + kappa_ab=(1.0, 1.0), + U=None, + arc=None, + d0=None, + D0=None, + draws: int = 1000, + tune: int = 1000, + chains: int = 4, + seed: int = 0, + cores: int | None = None, +) -> dict: + """NUTS on `pymc_model`. Returns the draws with the chains stacked (as in `gibbs`), the\ + max split R-hat over the parameters and the number of divergent transitions. `cores` defaults to one per chain.""" import pymc as pm with pymc_model(X, r, y, b0, B0, kappa_ab, U, arc, d0, D0): - idata = pm.sample(draws=draws, tune=tune, chains=chains, cores=cores or chains, random_seed=seed, progressbar=False, - compute_convergence_checks=False) + idata = pm.sample( + draws=draws, + tune=tune, + chains=chains, + cores=cores or chains, + random_seed=seed, + progressbar=False, + compute_convergence_checks=False, + ) post = idata.posterior out, rhats = {}, [] for name in ("beta", "kappa", "delta"): if name in post: - v = post[name].values.reshape(chains, draws, -1) # (chains, draws, parameters) + v = post[name].values.reshape(chains, draws, -1) # (chains, draws, parameters) rhats += [split_rhat(v[:, :, j]) for j in range(v.shape[2])] - out[name] = v.reshape(chains * draws, -1).squeeze() if name == "kappa" else v.reshape(chains * draws, -1) + out[name] = ( + v.reshape(chains * draws, -1).squeeze() + if name == "kappa" + else v.reshape(chains * draws, -1) + ) out["rhat"] = max(rhats) out["divergences"] = int(idata.sample_stats["diverging"].values.sum()) return out diff --git a/models/cacu/development_firth.py b/models/cacu/development_firth.py index e565f99..865e821 100644 --- a/models/cacu/development_firth.py +++ b/models/cacu/development_firth.py @@ -55,7 +55,9 @@ class FirthFamily(ClassifierMixin, BaseEstimator): def fit(self, X, y): """Fit the selected method to a binary outcome.""" if self.method not in ("firth", "flic", "flac"): - raise ValueError(f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'.") + raise ValueError( + f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'." + ) X = np.asarray(X, float) firth, h = solve_logistic(X, y) y = np.asarray(y, int) diff --git a/models/cacu/development_selection.py b/models/cacu/development_selection.py index d0e7ecd..af4d6bc 100644 --- a/models/cacu/development_selection.py +++ b/models/cacu/development_selection.py @@ -10,20 +10,21 @@ import time import numpy as np import pandas as pd -from scipy.special import expit, logit +from scipy.special import expit as expit +from scipy.special import logit from sklearn.linear_model import LogisticRegression from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score from sklearn.model_selection import LeaveOneOut, StratifiedKFold from models.cacu.development_firth import FirthFamily -METHODS = ('firth', 'flic', 'flac') +METHODS = ("firth", "flic", "flac") def _candidates(X, coverage, limit): eligible = [] for name in sorted(X.columns): - col = pd.to_numeric(X[name], errors='coerce') + col = pd.to_numeric(X[name], errors="coerce") known = col.dropna() if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}: eligible.append((name, col.notna().mean())) @@ -31,9 +32,11 @@ def _candidates(X, coverage, limit): chosen = [] for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])): a = X[name] - if any(((a == X[other]) | (a.isna() & X[other].isna())).all() or - ((a == 1 - X[other]) | (a.isna() & X[other].isna())).all() - for other in chosen): + if any( + ((a == X[other]) | (a.isna() & X[other].isna())).all() + or ((a == 1 - X[other]) | (a.isna() & X[other].isna())).all() + for other in chosen + ): continue chosen.append(name) if len(chosen) == limit: @@ -45,11 +48,11 @@ def _matrix(train, test, columns): tr = train[list(columns)].to_numpy(dtype=float) te = test[list(columns)].to_numpy(dtype=float) if tr.shape[1] and np.isnan(tr).all(axis=0).any(): - raise ValueError('predictor absent in training partition') + raise ValueError("predictor absent in training partition") median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([]) tr, te = np.where(np.isnan(tr), median, tr), np.where(np.isnan(te), median, te) if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1: - raise ValueError('collinear predictors in training partition') + raise ValueError("collinear predictors in training partition") return tr, te @@ -64,50 +67,76 @@ def _metrics(y, probability): y, p = np.asarray(y), np.asarray(probability) valid = np.isfinite(p) if valid.sum() != len(y) or len(np.unique(y)) != 2: - return {'auc': None, 'brier': None, 'calibration_intercept': None, - 'calibration_slope': None, 'log_loss': None} + return { + "auc": None, + "brier": None, + "calibration_intercept": None, + "calibration_slope": None, + "log_loss": None, + } logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1) calibration = LogisticRegression(C=1e6).fit(logits, y) - return {'auc': float(roc_auc_score(y, p)), 'brier': float(brier_score_loss(y, p)), - 'calibration_intercept': float(calibration.intercept_[0]), - 'calibration_slope': float(calibration.coef_[0, 0]), - 'log_loss': float(log_loss(y, p, labels=[0, 1]))} + return { + "auc": float(roc_auc_score(y, p)), + "brier": float(brier_score_loss(y, p)), + "calibration_intercept": float(calibration.intercept_[0]), + "calibration_slope": float(calibration.coef_[0, 0]), + "log_loss": float(log_loss(y, p, labels=[0, 1])), + } -def evaluate(X: pd.DataFrame, y, *, coverage=0.7, candidate_limit=5, subset_limit=2, - outer_folds=3, inner_folds=2, seed=17, max_fits=100000): +def evaluate( + X: pd.DataFrame, + y, + *, + coverage=0.7, + candidate_limit=5, + subset_limit=2, + outer_folds=3, + inner_folds=2, + seed=17, + max_fits=100000, +): """Evaluate Firth/FLIC/FLAC with nested stratified CV and nested leave-one-out. A fixed upper bound (default five candidates, pairs at most) permits at most 16 subsets including the intercept. Each method selects a subset by inner out-of-fold log loss for every outer split; all attempted subsets and failures are recorded. """ - X = X.reset_index(drop=True).apply(pd.to_numeric, errors='coerce') + X = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce") y = np.asarray(y) if len(X) != len(y) or not np.isin(y, [0, 1]).all(): - raise ValueError('one known binary outcome is required per row') + raise ValueError("one known binary outcome is required per row") if min(np.bincount(y.astype(int), minlength=2)) < max(outer_folds, inner_folds + 1): - raise ValueError('insufficient members of each outcome for nested CV and LOOCV') + raise ValueError("insufficient members of each outcome for nested CV and LOOCV") if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit: - raise ValueError('candidate and subset limits exceed the supported bounds') - max_subsets = sum(math.comb(candidate_limit, k) - for k in range(min(candidate_limit, subset_limit) + 1)) + raise ValueError("candidate and subset limits exceed the supported bounds") + max_subsets = sum( + math.comb(candidate_limit, k) for k in range(min(candidate_limit, subset_limit) + 1) + ) estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1) if estimated_fits > max_fits: - raise ValueError(f'estimated {estimated_fits} fits exceeds configured limit {max_fits}') + raise ValueError(f"estimated {estimated_fits} fits exceeds configured limit {max_fits}") attempted, outputs = [], {} started = time.monotonic() - plans = {'cv': StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y), - 'loocv': LeaveOneOut().split(X, y)} + plans = { + "cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y), + "loocv": LeaveOneOut().split(X, y), + } for plan, splits in plans.items(): predictions = {m: np.full(len(X), np.nan) for m in METHODS} selected = {m: [] for m in METHODS} for fold, (train_idx, test_idx) in enumerate(splits): train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int) candidates = _candidates(train, coverage, candidate_limit) - subsets = [()] + [c for size in range(1, min(len(candidates), subset_limit) + 1) - for c in itertools.combinations(candidates, size)] - inner = list(StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain)) + subsets = [()] + [ + c + for size in range(1, min(len(candidates), subset_limit) + 1) + for c in itertools.combinations(candidates, size) + ] + inner = list( + StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain) + ) for method in METHODS: ranking = [] for columns in subsets: @@ -115,28 +144,50 @@ def evaluate(X: pd.DataFrame, y, *, coverage=0.7, candidate_limit=5, subset_limi error = None try: for a, b in inner: - probs[b] = _predict(train.iloc[a], ytrain[a], train.iloc[b], columns, method) + probs[b] = _predict( + train.iloc[a], ytrain[a], train.iloc[b], columns, method + ) loss = float(log_loss(ytrain, probs, labels=[0, 1])) ranking.append((loss, len(columns), columns)) except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc: loss, error = None, type(exc).__name__ - attempted.append({'validation': plan, 'fold': fold, 'method': method, - 'variables': list(columns), 'inner_log_loss': loss, 'error': error}) + attempted.append( + { + "validation": plan, + "fold": fold, + "method": method, + "variables": list(columns), + "inner_log_loss": loss, + "error": error, + } + ) _, _, best = min(ranking) selected[method].append(list(best)) try: predictions[method][test_idx] = _predict(train, ytrain, test, best, method) except (ValueError, np.linalg.LinAlgError, RuntimeError): pass - outputs[plan] = {m: {'metrics': _metrics(y, predictions[m]), 'selected': selected[m], - 'unscored': int(np.isnan(predictions[m]).sum()), - 'stability': {name: sum(name in cols for cols in selected[m]) - for name in X.columns}} - for m in METHODS} - return {'development_only': True, 'candidate_limit': candidate_limit, - 'subset_limit': subset_limit, 'coverage_minimum': coverage, - 'max_subsets': max_subsets, 'maximum_fits': estimated_fits, - 'estimated_seconds_at_50ms_per_fit': estimated_fits * 0.05, - 'elapsed_seconds': time.monotonic() - started, - 'source': 'edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728', - 'attempts': attempted, 'validation': outputs} + outputs[plan] = { + m: { + "metrics": _metrics(y, predictions[m]), + "selected": selected[m], + "unscored": int(np.isnan(predictions[m]).sum()), + "stability": { + name: sum(name in cols for cols in selected[m]) for name in X.columns + }, + } + for m in METHODS + } + return { + "development_only": True, + "candidate_limit": candidate_limit, + "subset_limit": subset_limit, + "coverage_minimum": coverage, + "max_subsets": max_subsets, + "maximum_fits": estimated_fits, + "estimated_seconds_at_50ms_per_fit": estimated_fits * 0.05, + "elapsed_seconds": time.monotonic() - started, + "source": "edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728", + "attempts": attempted, + "validation": outputs, + } diff --git a/models/cacu/features.py b/models/cacu/features.py index 063638e..170ca4a 100644 --- a/models/cacu/features.py +++ b/models/cacu/features.py @@ -118,11 +118,15 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series: key = ["person_id", "source_table", "source_id"] samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred), [*key, "date"]] # fmt: skip - hysterectomy = events.loc[ - (events["source_table"] == "cervical_cytology") - & (events["type"] == "gynecologic_condition") - & (events["value_code"] == "hysterectomy") - ].groupby("person_id")["date"].min() + hysterectomy = ( + events.loc[ + (events["source_table"] == "cervical_cytology") + & (events["type"] == "gynecologic_condition") + & (events["value_code"] == "hysterectomy") + ] + .groupby("person_id")["date"] + .min() + ) recorded = samples["person_id"].map(hysterectomy) samples = samples[recorded.isna() | (samples["date"] < recorded)] results = events[events["type"].isin(RESULTS) & events["value_code"].notna()] diff --git a/models/cacu/pim.py b/models/cacu/pim.py index 048f5ab..98f97bd 100644 --- a/models/cacu/pim.py +++ b/models/cacu/pim.py @@ -271,8 +271,9 @@ class Mixture(BaseEstimator): point, variance = self.fits_[key].risk_with_variance( unique[:, :n_x], unique[:, n_x:], self.horizons_years ) - relative = np.where(np.isfinite(variance), - np.sqrt(variance) / np.maximum(point, 1e-300), np.nan) + relative = np.where( + np.isfinite(variance), np.sqrt(variance) / np.maximum(point, 1e-300), np.nan + ) band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1), np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip out[index[placed]] = band[inverse.ravel()] @@ -286,8 +287,11 @@ class Mixture(BaseEstimator): f = self.fits_.get(key) predictions = self.predict(X.iloc[index]) missing = np.isnan(predictions[:, h:]).any(axis=1) - entry = {"stratum": [str(v) for v in key], "rows": len(index), - "rows_without_interval": int(missing.sum())} + entry = { + "stratum": [str(v) for v in key], + "rows": len(index), + "rows_without_interval": int(missing.sum()), + } if f is None: entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[]) else: @@ -297,12 +301,18 @@ class Mixture(BaseEstimator): free = np.isfinite(diagonal) block = f.covariance[np.ix_(free, free)] try: - positive = bool(block.size and np.isfinite(block).all() - and np.allclose(block, block.T) - and (np.linalg.eigvalsh(block) > 0).all()) + positive = bool( + block.size + and np.isfinite(block).all() + and np.allclose(block, block.T) + and (np.linalg.eigvalsh(block) > 0).all() + ) except np.linalg.LinAlgError: positive = False - entry.update(status="positive_definite" if positive else "not_estimable", - frozen_parameters=frozen, negative_variances=negative) + entry.update( + status="positive_definite" if positive else "not_estimable", + frozen_parameters=frozen, + negative_variances=negative, + ) result.append(entry) return {"strata": result, "horizons_years": list(self.horizons_years)} diff --git a/models/cacu/reports.py b/models/cacu/reports.py index 053d2ae..7422b8c 100644 --- a/models/cacu/reports.py +++ b/models/cacu/reports.py @@ -36,13 +36,21 @@ COHORT_SCENARIOS = { AWAITING = {"unreported_biopsy", "no_index_result"} # Clinical categories, not execution order: a candidate may belong to several stages. REASON_STAGE = { - "hysterectomy": "eligibility", "under_18": "eligibility", - "no_birth_date": "eligibility", "died_by_index": "eligibility", - "prior_outcome": "history", "outcome_by_index": "history", - "cancer_history": "history", "prior_treatment": "history", - "outcome_before_index": "history", "no_pretreatment_biopsy": "history", - "no_referral": "index", "referral_not_graded": "index", "no_cotest": "index", - "no_index_result": "index", "unreported_biopsy": "index", + "hysterectomy": "eligibility", + "under_18": "eligibility", + "no_birth_date": "eligibility", + "died_by_index": "eligibility", + "prior_outcome": "history", + "outcome_by_index": "history", + "cancer_history": "history", + "prior_treatment": "history", + "outcome_before_index": "history", + "no_pretreatment_biopsy": "history", + "no_referral": "index", + "referral_not_graded": "index", + "no_cotest": "index", + "no_index_result": "index", + "unreported_biopsy": "index", } @@ -75,8 +83,10 @@ def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict str(stage): len(group[key].drop_duplicates()) for stage, group in stages.groupby("stage", sort=True) }, - "stage_by_reason": {str(reason): REASON_STAGE.get(str(reason), "unknown") - for reason in sorted(excluded["criterion"].unique())}, + "stage_by_reason": { + str(reason): REASON_STAGE.get(str(reason), "unknown") + for reason in sorted(excluded["criterion"].unique()) + }, "stage_counts_overlap": True, } @@ -129,8 +139,9 @@ def _label(feature: str, value) -> str: def _band(curve, variance) -> tuple[list, list]: - relative = np.where(np.isfinite(variance), - np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan) + relative = np.where( + np.isfinite(variance), np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan + ) return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip diff --git a/models/cacu/specs.py b/models/cacu/specs.py index ff49c19..b0f5767 100644 --- a/models/cacu/specs.py +++ b/models/cacu/specs.py @@ -49,9 +49,13 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, predictors=()) -> frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel() else: frame["ci_low"] = frame["ci_high"] = np.nan - frame["input_values"] = np.repeat([ - json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str) - for row in members[list(predictors)].to_dict("records")], h) + frame["input_values"] = np.repeat( + [ + json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str) + for row in members[list(predictors)].to_dict("records") + ], + h, + ) return frame[[*OUTPUT, "input_values"]] diff --git a/models/definitions.py b/models/definitions.py index fb56ed2..c52374a 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -96,7 +96,9 @@ class CacuDevelopmentEvaluation(dg.Config): @dg.op -def evaluate_cacu_development(context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation) -> str: +def evaluate_cacu_development( + context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation +) -> str: """Opt-in research evaluation only: no registered model, promotion or patient scores.""" import mlflow import pandas as pd @@ -112,8 +114,9 @@ def evaluate_cacu_development(context: dg.OpExecutionContext, config: CacuDevelo if events.empty: raise EmptyCohort(f"no eligible patients in {cohort}") encoded = encoders.encode(events, gold.cervical_forms(cohort)) - outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0, - pd.Timestamp(as_of)) + outcome = features.windowed_outcome( + features.prepared(events), cacu.CIN2_PLUS, 1.0, pd.Timestamp(as_of) + ) rows = encoded.merge(outcome, on="person_id", validate="one_to_one") rows = rows[rows["known"]].reset_index(drop=True) X = rows.drop(columns=["person_id", "index_date", "known", "y"]) @@ -185,5 +188,7 @@ nightly = ( else [] ) -defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup, - cacu_development_evaluation], schedules=nightly) +defs = dg.Definitions( + jobs=[ingest, train, score, analyze, rebuild, backup, cacu_development_evaluation], + schedules=nightly, +) diff --git a/models/jobs.py b/models/jobs.py index ba4bd3e..cc65243 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -73,7 +73,8 @@ class Jobs: } if hasattr(fitted, "variance_diagnostics"): found["variance_diagnostics"] = fitted.variance_diagnostics( - data["coded"][spec.features]) + data["coded"][spec.features] + ) # Bootstraps ran on joblib's worker pool: release it now, or the job's process waits # for its idle workers to time out (5 minutes) before it can end. get_reusable_executor().shutdown(wait=True) diff --git a/models/survival.py b/models/survival.py index 2ff5b96..a2e1964 100644 --- a/models/survival.py +++ b/models/survival.py @@ -351,9 +351,13 @@ class Spec: "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h), })[OUTPUT] # fmt: skip if self.cohort.startswith("cacu_"): - result["input_values"] = np.repeat([ - json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str) - for row in members[list(self.features)].to_dict("records")], h) + result["input_values"] = np.repeat( + [ + json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str) + for row in members[list(self.features)].to_dict("records") + ], + h, + ) return result @@ -462,7 +466,10 @@ def _combination_curves(spec: Spec, model: IntervalSurvival, members: pd.DataFra entry["points"] = {"COMB": point} entry["horizons_months"] = list(spec.borders[1:]) entry["km"]["interval"] = { - "available": True, "level": 0.95, "method": "greenwood_log_log"} + "available": True, + "level": 0.95, + "method": "greenwood_log_log", + } for name in ("weibull", "weibull_fractional"): entry[name]["interval"] = {"available": False, "level": None, "method": None} found.append(entry) @@ -550,20 +557,30 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: } if spec.cohort.startswith("cacu_"): for curve in report["curves"]: - method = ("greenwood_log_log" if curve["name"].startswith("Kaplan-Meier") - else "delta_method") + method = ( + "greenwood_log_log" if curve["name"].startswith("Kaplan-Meier") else "delta_method" + ) curve["interval"] = {"available": True, "level": 0.95, "method": method} report["predicted"]["interval"] = { - "available": True, "level": 0.95, "method": "bootstrap_percentile"} + "available": True, + "level": 0.95, + "method": "bootstrap_percentile", + } for combination in report["combinations"]: combination["interval"] = {"available": False, "level": None, "method": None} for scenario in report["escenarios"]: scenario["km"]["interval"] = { - "available": True, "level": 0.95, "method": "greenwood_log_log"} + "available": True, + "level": 0.95, + "method": "greenwood_log_log", + } for name in ("weibull", "weibull_fractional"): scenario[name]["interval"] = {"available": False, "level": None, "method": None} scenario["points"]["COMB"]["interval"] = { - "available": True, "level": 0.95, "method": "bootstrap_percentile"} + "available": True, + "level": 0.95, + "method": "bootstrap_percentile", + } for scenario in report["escenarios_sin_curvas"]: scenario["reason"] = "insufficient_deaths" report["km_combinaciones"] = _combination_curves(spec, model, members) diff --git a/tests/test_cacu_bayes_prevalence.py b/tests/test_cacu_bayes_prevalence.py index 37815e7..0b18c0b 100644 --- a/tests/test_cacu_bayes_prevalence.py +++ b/tests/test_cacu_bayes_prevalence.py @@ -1,12 +1,13 @@ -import pytest import numpy as np +import pytest from scipy.stats import norm from models.cacu.bayes_development import prevalence_gibbs as PG def test_normal_posterior_is_least_squares_under_a_flat_prior(): - """Fails if the conjugate mean does not reduce to least squares when the prior carries no information.""" + """Fails if the conjugate mean does not reduce to least squares when the prior carries no\ + information.""" rng = np.random.default_rng(1) X = np.column_stack([np.ones(200), rng.normal(size=200)]) z = X @ [0.5, -1.0] + rng.normal(size=200) @@ -24,7 +25,8 @@ def test_latent_sign_follows_g(): def test_prob_g_by_observation(): - """Fails if a tested positive is not certainly diseased, an untested woman does not keep her prior, or a tested + """Fails if a tested positive is not certainly diseased, an untested woman does not keep\ + her prior, or a tested negative is not discounted by 1 - kappa.""" p, k = np.full(3, 0.2), 0.7 out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k) @@ -33,7 +35,8 @@ def test_prob_g_by_observation(): def test_gibbs_recovers_the_prevalence_with_known_sensitivity(): - """Fails if, with kappa pinned by a strong prior, the chain misses the true probit coefficients of a simulated + """Fails if, with kappa pinned by a strong prior, the chain misses the true probit\ + coefficients of a simulated cross-sectional sample (60 % tested, one test each).""" rng = np.random.default_rng(3) n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7 @@ -41,13 +44,24 @@ def test_gibbs_recovers_the_prevalence_with_known_sensitivity(): g = rng.random(n) < norm.cdf(X @ beta) r = (rng.random(n) < 0.6).astype(int) y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan) - out = PG.gibbs(X, r, y, np.zeros(2), np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=4) + out = PG.gibbs( + X, + r, + y, + np.zeros(2), + np.eye(2) * 4, + kappa_ab=(7000, 3000), + iterations=1500, + warmup=500, + seed=4, + ) assert np.allclose(out["beta"].mean(0), beta, atol=0.12) assert abs(out["kappa"].mean() - 0.7) < 0.02 def test_referral_odds(): - """Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) / Phi(eta) for a tested woman + """Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) /\ + Phi(eta) for a tested woman and the same with the survival function for an untested one.""" eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8 out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0])) @@ -57,8 +71,10 @@ def test_referral_odds(): def _referral_sample(n=8000, seed=5): - """Two cells: the protocol refers the abnormal one (84 %); the normal one is referred mostly when diseased - (3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell: Phi(-1.6) = 5.5 %.""" + """Two cells: the protocol refers the abnormal one (84 %); the normal one is referred\ + mostly when diseased + (3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell:\ + Phi(-1.6) = 5.5 %.""" rng = np.random.default_rng(seed) abnormal = (rng.random(n) < 0.2).astype(float) X = np.column_stack([np.ones(n), abnormal]) @@ -71,10 +87,13 @@ def _referral_sample(n=8000, seed=5): def test_the_arc_removes_the_selection_bias(): - """Fails if ignoring who gets referred does not overstate the prevalence of the unreferred cell, or if the arc + """Fails if ignoring who gets referred does not overstate the prevalence of the unreferred\ + cell, or if the arc with an informative prior on gamma_g does not bring it back to the truth (5.5 %).""" X, r, y, U, arc = _referral_sample() - common = dict(b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6) + common = dict( + b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6 + ) without = PG.gibbs(X, r, y, **common) with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common) assert norm.cdf(without["beta"][:, 0]).mean() > 0.2 @@ -83,7 +102,8 @@ def test_the_arc_removes_the_selection_bias(): def test_split_rhat(): - """Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different levels do not exceed 1.1.""" + """Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different\ + levels do not exceed 1.1.""" rng = np.random.default_rng(7) assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01 assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1 @@ -94,12 +114,15 @@ def test_patterns_keep_every_woman(): X, r, y, U, arc = _referral_sample(n=500) d = PG.patterns(X, r, y, U, arc) assert d["n"].sum() == 500 - assert len(d["n"]) == len(np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0)) + assert len(d["n"]) == len( + np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0) + ) def test_summed_likelihood_matches_a_direct_sum(): pytest.importorskip("pymc") # optional dependency, not in the production environment - """Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g) woman by woman.""" + """Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g)\ + woman by woman.""" X, r, y, U, arc = _referral_sample(n=400) beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2]) model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3)) @@ -107,8 +130,13 @@ def test_summed_likelihood_matches_a_direct_sum(): point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta}) got = model.compile_logp(vars=model.potentials)(point) p = norm.cdf(X @ beta) - pr = lambda shift: np.where(r == 1, norm.cdf(shift), norm.sf(shift)) + + def pr(shift): + return np.where(r == 1, norm.cdf(shift), norm.sf(shift)) + py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0) py0 = np.where((r == 1) & (y == 1), 0.0, 1.0) - direct = np.log(p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0).sum() + direct = np.log( + p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0 + ).sum() assert np.isclose(got, direct) diff --git a/tests/test_cacu_development_selection.py b/tests/test_cacu_development_selection.py index e0d42bf..bc54950 100644 --- a/tests/test_cacu_development_selection.py +++ b/tests/test_cacu_development_selection.py @@ -6,7 +6,7 @@ from models.cacu.development_firth import FirthFamily from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate -@pytest.mark.parametrize('method', METHODS) +@pytest.mark.parametrize("method", METHODS) def test_methods_fit_simulated_data(method): X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float) y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0]) @@ -15,28 +15,28 @@ def test_methods_fit_simulated_data(method): def test_candidates_and_imputation_use_only_training_rows(): - train = pd.DataFrame({'a': [0., 1., np.nan, 1.], 'copy': [0., 1., np.nan, 1.], - 'absent': [np.nan] * 4}) - assert _candidates(train, 0.7, 5) == ['a'] - a, b = _matrix(train, pd.DataFrame({'a': [np.nan]}), ['a']) + train = pd.DataFrame( + {"a": [0.0, 1.0, np.nan, 1.0], "copy": [0.0, 1.0, np.nan, 1.0], "absent": [np.nan] * 4} + ) + assert _candidates(train, 0.7, 5) == ["a"] + a, b = _matrix(train, pd.DataFrame({"a": [np.nan]}), ["a"]) assert b[0, 0] == np.nanmedian(a[:, 0]) == 1 def test_nested_cv_and_loocv_record_every_attempt(): - X = pd.DataFrame({'a': [0, 0, 1, 1, 0, 1, 0, 1], - 'b': [0, 1, 0, 1, 1, 0, 0, 1]}) + X = pd.DataFrame({"a": [0, 0, 1, 1, 0, 1, 0, 1], "b": [0, 1, 0, 1, 1, 0, 0, 1]}) y = np.array([0, 1, 0, 1, 0, 1, 1, 0]) report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2) - assert report['development_only'] and report['max_subsets'] == 4 - assert set(report['validation']) == {'cv', 'loocv'} - assert {a['method'] for a in report['attempts']} == set(METHODS) - assert all('variables' in a and 'error' in a for a in report['attempts']) - assert all(len(report['validation']['loocv'][m]['selected']) == len(X) for m in METHODS) + assert report["development_only"] and report["max_subsets"] == 4 + assert set(report["validation"]) == {"cv", "loocv"} + assert {a["method"] for a in report["attempts"]} == set(METHODS) + assert all("variables" in a and "error" in a for a in report["attempts"]) + assert all(len(report["validation"]["loocv"][m]["selected"]) == len(X) for m in METHODS) def test_budget_rejects_large_loocv_before_fitting(): - X = pd.DataFrame({'a': [0, 1] * 10}) - with pytest.raises(ValueError, match='exceeds configured limit'): + X = pd.DataFrame({"a": [0, 1] * 10}) + with pytest.raises(ValueError, match="exceeds configured limit"): evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1) @@ -44,9 +44,9 @@ def test_development_job_is_not_a_production_score(): from core.models import DEVELOPMENT from models.definitions import defs - assert 'cacu.cin2_firth_development' in DEVELOPMENT - job = defs.get_job_def('cacu_development_evaluation') - assert job.name == 'cacu_development_evaluation' + assert "cacu.cin2_firth_development" in DEVELOPMENT + job = defs.get_job_def("cacu_development_evaluation") + assert job.name == "cacu_development_evaluation" def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch): @@ -58,26 +58,37 @@ def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypa from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development from persistance import gold - monkeypatch.setenv('MLFLOW_TRACKING_URI', (tmp_path / 'mlruns').as_uri()) - monkeypatch.setenv('MLFLOW_ALLOW_FILE_STORE', 'true') - monkeypatch.setattr(tracking_utils, '_tracking_uri', tracking_utils._tracking_uri) - mlflow.set_tracking_uri((tmp_path / 'mlruns').as_uri()) + monkeypatch.setenv("MLFLOW_TRACKING_URI", (tmp_path / "mlruns").as_uri()) + monkeypatch.setenv("MLFLOW_ALLOW_FILE_STORE", "true") + monkeypatch.setattr(tracking_utils, "_tracking_uri", tracking_utils._tracking_uri) + mlflow.set_tracking_uri((tmp_path / "mlruns").as_uri()) patients = [str(i) for i in range(8)] - events = pd.DataFrame({'person_id': patients, 'date': ['2025-01-01'] * 8, - 'index_date': ['2025-01-01'] * 8}) - encoded = pd.DataFrame({'person_id': patients, 'index_date': ['2025-01-01'] * 8, - 'factor': [0, 0, 1, 1, 0, 1, 0, 1]}) - outcomes = pd.DataFrame({'person_id': patients, 'known': [True] * 8, - 'y': [0, 1, 0, 1, 0, 1, 1, 0]}) - monkeypatch.setattr(gold, 'evidence_timelines', lambda *a: events) - monkeypatch.setattr(gold, 'cervical_forms', lambda *a: pd.DataFrame()) - monkeypatch.setattr(encoders, 'encode', lambda *a: encoded) - monkeypatch.setattr(features, 'windowed_outcome', lambda *a: outcomes) + events = pd.DataFrame( + {"person_id": patients, "date": ["2025-01-01"] * 8, "index_date": ["2025-01-01"] * 8} + ) + encoded = pd.DataFrame( + { + "person_id": patients, + "index_date": ["2025-01-01"] * 8, + "factor": [0, 0, 1, 1, 0, 1, 0, 1], + } + ) + outcomes = pd.DataFrame( + {"person_id": patients, "known": [True] * 8, "y": [0, 1, 0, 1, 0, 1, 1, 0]} + ) + monkeypatch.setattr(gold, "evidence_timelines", lambda *a: events) + monkeypatch.setattr(gold, "cervical_forms", lambda *a: pd.DataFrame()) + monkeypatch.setattr(encoders, "encode", lambda *a: encoded) + monkeypatch.setattr(features, "windowed_outcome", lambda *a: outcomes) real = development_selection.evaluate - monkeypatch.setattr(development_selection, 'evaluate', - lambda X, y, **kw: real(X, y, candidate_limit=1, subset_limit=1, - outer_folds=2, inner_folds=2, **kw)) + monkeypatch.setattr( + development_selection, + "evaluate", + lambda X, y, **kw: real( + X, y, candidate_limit=1, subset_limit=1, outer_folds=2, inner_folds=2, **kw + ), + ) with dg.build_op_context() as context: - run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of='2026-01-01')) - artifacts = mlflow.MlflowClient().list_artifacts(run_id, 'reports') - assert [a.path for a in artifacts] == ['reports/development_evaluation.json'] + run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of="2026-01-01")) + artifacts = mlflow.MlflowClient().list_artifacts(run_id, "reports") + assert [a.path for a in artifacts] == ["reports/development_evaluation.json"] diff --git a/tests/test_cacu_hpv_required.py b/tests/test_cacu_hpv_required.py index 3f621f7..b554b7d 100644 --- a/tests/test_cacu_hpv_required.py +++ b/tests/test_cacu_hpv_required.py @@ -10,4 +10,7 @@ def test_without_an_hpv_result_she_is_not_evaluated(): rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")] events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"]) found = f.index_results(events, cacu.KPNC) - assert dict(zip(found["person_id"], found["hpv_positive"])) == {"negative": 0.0, "positive": 1.0} + assert dict(zip(found["person_id"], found["hpv_positive"], strict=False)) == { + "negative": 0.0, + "positive": 1.0, + } diff --git a/tests/test_cacu_models.py b/tests/test_cacu_models.py index e86b881..20856d8 100644 --- a/tests/test_cacu_models.py +++ b/tests/test_cacu_models.py @@ -68,7 +68,9 @@ def hpv_missing_as_the_current_platform_read_it(events: pd.DataFrame) -> pd.Data near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS) has = events[(events["type"] == "hpv") & near] missing = index[~index["person_id"].isin(has["person_id"])] - assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed") # not positive, and not a negative visit + assumed = missing.assign( + date=missing["index_date"], type="hpv", value_code="assumed" + ) # not positive, and not a negative visit return pd.concat([events, assumed[events.columns]], ignore_index=True) @@ -100,8 +102,9 @@ def test_predictions_match_the_current_models(name): # Older reference intervals include non-estimable covariance estimates. Preserve # parity for point estimates and for intervals that remain estimable. comparable = both[ours].notna() if ours != "probability" else np.ones(len(both), bool) - np.testing.assert_allclose(both.loc[comparable, ours], both.loc[comparable, theirs], - rtol=RTOL, atol=0) + np.testing.assert_allclose( + both.loc[comparable, ours], both.loc[comparable, theirs], rtol=RTOL, atol=0 + ) if spec.method != "logistic regression": assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all() @@ -128,7 +131,7 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk "stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name found = spec.predict(model, events) - assert all(set(json.loads(value)) == set(spec.features) for value in found['input_values']) + assert all(set(json.loads(value)) == set(spec.features) for value in found["input_values"]) reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet") both = found.merge(reference, left_on=["person_id", "horizon_years"], right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip diff --git a/tests/test_cacu_prediction_inputs.py b/tests/test_cacu_prediction_inputs.py index fafd9ad..4391c49 100644 --- a/tests/test_cacu_prediction_inputs.py +++ b/tests/test_cacu_prediction_inputs.py @@ -7,12 +7,16 @@ from models.cacu.specs import _rows def test_each_scored_horizon_keeps_the_inputs_of_its_patient(): - members = pd.DataFrame([ - {"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0}, - {"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1}, - ]) - result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5), - ("cytology", "hpv")) + members = pd.DataFrame( + [ + {"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0}, + {"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1}, + ] + ) + result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5), ("cytology", "hpv")) assert [json.loads(v) for v in result.input_values] == [ - {"cytology": "NILM", "hpv": 0}, {"cytology": "NILM", "hpv": 0}, - {"cytology": "HSIL", "hpv": 1}, {"cytology": "HSIL", "hpv": 1}] + {"cytology": "NILM", "hpv": 0}, + {"cytology": "NILM", "hpv": 0}, + {"cytology": "HSIL", "hpv": 1}, + {"cytology": "HSIL", "hpv": 1}, + ] diff --git a/tests/test_pim_variance_availability.py b/tests/test_pim_variance_availability.py index 2e969e9..c8434fc 100644 --- a/tests/test_pim_variance_availability.py +++ b/tests/test_pim_variance_availability.py @@ -10,8 +10,11 @@ def test_unestimable_covariances_never_produce_zero_width_intervals(): X, Z = np.ones((1, 1)), np.empty((1, 0)) good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True) assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all() - for covariance in (np.full((len(params), len(params)), np.nan), - -np.eye(len(params)), np.zeros((len(params), len(params)))): + for covariance in ( + np.full((len(params), len(params)), np.nan), + -np.eye(len(params)), + np.zeros((len(params), len(params))), + ): broken = Fit(1, 0, baseline, params, covariance, 0, True) assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all() @@ -35,6 +38,6 @@ def test_diagnostics_count_rows_without_intervals(): model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)} model.seen_ = {(): {}} report = model.variance_diagnostics(pd.DataFrame(index=range(2))) - assert report['strata'][0]['rows_without_interval'] == 2 - assert report['strata'][0]['negative_variances'] - assert report['strata'][0]['status'] == 'not_estimable' + assert report["strata"][0]["rows_without_interval"] == 2 + assert report["strata"][0]["negative_variances"] + assert report["strata"][0]["status"] == "not_estimable"