Compare commits

...

15 Commits

Author SHA1 Message Date
edgar aca4c9d58a Publicar Weibull y puntos del modelo en las curvas por combinación 2026-12-03 07:28:47 -06:00
edgar a1e2e07e0c Revertir el diagnóstico NUTS opcional con PyMC 2026-12-03 07:21:25 -06:00
edgar 17a60ff68d Añadir diagnóstico NUTS sintético opcional 2026-12-03 01:00:04 -06:00
edgar efa2c2793e Omitir la prueba que requiere PyMC cuando no está instalado 2026-12-03 00:55:50 -06:00
edgar 3a033efc1b Incorporar base bayesiana de investigación 2026-12-03 00:47:02 -06:00
edgar d27b585560 Evaluar regresiones de desarrollo con selección anidada 2026-12-03 00:44:47 -06:00
edgar 1feedad79a Agregar codificadores binarios de las variables CaCu a la fecha índice 2026-12-02 23:59:02 -06:00
edgar da14e4ea8e Publicar Kaplan-Meier por combinación de valores en supervivencia CaCu 2026-12-02 23:20:50 -06:00
edgar fe1f284e00 Guardar variables usadas en cada predicción 2026-12-02 23:13:55 -06:00
edgar d392cc02a5 Informar intervalos PIM no estimables 2026-12-02 23:04:01 -06:00
edgar 8a860c698f Declarar intervalos y motivos en curvas CaCu 2026-12-02 21:59:04 -06:00
edgar 6e6c5bb81b Contar etapas de descarte en cohortes CaCu 2026-12-02 21:59:04 -06:00
edgar d27319ad1f Agregar el job que reconstruye silver y gold sin ingerir 2026-12-02 21:57:33 -06:00
edgar b5480e8bbb Guardar la deserción de cada cohorte CaCu junto al modelo entrenado 2026-12-02 17:03:54 -06:00
edgar dbbea0b16e Conservar las fechas y referencias de origen en la ingesta FHIR 2026-12-02 15:38:09 -06:00
22 changed files with 1371 additions and 22 deletions
+20
View File
@@ -0,0 +1,20 @@
# Fundamento bayesiano en desarrollo
`prevalence_gibbs.py` y sus pruebas proceden de `edgar/bayes-pim`, commit
`1cef69be90a7a9ea30378118cd2a2c9fa312943e`. Solo se cambió el import de las
pruebas. El módulo incluye Gibbs de prevalencia transversal y funciones NUTS
con importación diferida de PyMC; no está conectado a producción ni a Dagster.
Esto **no implementa todavía** el modelo longitudinal: faltan los módulos de
Markov y Klausch, el adaptador de visitas gold con fecha de disponibilidad,
la ejecución NUTS, y el artefacto de diagnóstico y comparación. El original
usa CIN3+ y categorías de biopsia que esta plataforma no puede identificar
por separado; no se deben transformar HSIL o CIN2+ en CIN3+. Su fitting
además importa `models.cacu.cin2_pim.likelihood`, que no existe aquí: hay que
verificar matemáticamente la equivalencia con el PIM actual antes de conectar
las verosimilitudes. La disponibilidad temporal y la definición del desenlace
se deben resolver antes de entrenar con datos reales.
No se añadieron PyMC ni otras dependencias al entorno de producción. El modelo
se mantiene únicamente como código de investigación, sin registro, promoción,
servicio de predicciones ni entrenamiento con datos de pacientes.
@@ -0,0 +1,190 @@
"""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
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)
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,
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
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]:
"""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)
m = V @ (X.T @ z + B0inv @ b0)
return m, np.linalg.cholesky(V)
def draw_latent(mean: np.ndarray, positive: np.ndarray, rng: np.random.Generator) -> np.ndarray:
"""Albert-Chib step: z ~ N(mean, 1) truncated to z > 0 where `positive`, to z <= 0 elsewhere."""
lo = np.where(positive, -mean, -np.inf)
hi = np.where(positive, np.inf, -mean)
return mean + truncnorm.rvs(lo, hi, random_state=rng)
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
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."""
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
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."""
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."""
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.
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)
b0, B0inv = np.asarray(b0, float), np.linalg.inv(np.asarray(B0, float))
beta, kappa = b0.copy(), kappa_ab[0] / sum(kappa_ab)
with_arc = U is not None
if with_arc:
arc, d0 = np.asarray(arc, float), np.asarray(d0, float)
D0inv, delta = np.linalg.inv(np.asarray(D0, float)), np.asarray(d0, float).copy()
kept = {"beta": [], "kappa": [], "delta": []}
for it in range(iterations):
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
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
delta = m + L @ rng.standard_normal(len(m))
kappa = draw_kappa(g, r, y, *kappa_ab, rng) # 5. kappa | g, y
if it >= warmup:
kept["beta"].append(beta)
kept["kappa"].append(kappa)
if with_arc:
kept["delta"].append(delta)
return {k: np.array(v) for k, v in kept.items() if v}
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."""
half = draws.shape[1] // 2
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
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)}
if U is not None:
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:
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
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
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
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_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(-.)
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
diseased = log_g1 + log_r1 + log_y1
healthy = log_g0 + log_r0
loglik = pt.switch(positive, diseased + pt.log(kappa), pt.logaddexp(diseased, healthy))
pm.Potential("loglik", pt.sum(d["n"] * loglik))
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
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)
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)
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["rhat"] = max(rhats)
out["divergences"] = int(idata.sample_stats["diverging"].values.sum())
return out
+83
View File
@@ -0,0 +1,83 @@
"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
import warnings
import numpy as np
from scipy.optimize import brentq
from scipy.special import expit
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.exceptions import ConvergenceWarning
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
class ConvergenceError(RuntimeError):
"""Raised when the remaining Newton step fails the convergence check."""
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
"""Fit logistic regression and return the fitted solver and leverages.
Check the remaining Newton step directly because numerical precision can
affect the solver's convergence flag.
"""
y = np.asarray(y)
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
y = y.astype(int, copy=False)
from firthmodels import FirthLogisticRegression
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
X, y, sample_weight=sample_weight
)
design = np.column_stack([np.ones(len(y)), X])
weights = np.ones(len(y)) if sample_weight is None else sample_weight
p = expit(model.intercept_ + X @ model.coef_)
w = weights * p * (1 - p)
info = design.T @ (w[:, None] * design)
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
step = np.abs(np.linalg.solve(info, score)).max()
if not np.isfinite(step) or step >= 1e-4:
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
return model, h
class FirthFamily(ClassifierMixin, BaseEstimator):
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
def __init__(self, method="firth"):
self.method = method
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'.")
X = np.asarray(X, float)
firth, h = solve_logistic(X, y)
y = np.asarray(y, int)
self.classes_ = np.array([0, 1])
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
if self.method == "flic":
eta = X @ self.coef_
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
elif self.method == "flac":
# Pseudo-observations use both outcomes, each with half the leverage.
g = np.repeat([0, 1, 1], len(y))
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
self.y_aug_ = np.concatenate([y, y, 1 - y])
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
# Predict on original observations, where the indicator is zero.
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
return self
def predict_proba(self, X):
"""Return probabilities for classes 0 and 1 in that order."""
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
return np.column_stack([1 - p, p])
+142
View File
@@ -0,0 +1,142 @@
"""Nested, exhaustive evaluation of a bounded set of CaCu binary encoders.
Development only. Selection, coverage screening, rank checks and imputation use training
partitions only. Methods follow edgar/camodels commit 2392d54fd4a3942b56dae803906586bc65600728.
"""
import itertools
import math
import time
import numpy as np
import pandas as pd
from scipy.special import expit, 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')
def _candidates(X, coverage, limit):
eligible = []
for name in sorted(X.columns):
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()))
# Perfectly identical or complementary observed columns are not distinguishable.
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):
continue
chosen.append(name)
if len(chosen) == limit:
break
return chosen
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')
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')
return tr, te
def _predict(train, y, test, columns, method):
tr, te = _matrix(train, test, columns)
if not columns:
return np.repeat(np.mean(y), len(test))
return FirthFamily(method).fit(tr, y).predict_proba(te)[:, 1]
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}
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]))}
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')
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')
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')
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))
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}')
attempted, outputs = [], {}
started = time.monotonic()
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))
for method in METHODS:
ranking = []
for columns in subsets:
probs = np.full(len(train), np.nan)
error = None
try:
for a, b in inner:
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})
_, _, 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}
+234
View File
@@ -0,0 +1,234 @@
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her
index date. NaN is missing: an absent value is never 0. No model reads these; they are
there for when one does.
Only what was available at the index is read (see `visible`): the index sample's results,
reported after it, are missing when the index is the sample day.
Inputs are the gold timeline with its `evidence_date` and `source_available_at`
(persistance.gold.evidence_timelines) and, for the form fields gold does not carry, the
wide silver cytology (persistance.gold.cervical_forms)."""
import numpy as np
import pandas as pd
from core import cacu, catalog
from models.cacu.features import _referral_grade, _worst, prepared
from models.cacu.specs import _REFERRAL
from models.survival import age_group, band
# What was done to her before the index: the index day's own is left out, as it may be
# (or follow from) the outcome.
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
GENOTYPES = cacu.HPV_GENOTYPE_FIELDS
EVIDENCE_TABLE = "cacu_eligibility_evidence"
def _codes(field: str) -> list[str]:
return list(catalog.studies()["cervical_cytology"].fields[field].codes)
FINDINGS = tuple(
name for name, f in catalog.studies()["cervical_cytology"].fields.items()
if name.startswith("finding_") and f.type == "boolean"
) # fmt: skip
def _day(values: pd.Series) -> pd.Series:
"""The calendar day of dates or ISO timestamps (as written); empty stays NaT."""
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's events available at her index, with her index date:
- dated (a result: reported) and, if it has one, clinically dated by the index;
- `source_available_at`, when the source gave it, by the index day. When it gave none,
the event's date stands, except for standalone eligibility evidence, dated by its
clinical onset: that is left out, as the cohort rules do;
- procedures and diagnoses strictly before the index day.
`known_at` (when the platform loaded it) is not read."""
found = events.drop(columns="index_date", errors="ignore").merge(
members[["person_id", "index_date"]], on="person_id"
)
index = pd.to_datetime(found["index_date"]).dt.normalize()
date, clinical = _day(found["date"]), _day(found["evidence_date"])
available = _day(found["source_available_at"])
keep = (date <= index) & (clinical.isna() | (clinical <= index))
undated = available.isna() & (found["source_table"] != EVIDENCE_TABLE)
keep &= undated | (available <= index)
earlier = (date < index) & (clinical.isna() | (clinical < index))
hysterectomy = (found["type"] == "gynecologic_condition") & (
found["value_code"] == "hysterectomy"
)
keep &= earlier | ~(found["type"].isin(PROCEDURES) | hysterectomy)
return prepared(found[keep])
def _flag(known: pd.Series, true: pd.Series) -> pd.Series:
"""1.0 / 0.0 where `known`, NaN elsewhere."""
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
def _one_hot(values: pd.Series, prefix: str, codes: list[str]) -> dict[str, pd.Series]:
"""One column per code; a value that is none of them is missing, not 0 in all."""
known = values.isin(codes)
return {f"{prefix}__{code}": _flag(known, values == code) for code in codes}
def _present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
"""1 when recorded; NaN otherwise (no record does not show it never happened)."""
return pd.Series(np.where(people.isin(events["person_id"]), 1.0, np.nan), index=people)
def _latest(events: pd.DataFrame, kind: str, people: pd.Index) -> pd.Series:
"""Each member's latest recorded value of one kind of event."""
found = events[(events["type"] == kind) & events["value_code"].notna()]
found = found.sort_values(["date", "source_id"], kind="stable")
return found.groupby("person_id")["value_code"].last().reindex(people)
def _latest_bethesda(events: pd.DataFrame, people: pd.Index) -> pd.Series:
"""The result of her latest report; the most severe when that day has several."""
codes = _codes("result")
found = events[(events["type"] == "bethesda") & events["value_code"].isin(codes)]
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
# severity is the order of the KPNC categories, not the catalog's
severity = {name: [name] for names in cacu.KPNC.values() for name in names if name in codes}
return _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
def _age(events: pd.DataFrame, members: pd.DataFrame) -> dict[str, pd.Series]:
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
keyed = members.set_index("person_id", drop=False)
keyed = keyed.assign(index_date=pd.to_datetime(keyed["index_date"]))
found = age_group(events, keyed, cuts)
labels = list(band(pd.Series([cuts[0] - 1, *cuts]), cuts))
return _one_hot(found, "age", labels)
def _cytology(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
result = _latest_bethesda(events, people)
columns = _one_hot(result, "bethesda", _codes("result"))
for name, codes in cacu.PROCEDURE_CYTOLOGY.items():
columns[f"cytology_{name}"] = _flag(result.notna(), result.isin(codes))
return columns
def _hpv(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
columns = {}
for kind in ("hpv", *GENOTYPES):
value = _latest(events, kind, people)
columns[f"{kind}_positive"] = _flag(
value.isin(["positive", "negative"]), value == "positive"
)
# From the two genotypes of one sample, not gold's `hpv_16_18`: that is 0 when one is
# negative and the other was not reported.
found = events[events["type"].isin(GENOTYPES) & events["value_code"].notna()]
wide = found.pivot_table(
index=["person_id", "date", "source_id"], columns="type", values="value_code",
aggfunc="first",
).reindex(columns=list(GENOTYPES)) # fmt: skip
latest = wide.sort_index().reset_index().drop_duplicates("person_id", keep="last")
latest = latest.set_index("person_id").reindex(people)[list(GENOTYPES)]
positive = (latest == "positive").any(axis=1)
both_negative = (latest == "negative").all(axis=1)
columns["hpv_16_or_18_positive"] = _flag(positive | both_negative, positive)
return columns
def _history(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
of = {kind: events[events["type"] == kind] for kind in (*PROCEDURES, "cytology")}
columns = {
"prior_cytology_sample": _present(
of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]], people
),
"prior_biopsy_order": _present(of["biopsy_order"], people),
"prior_biopsy_report": _present(of["biopsy"], people),
"prior_colposcopy": _present(of["colposcopy"], people),
"prior_treatment": _present(of["treatment"], people),
"prior_diagnosis_note": _present(of["diagnosis"], people),
"history_cancer_icd10": _present(of["history"], people),
"history_hysterectomy": _present(
events[(events["type"] == "gynecologic_condition")
& (events["value_code"] == "hysterectomy")], people
),
} # fmt: skip
rank = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY)}
worst = of["biopsy"]["value_code"].map(rank).groupby(of["biopsy"]["person_id"]).max()
worst = worst.reindex(people)
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "HSIL"), ("carcinoma", "carcinoma")):
columns[f"prior_biopsy_{name}"] = _flag(worst.notna(), worst >= rank[grade])
persons = pd.Series(people, index=people)
if events["type"].eq("colposcopy").any():
grade = _referral_grade(events, persons, _REFERRAL | {"cytology": cacu.KPNC_3})
else:
grade = pd.Series(None, index=people, dtype=object)
columns["referral_high_grade"] = _flag(grade.notna(), grade == "high")
return columns
def _forms(forms: pd.DataFrame | None, members: pd.DataFrame) -> dict[str, pd.Series]:
"""The cytology form's fields gold does not carry. Silver keeps no
`source_available_at` for them: what the sample form says counts from the sample day,
what the report says from the report day."""
people = pd.Index(members["person_id"])
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
*FINDINGS] # fmt: skip
if forms is None:
forms = pd.DataFrame(columns=columns)
found = forms[columns].merge(members[["person_id", "index_date"]], on="person_id")
index = pd.to_datetime(found["index_date"]).dt.normalize()
sampled = found[(_day(found["sample_date"]) <= index) & found["screening_history"].notna()]
sampled = sampled.sort_values("sample_date", key=_day, kind="stable")
history = sampled.groupby("person_id")["screening_history"].last().reindex(people)
reported = found[(_day(found["report_date"]) <= index) & (_day(found["sample_date"]) <= index)]
reported = reported.assign(r=_day(reported["report_date"]), s=_day(reported["sample_date"]))
# Her latest report, whole: a finding it does not state is unknown, whatever older
# reports said.
report = reported.sort_values(["r", "s"], kind="stable").drop_duplicates(
"person_id", keep="last"
)
report = report.set_index("person_id").reindex(people)
out = _one_hot(history, "screening_history", _codes("screening_history"))
adequacy = report["adequacy"]
out["sample_unsatisfactory"] = _flag(
adequacy.isin(_codes("adequacy")), adequacy == "unsatisfactory"
)
for name in FINDINGS:
value = report[name]
out[name] = _flag(value.notna(), value.eq(True))
return out
def encode(events: pd.DataFrame, forms: pd.DataFrame | None = None) -> pd.DataFrame:
"""One row per member of `events` (`person_id`, `index_date`): every encoder's column,
0.0, 1.0 or NaN. `events` needs `evidence_date` and `source_available_at`; without
`forms` their columns are all missing."""
missing = {"evidence_date", "source_available_at"} - set(events.columns)
if missing:
raise ValueError(f"timeline without availability columns: {', '.join(sorted(missing))}")
members = events[["person_id", "index_date"]].drop_duplicates().reset_index(drop=True)
if members["person_id"].duplicated().any():
raise ValueError("one index date per person")
people = pd.Index(members["person_id"], name="person_id")
seen = visible(events, members)
columns = _age(seen, members)
columns |= _cytology(seen, people)
columns |= _hpv(seen, people)
exam = seen[seen["source_table"] == "cervical_cytology"]
for field in EXAM_FIELDS:
columns |= _one_hot(_latest(exam, field, people), field, _codes(field))
columns |= _history(seen, people)
columns |= _forms(forms, members)
values = {name: column.to_numpy(dtype=float) for name, column in columns.items()}
return pd.concat([members, pd.DataFrame(values)], axis=1)
+14 -1
View File
@@ -1,8 +1,21 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports.""" """CaCu's training and scoring jobs (models.jobs) over its models and reports."""
from datetime import date
from models.cacu import reports from models.cacu import reports
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
from persistance import gold
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
def attrition(spec, as_of: date) -> dict | None:
"""The attrition of the spec's cohort; None when eligibility doesn't list that cohort."""
scenario = reports.COHORT_SCENARIOS.get(spec.cohort)
if scenario is None:
return None
rows = gold.cacu_eligibility_report(scenario, cutoff=as_of)
return reports.attrition(spec.cohort, rows, gold.people("cacu_events", as_of), as_of)
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability, attrition)
train, score = JOBS.train, JOBS.score train, score = JOBS.train, JOBS.score
+45 -4
View File
@@ -149,9 +149,20 @@ class Fit:
up[k] += step up[k] += step
down[k] -= step down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step) gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
covariance = np.nan_to_num(self.covariance, nan=0.0) free = np.isfinite(np.diag(self.covariance))
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient) variance = np.full((len(X), len(years)), np.nan)
return self.risk(X, Z, years), np.maximum(variance, 0.0) block = self.covariance[np.ix_(free, free)]
if block.size and np.isfinite(block).all() and np.allclose(block, block.T):
try:
positive = bool(np.all(np.linalg.eigvalsh(block) > 0))
except np.linalg.LinAlgError:
positive = False
if positive:
values = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free])
affected = np.any(np.abs(gradient[~free]) > 1e-10, axis=0)
valid = ~affected & np.isfinite(values) & (values >= 0)
variance[valid] = values[valid]
return self.risk(X, Z, years), variance
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
@@ -258,8 +269,38 @@ class Mixture(BaseEstimator):
point, variance = self.fits_[key].risk_with_variance( point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], self.horizons_years unique[:, :n_x], unique[:, n_x:], self.horizons_years
) )
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) 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), 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 np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
out[index[placed]] = band[inverse.ravel()] out[index[placed]] = band[inverse.ravel()]
return out return out
def variance_diagnostics(self, X: pd.DataFrame) -> dict:
"""Per stratum covariance properties and input rows without a complete interval."""
h = len(self.horizons_years)
result = []
for key, index in self._groups(X):
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())}
if f is None:
entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[])
else:
diagonal = np.diag(f.covariance)
frozen = np.flatnonzero(np.abs(f.params) >= FROZEN).tolist()
negative = np.flatnonzero(np.isfinite(diagonal) & (diagonal < 0)).tolist()
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())
except np.linalg.LinAlgError:
positive = False
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)}
+59 -1
View File
@@ -9,6 +9,8 @@ validation, is a document the clinical team adds). Both are data the governance
For the logistic regression, its coefficients and calibration by risk decile. For the logistic regression, its coefficients and calibration by risk decile.
""" """
from datetime import date
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from scipy.stats import norm from scipy.stats import norm
@@ -23,6 +25,61 @@ BOOTSTRAP = 200
SEED = 20261122 SEED = 20261122
Z = norm.ppf(0.975) Z = norm.ppf(0.975)
# The scenario of gold.cacu_eligibility that lists each cohort's candidates.
COHORT_SCENARIOS = {
"cacu_cohort_surveillance": "surveillance",
"cacu_cohort_post_colposcopy": "post_colposcopy",
"cacu_cohort_post_treatment": "post_treatment",
"cacu_cohort_survival": "survival",
}
# Reasons that a result still to arrive could lift.
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", "no_cotest": "index",
"no_index_result": "index", "unreported_biopsy": "index",
}
def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict:
"""Who a cohort lost and why, up to `as_of`. `rows`: its candidates' eligibility report (one
row per candidate and reason). A candidate with several reasons counts once in `excluded`
and once in each reason; `pending` are the excluded whose every reason awaits a result."""
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
key = ["person_id", "index_date", "index_sample_id"]
candidates = rows[key].drop_duplicates()
excluded = rows[rows["criterion"].notna()]
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
pending = int(sum(found <= AWAITING for found in reasons))
stages = excluded.assign(stage=excluded["criterion"].map(REASON_STAGE).fillna("unknown"))
return {
"cohort": cohort,
"scenario": COHORT_SCENARIOS[cohort],
"as_of": as_of.isoformat(),
"people": people,
"without_candidate": people - int(candidates["person_id"].nunique()),
"candidates": len(candidates),
"eligible": len(candidates) - len(reasons),
"excluded": len(reasons),
"pending": pending,
"by_reason": {
str(reason): int(count)
for reason, count in excluded["criterion"].value_counts().sort_index().items()
},
"by_stage": {
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_counts_overlap": True,
}
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict: def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
if isinstance(spec, survival.Spec): if isinstance(spec, survival.Spec):
@@ -72,7 +129,8 @@ def _label(feature: str, value) -> str:
def _band(curve, variance) -> tuple[list, list]: def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) 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(), return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
+8 -4
View File
@@ -2,6 +2,7 @@
the prevalence-incidence mixture or a logistic regression. Training and scoring read the the prevalence-incidence mixture or a logistic regression. Training and scoring read the
patient timelines of the spec's cohort (see features).""" patient timelines of the spec's cohort (see features)."""
import json
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Literal from typing import Literal
@@ -32,7 +33,7 @@ SURVIVAL_SCENARIOS = {
} }
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame: def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, predictors=()) -> pd.DataFrame:
"""One row per patient and horizon; patients the model can't score are left out.""" """One row per patient and horizon; patients the model can't score are left out."""
h = len(horizons) h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1) scored = ~np.isnan(risks[:, :h]).any(axis=1)
@@ -48,7 +49,10 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel() frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
else: else:
frame["ci_low"] = frame["ci_high"] = np.nan frame["ci_low"] = frame["ci_high"] = np.nan
return frame[OUTPUT] 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"]]
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -120,7 +124,7 @@ class Pim:
events = events.assign(index_date=events["person_id"].map(chosen)) events = events.assign(index_date=events["person_id"].map(chosen))
members = f.index_results(events, self.cytology, self._history()) members = f.index_results(events, self.cytology, self._history())
members = members.sort_values("person_id", kind="stable").reset_index(drop=True) members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
return _rows(members, mixture.predict(members[self.features]), self.horizons) return _rows(members, mixture.predict(members[self.features]), self.horizons, self.features)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -166,7 +170,7 @@ class Logistic:
members = f.index_sample(f.prepared(events), list(self.predictors)) members = f.index_sample(f.prepared(events), list(self.predictors))
members = members.sort_values("person_id", kind="stable").reset_index(drop=True) members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
p = model.predict_proba(members[list(self.predictors)])[:, 1] p = model.predict_proba(members[list(self.predictors)])[:, 1]
return _rows(members, p[:, None], (self.years,)) return _rows(members, p[:, None], (self.years,), self.predictors)
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
+56 -1
View File
@@ -90,6 +90,47 @@ def score():
score_models() score_models()
class CacuDevelopmentEvaluation(dg.Config):
as_of: str
max_fits: int = 100000
@dg.op
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
from core import cacu
from models.cacu import encoders, features
from models.cacu.development_selection import evaluate
from persistance import gold, registry
as_of = date.fromisoformat(config.as_of)
cohort = "cacu_cohort_surveillance"
events = gold.evidence_timelines("cacu_events", cohort, as_of)
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))
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"])
report = evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
report.update(cohort=cohort, as_of=as_of.isoformat(), outcome="CIN2+ at one year")
mlflow.set_experiment(registry.EXPERIMENT)
with mlflow.start_run(run_name="cacu.cin2_firth_development") as run:
mlflow.log_dict(report, "reports/development_evaluation.json")
context.log.info("Development evaluation logged as %s", run.info.run_id)
return run.info.run_id
@dg.job
def cacu_development_evaluation():
evaluate_cacu_development()
class Analysis(dg.Config): class Analysis(dg.Config):
domain: str domain: str
@@ -107,6 +148,19 @@ def analyze():
analyze_studies() analyze_studies()
@dg.op
def build_gold(context: dg.OpExecutionContext) -> None:
"""Silver and everything derived from it, with the deployed code: what an ingest ends
with, without ingesting (after deploying a version that changes the tables)."""
silver.build(["silver+"])
context.log.info("silver and gold rebuilt")
@dg.job(tags=WRITES)
def rebuild():
build_gold()
@dg.op @dg.op
def make_backup(context: dg.OpExecutionContext) -> str: def make_backup(context: dg.OpExecutionContext) -> str:
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay.""" """The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
@@ -131,4 +185,5 @@ nightly = (
else [] else []
) )
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly) defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup,
cacu_development_evaluation], schedules=nightly)
+18 -8
View File
@@ -24,6 +24,7 @@ from splink.clustering import cluster_pairwise_predictions_at_threshold
from core import catalog, concept_map, fhir_in from core import catalog, concept_map, fhir_in
from core.pipeline import ( from core.pipeline import (
FIELD_EVIDENCE,
HELD, HELD,
IDENTIFIERS, IDENTIFIERS,
QUOTES, QUOTES,
@@ -184,14 +185,11 @@ def run_map(p: str, node: Map):
def run_fhir(p: str, node: Fhir): def run_fhir(p: str, node: Fhir):
"""Each Bundle's rows of the node's entity; a resource sent again is its latest.""" """Resolve a sender's references across the Bundles accumulated at its source."""
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else [] maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
found: dict[str, dict] = {} stored = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or ""))
for row in nodes.rows(p, node.inputs[0]): bundle = fhir_in.combined(json.loads(row[node.column]) for row in stored)
bundle = json.loads(row[node.column]) return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps))
for r in fhir_in.rows(bundle, node.entity, p, maps):
found[r[RECORD]] = r
return nodes.write(p, node.id, list(found.values()))
def run_join(p: str, node: Join): def run_join(p: str, node: Join):
@@ -486,6 +484,7 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
linked = {r[RECORD]: r for r in nodes.rows(p, link)} linked = {r[RECORD]: r for r in nodes.rows(p, link)}
person = {k: r["person_id"] for k, r in linked.items()} person = {k: r["person_id"] for k, r in linked.items()}
model, study = catalog.model(node.entity), catalog.studies()[node.entity] model, study = catalog.model(node.entity), catalog.studies()[node.entity]
report = study.events.get("report")
fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction
observations, held_rows = [], [] observations, held_rows = [], []
for i in (i for i in node.inputs if i != link): for i in (i for i in node.inputs if i != link):
@@ -506,9 +505,20 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
continue continue
clean = model.model_validate(values) clean = model.model_validate(values)
instance = json.dumps([str(getattr(clean, k)) for k in model.key]) instance = json.dumps([str(getattr(clean, k)) for k in model.key])
evidence = json.loads(row.get(FIELD_EVIDENCE) or "{}")
for name, field in study.fields.items(): for name, field in study.fields.items():
if (value := getattr(clean, name)) is not None: if (value := getattr(clean, name)) is not None:
observations.append({**base, "instance": instance, "field": name, provenance = evidence.get(name)
if provenance is None:
event_date = getattr(clean, study.events[field.event].date)
# A dated report or note documents the values it contains.
documented = getattr(clean, report.date) if report else event_date
provenance = {
"source_ref": row[RECORD],
"source_clinical_date": str(event_date) if event_date else None,
"source_available_at": str(documented) if documented else None,
}
observations.append({**base, **provenance, "instance": instance, "field": name,
catalog.value_column(field): value}) # fmt: skip catalog.value_column(field): value}) # fmt: skip
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
+7
View File
@@ -35,6 +35,8 @@ class Jobs:
models: dict models: dict
technical_validation: Callable[..., dict] technical_validation: Callable[..., dict]
interpretability: Callable[..., dict] interpretability: Callable[..., dict]
# (spec, as_of) -> who the model's cohort lost, kept beside the reports; None: not kept
attrition: Callable[..., dict | None] | None = None
@property @property
def events(self) -> str: def events(self) -> str:
@@ -69,9 +71,14 @@ class Jobs:
"technical_validation": self.technical_validation(spec, metrics, data), "technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data), "interpretability": self.interpretability(spec, fitted, data),
} }
if hasattr(fitted, "variance_diagnostics"):
found["variance_diagnostics"] = fitted.variance_diagnostics(
data["coded"][spec.features])
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits # 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. # for its idle workers to time out (5 minutes) before it can end.
get_reusable_executor().shutdown(wait=True) get_reusable_executor().shutdown(wait=True)
if self.attrition and (lost := self.attrition(spec, as_of)) is not None:
found = {**found, "attrition": lost} # not one of the reports promotion asks for
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()} params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted) model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found) return registry.register(self.registered(name), model, params, metrics, found)
+61 -2
View File
@@ -341,7 +341,7 @@ class Spec:
masks = scenario_masks(members, self.scenarios) masks = scenario_masks(members, self.scenarios)
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
for i in range(n)] # fmt: skip for i in range(n)] # fmt: skip
return pd.DataFrame({ result = pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h), "person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h), "index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n), "horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
@@ -350,6 +350,11 @@ class Spec:
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(), "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h), "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
})[OUTPUT] # fmt: skip })[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)
return result
# ---------------------------------------------------------------- reports (curves) # ---------------------------------------------------------------- reports (curves)
@@ -430,6 +435,40 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
} # fmt: skip } # fmt: skip
def _combination_curves(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> list[dict]:
"""The curves of the members who share every covariate value, the ones a patient with those
values is shown: Kaplan-Meier, Weibull, fractional Weibull and the model's points for those
values (its bootstrap band where training saw them). Fewer than MIN_SCENARIO_EVENTS deaths:
counts and why, no curve."""
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
keys = spec._combinations(members)
intervals = getattr(model, "intervals_", {})
found = []
for values, rows in keys.groupby(list(spec.features), sort=True).indices.items():
values = values if isinstance(values, tuple) else (values,)
entry = {"valores": dict(zip(spec.features, values, strict=True)), "n": len(rows),
"fallecidos": int(event[rows].sum())} # fmt: skip
if entry["fallecidos"] < MIN_SCENARIO_EVENTS:
entry["reason"] = "insufficient_deaths"
else:
entry |= _scenario_curves(months[rows], event[rows], spec.cap_months)
point = {"S": model.survival(members.iloc[rows[:1]])[0].tolist()}
band = intervals.get(values)
if band: # kept as mortality: survival's limits are its complements, swapped
point |= {"low": [1 - v for v in band[1]], "high": [1 - v for v in band[0]]}
point["interval"] = {"available": bool(band),
"level": spec.interval_level if band else None,
"method": "bootstrap_percentile" if band else None} # fmt: skip
entry["points"] = {"COMB": point}
entry["horizons_months"] = list(spec.borders[1:])
entry["km"]["interval"] = {
"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)
return found
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a """The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
@@ -487,7 +526,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
for n, m in masks.items() if n not in drawn] # fmt: skip for n, m in masks.items() if n not in drawn] # fmt: skip
combinations = spec._combinations(train).value_counts().reset_index(name="members") combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None)) survival = model.survival(combinations.replace(UNKNOWN, None))
return { report = {
"model": spec.name, "model": spec.name,
"kind": "curves", "kind": "curves",
"curves": curves, "curves": curves,
@@ -509,6 +548,26 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS, "min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
**risk_factor_report(spec, model, members), **risk_factor_report(spec, model, members),
} }
if spec.cohort.startswith("cacu_"):
for curve in report["curves"]:
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"}
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"}
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"}
for scenario in report["escenarios_sin_curvas"]:
scenario["reason"] = "insufficient_deaths"
report["km_combinaciones"] = _combination_curves(spec, model, members)
return report
# ---------------------------------------------------------------- risk factors # ---------------------------------------------------------------- risk factors
+1
View File
@@ -24,6 +24,7 @@ dependencies = [
"edfio>=0.4.18", "edfio>=0.4.18",
"statsmodels>=0.15.0", "statsmodels>=0.15.0",
"pgmpy>=1.1.2", "pgmpy>=1.1.2",
"firthmodels>=0.8.2",
] ]
[project.optional-dependencies] [project.optional-dependencies]
+34
View File
@@ -0,0 +1,34 @@
"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once."""
from datetime import date
import pandas as pd
from models.cacu import reports
def test_a_candidate_with_two_reasons_is_excluded_once():
"""Pins the totals, the pending rule, the people without a candidate and the as-of cut."""
rows = pd.DataFrame(
[
("eligible", "2025-01-01", None, None),
("two", "2025-01-01", None, "hysterectomy"),
("two", "2025-01-01", None, "under_18"),
("waiting", "2025-01-01", None, "no_index_result"),
("waiting_and_out", "2025-01-01", None, "no_index_result"),
("waiting_and_out", "2025-01-01", None, "prior_outcome"),
("after", "2025-07-01", None, "hysterectomy"),
],
columns=["person_id", "index_date", "index_sample_id", "criterion"],
)
found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30))
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
assert (found["pending"], found["without_candidate"]) == (1, 6)
assert found["by_reason"] == {
"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1,
} # fmt: skip
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
assert found["stage_by_reason"]["no_index_result"] == "index"
assert found["stage_counts_overlap"] is True
+114
View File
@@ -0,0 +1,114 @@
import pytest
import numpy as np
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."""
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)
m, L = PG.normal_posterior(X, z, np.zeros(2), np.eye(2) * 1e-10)
assert np.allclose(m, np.linalg.lstsq(X, z, rcond=None)[0], atol=1e-6)
assert np.allclose(L @ L.T, np.linalg.inv(X.T @ X), rtol=1e-6)
def test_latent_sign_follows_g():
"""Fails if a truncated latent falls on the wrong side of zero."""
rng = np.random.default_rng(2)
g = rng.random(1000) < 0.5
z = PG.draw_latent(rng.normal(size=1000) * 3, g, rng)
assert np.all((z > 0) == 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
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)
assert out[0] == 1.0 and np.isclose(out[1], 0.2)
assert np.isclose(out[2], 0.2 * 0.3 / (0.2 * 0.3 + 0.8))
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
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
X = np.column_stack([np.ones(n), rng.random(n) < 0.4])
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)
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
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]))
assert np.isclose(out[0], 1.0)
assert np.isclose(out[1], norm.cdf(-0.2) / norm.cdf(-1.0))
assert np.isclose(out[2], norm.sf(1.3) / norm.sf(0.5))
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 %."""
rng = np.random.default_rng(seed)
abnormal = (rng.random(n) < 0.2).astype(float)
X = np.column_stack([np.ones(n), abnormal])
g = rng.random(n) < norm.cdf(X @ [-1.6, 1.2])
U = np.column_stack([np.ones(n), abnormal])
arc = 1.0 - abnormal
r = (rng.random(n) < norm.cdf(U @ [-1.8, 2.8] + 1.5 * arc * g)).astype(int)
y = np.where(r == 1, g & (rng.random(n) < 0.7), np.nan)
return X, r, y, U, arc
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
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)
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
assert abs(norm.cdf(with_arc["beta"][:, 0]).mean() - norm.cdf(-1.6)) < 0.02
assert abs(with_arc["delta"][:, -1].mean() - 1.5) < 0.3
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."""
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
def test_patterns_keep_every_woman():
"""Fails if collapsing identical women loses anyone or merges different observations."""
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))
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."""
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))
point = model.initial_point()
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))
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()
assert np.isclose(got, direct)
+83
View File
@@ -0,0 +1,83 @@
import numpy as np
import pandas as pd
import pytest
from models.cacu.development_firth import FirthFamily
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
@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])
prediction = FirthFamily(method).fit(X, y).predict_proba(X)[:, 1]
assert np.isfinite(prediction).all() and ((prediction > 0) & (prediction < 1)).all()
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'])
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]})
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)
def test_budget_rejects_large_loocv_before_fitting():
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)
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'
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
import dagster as dg
import mlflow
from mlflow.tracking._tracking_service import utils as tracking_utils
from models.cacu import development_selection, encoders, features
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())
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)
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))
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']
+129
View File
@@ -0,0 +1,129 @@
"""The binary encoders read only what was available at the index, and never turn an
absent value into 0."""
import numpy as np
import pandas as pd
import pytest
from models.cacu.encoders import FINDINGS, encode
INDEX = "2025-06-10"
def event(day, kind, code=None, person="p1", table="cervical_cytology", sample=None,
clinical=None, available=None): # fmt: skip
return {
"person_id": person, "index_date": INDEX, "date": day, "type": kind,
"value_code": code, "value_num": np.nan, "source_table": table,
"source_id": sample or day, "evidence_date": clinical, "source_available_at": available,
} # fmt: skip
def form(sample, report, person="p1", **fields):
empty = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
return {"person_id": person, "sample_date": sample, "report_date": report} | empty | fields
def row(events, forms=None, person="p1"):
found = encode(pd.DataFrame(events), None if forms is None else pd.DataFrame(forms))
return found.set_index("person_id").loc[person].drop("index_date").astype(float)
def test_nothing_known_is_all_missing():
found = row([event(INDEX, "cytology", "satisfactory")])
assert found.isna().all()
def test_values_and_missing():
found = row([
event("1980-06-11", "birth", table="person"),
event("2025-01-15", "bethesda", "LSIL", sample="2025-01-10"),
event("2025-01-15", "hpv", "positive", sample="2025-01-10"),
event("2025-01-15", "hpv_16", "negative", sample="2025-01-10"),
event(INDEX, "cervix_appearance", "lesion"),
event(INDEX, "presenting_symptom", "not-a-code"),
]) # fmt: skip
assert found["age__35-44"] == 1 and found["age__45-54"] == 0
assert found["bethesda__LSIL"] == 1 and found["bethesda__HSIL"] == 0
assert found["cytology_ascus_plus"] == 1 and found["cytology_hsil_plus"] == 0
assert found["hpv_positive"] == 1 and found["hpv_16_positive"] == 0
assert np.isnan(found["hpv_18_positive"])
# one genotype negative and the other unreported is unknown, not negative
assert np.isnan(found["hpv_16_or_18_positive"])
assert found["cervix_appearance__lesion"] == 1 and found["cervix_appearance__healthy"] == 0
assert found.filter(like="presenting_symptom").isna().all() # ambiguous value
assert found.filter(like="prior_").isna().all()
@pytest.mark.parametrize("positive, other, expected", [
("positive", None, 1.0), ("negative", "negative", 0.0), ("negative", "positive", 1.0),
]) # fmt: skip
def test_genotypes_combined(positive, other, expected):
events = [event("2025-01-15", "hpv_16", positive)]
if other:
events.append(event("2025-01-15", "hpv_18", other))
assert row(events)["hpv_16_or_18_positive"] == expected
def test_nothing_later_than_the_index_is_read():
base = [event(INDEX, "cytology", "satisfactory")]
later = [
event("2025-06-20", "bethesda", "HSIL", sample=INDEX), # the index sample's report
event("2025-06-20", "hpv", "positive", sample=INDEX),
event("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
event("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
# procedures of the index day may be the outcome
event(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
event(INDEX, "colposcopy", table="clinical_note"),
event(INDEX, "treatment", table="clinical_note"),
event("2025-08-01", "history", table="clinical_note"),
# standalone evidence without an availability date: its onset says nothing of it
event("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence"),
] # fmt: skip
forms = [form(INDEX, "2025-06-20", adequacy="unsatisfactory", finding_atrophy=True)]
pd.testing.assert_series_equal(row(base + later, forms), row(base))
def test_available_by_the_index_day_is_read():
found = row([
event("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
event("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence", available="2024-01-01"),
]) # fmt: skip
assert found["cytology_hsil_plus"] == 1 and found["history_hysterectomy"] == 1
def test_prior_procedures_and_referral():
found = row([
event("2025-01-15", "bethesda", "HSIL", sample="2025-01-10"),
event("2025-03-01", "colposcopy", table="clinical_note"),
event("2025-03-01", "biopsy_order", table="cervical_biopsy"),
event("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
]) # fmt: skip
assert found["prior_colposcopy"] == 1 and found["prior_biopsy_order"] == 1
assert found["prior_biopsy_lsil_plus"] == 1 and found["prior_biopsy_hsil_plus"] == 0
assert found["referral_high_grade"] == 1
assert np.isnan(found["prior_treatment"])
def test_form_fields_come_from_the_latest_report():
forms = [
form("2024-01-10", "2024-01-20", screening_history="never", finding_atrophy=True),
form("2025-01-10", "2025-01-20", adequacy="satisfactory", finding_candida=1),
]
found = row([event(INDEX, "cytology")], forms)
assert found["screening_history__never"] == 1
assert found["sample_unsatisfactory"] == 0 and found["finding_candida"] == 1
assert np.isnan(found["finding_atrophy"])
def test_members_are_kept_apart():
events = [event("2025-01-15", "hpv", "positive"), event(INDEX, "cytology", person="p2")]
assert np.isnan(row(events, person="p2")["hpv_positive"])
def test_a_timeline_without_availability_is_refused():
events = pd.DataFrame([event(INDEX, "cytology")]).drop(columns="source_available_at")
with pytest.raises(ValueError, match="source_available_at"):
encode(events)
+15 -1
View File
@@ -81,7 +81,11 @@ def test_predictions_match_the_current_models(name):
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"), for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip ("ci_high", "ic_alto")]: # fmt: skip
if theirs in both: if theirs in both:
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0) # 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)
if spec.method != "logistic regression": if spec.method != "logistic regression":
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all() assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
@@ -108,6 +112,7 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip "stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events) found = spec.predict(model, events)
assert all(set(json.loads(value)) == set(spec.features) for value in found['input_values'])
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet") reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"], both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
@@ -120,6 +125,15 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
monkeypatch.setattr(curves, "fit_fractional", lambda d, c, k, lam: (1.0, 1.0, lam)) monkeypatch.setattr(curves, "fit_fractional", lambda d, c, k, lam: (1.0, 1.0, lam))
with parallel_config(backend="sequential"): with parallel_config(backend="sequential"):
report = reports.interpretability(spec, model, data) report = reports.interpretability(spec, model, data)
combined = report["km_combinaciones"]
assert sum(c["n"] for c in combined) == len(pd.concat([data["train"], data["test"]]))
for c in combined:
assert set(c["valores"]) == set(spec.features)
assert ("km" in c) == (c["fallecidos"] >= survival.MIN_SCENARIO_EVENTS)
if "km" in c:
assert {"weibull", "weibull_fractional", "points"} <= set(c)
point = c["points"]["COMB"]
assert len(point["S"]) == len(c["horizons_months"]) == len(spec.borders) - 1
(scenario,) = report["escenarios"] (scenario,) = report["escenarios"]
name = scenario["escenario"] name = scenario["escenario"]
assert name == "Citología · HSIL+" assert name == "Citología · HSIL+"
+18
View File
@@ -0,0 +1,18 @@
import json
import numpy as np
import pandas as pd
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"))
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}]
+40
View File
@@ -0,0 +1,40 @@
import numpy as np
import pandas as pd
from models.cacu.pim import Fit, ISpline, Mixture
def test_unestimable_covariances_never_produce_zero_width_intervals():
baseline = ISpline((0.0, 1.0, 2.0), 2)
params = np.zeros(1 + baseline.n_params)
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)))):
broken = Fit(1, 0, baseline, params, covariance, 0, True)
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
def test_frozen_parameter_only_invalidates_horizons_it_affects():
baseline = ISpline((0.0, 1.0, 2.0), 2)
params = np.zeros(1 + baseline.n_params)
covariance = np.eye(len(params))
covariance[1, :] = np.nan
covariance[:, 1] = np.nan
fitted = Fit(1, 0, baseline, params, covariance, 0, True)
variance = fitted.risk_with_variance(np.ones((1, 1)), np.empty((1, 0)), [0, 1])[1]
assert np.isfinite(variance[0, 0])
assert np.isnan(variance[0, 1])
def test_diagnostics_count_rows_without_intervals():
baseline = ISpline((0.0, 1.0, 2.0), 2)
params = np.zeros(1 + baseline.n_params)
model = Mixture((0, 1), (), (), {})
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'