Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| aca4c9d58a | |||
| a1e2e07e0c | |||
| 17a60ff68d | |||
| efa2c2793e | |||
| 3a033efc1b | |||
| d27b585560 | |||
| 1feedad79a | |||
| da14e4ea8e | |||
| fe1f284e00 | |||
| d392cc02a5 | |||
| 8a860c698f | |||
| 6e6c5bb81b | |||
| d27319ad1f | |||
| b5480e8bbb | |||
| dbbea0b16e | |||
| 76e88d0779 | |||
| 8548eb8d9e | |||
| 1a1ea5c7a9 | |||
| 77350b8fec | |||
| a9945bc021 |
@@ -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
|
||||||
@@ -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])
|
||||||
@@ -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}
|
||||||
@@ -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)
|
||||||
@@ -115,6 +115,13 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
|||||||
key = ["person_id", "source_table", "source_id"]
|
key = ["person_id", "source_table", "source_id"]
|
||||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||||
[*key, "date"]] # fmt: skip
|
[*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()
|
||||||
|
recorded = samples["person_id"].map(hysterectomy)
|
||||||
|
samples = samples[recorded.isna() | (samples["date"] < recorded)]
|
||||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||||
has = has.reindex(columns=list(RESULTS))
|
has = has.reindex(columns=list(RESULTS))
|
||||||
|
|||||||
+14
-1
@@ -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
@@ -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
@@ -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
|
||||||
|
|
||||||
|
|||||||
+20
-6
@@ -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
|
||||||
|
|
||||||
@@ -20,9 +21,19 @@ from models.survival import Spec, age_group
|
|||||||
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
||||||
TRAIN_FRACTION = 0.7
|
TRAIN_FRACTION = 0.7
|
||||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
||||||
|
SURVIVAL_AGE_CUTS = (35, 45, 55)
|
||||||
|
SURVIVAL_SCENARIOS = {
|
||||||
|
**{
|
||||||
|
f"Edad al diagnóstico · {group} años": (("age_group", "==", group),)
|
||||||
|
for group in ("<35", "35-44", "45-54", "≥55")
|
||||||
|
},
|
||||||
|
**{f"Citología · {group}": (("cytology", "==", group),) for group in cacu.KPNC},
|
||||||
|
"VPH positivo": (("hpv", "==", "positive"),),
|
||||||
|
"VPH negativo": (("hpv", "==", "negative"),),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -38,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)
|
||||||
@@ -110,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)
|
||||||
@@ -156,14 +170,14 @@ 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:
|
||||||
"""Each member's most recent observations up to her index (that day included): her age
|
"""Each member's most recent observations up to her index (that day included): her age
|
||||||
group, the KPNC category of her latest cytology result and her latest HPV result."""
|
group, the KPNC category of her latest cytology result and her latest HPV result."""
|
||||||
found = pd.DataFrame(index=members.index)
|
found = pd.DataFrame(index=members.index)
|
||||||
found["age_group"] = age_group(events, members, (35, 45, 55))
|
found["age_group"] = age_group(events, members, SURVIVAL_AGE_CUTS)
|
||||||
prior = events[events["date"] <= events["index_date"]]
|
prior = events[events["date"] <= events["index_date"]]
|
||||||
names = list(cacu.KPNC)
|
names = list(cacu.KPNC)
|
||||||
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
||||||
@@ -200,6 +214,6 @@ MODELS = {
|
|||||||
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
||||||
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
||||||
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
||||||
interval_level=0.95),
|
interval_level=0.95, scenarios=SURVIVAL_SCENARIOS),
|
||||||
]
|
]
|
||||||
} # fmt: skip
|
} # fmt: skip
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
|
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
|
||||||
learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
|
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian
|
||||||
published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
|
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator
|
||||||
regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
|
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and
|
||||||
(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
|
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports
|
||||||
with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by
|
gives the tables and figures."""
|
||||||
four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's,
|
|
||||||
refitted on each whole horizon cohort."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
@@ -15,15 +13,7 @@ import pandas as pd
|
|||||||
|
|
||||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||||
|
|
||||||
SOURCES = ("metabric", "scanb")
|
|
||||||
HORIZONS = modeling.HORIZONS # months
|
HORIZONS = modeling.HORIZONS # months
|
||||||
SAVED = "metabric"
|
|
||||||
|
|
||||||
|
|
||||||
def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
"""The source's cohort table, from its dataset's rows: fixed columns, then its
|
|
||||||
covariates as categories."""
|
|
||||||
return cohorts.prepare(source, rows).frame
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -59,28 +49,21 @@ class Recurrence:
|
|||||||
return pd.DataFrame(out, index=X.index)
|
return pd.DataFrame(out, index=X.index)
|
||||||
|
|
||||||
|
|
||||||
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
|
||||||
"""Both reference cohorts' models, validation, calculator and risk factors, from their
|
|
||||||
datasets' rows; the saved model is METABRIC's.
|
|
||||||
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
|
|
||||||
stability criterion, are then missing)."""
|
|
||||||
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
|
|
||||||
return fit(found, SAVED, "metabric+scanb", bootstrap)
|
|
||||||
|
|
||||||
|
|
||||||
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
||||||
"""The same, on the site's own cohort (models.cama.recurrence.site)."""
|
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
|
||||||
|
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
|
||||||
|
factors' stability criterion, are then missing)."""
|
||||||
from models.cama.recurrence import site
|
from models.cama.recurrence import site
|
||||||
|
|
||||||
return fit({"site": site.prepare(rows)}, "site", "site", bootstrap)
|
return fit({"site": site.prepare(rows)}, "site", "site",
|
||||||
|
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
def fit(found: dict, saved: str, label: str,
|
def fit(found: dict, saved: str, label: str,
|
||||||
bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
||||||
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
||||||
the `saved` cohort's is the model kept."""
|
the `saved` cohort's is the model kept."""
|
||||||
sources = list(found)
|
sources = list(found)
|
||||||
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
|
|
||||||
try:
|
try:
|
||||||
fits = modeling.fit(found, n_bootstrap)
|
fits = modeling.fit(found, n_bootstrap)
|
||||||
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
||||||
|
|||||||
@@ -21,45 +21,6 @@ RESAMPLES = 200
|
|||||||
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
|
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
|
||||||
CAP_MONTHS = 72 # the Weibull curves' extent
|
CAP_MONTHS = 72 # the Weibull curves' extent
|
||||||
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
|
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
|
||||||
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"}
|
|
||||||
|
|
||||||
# Each scenario: covariate -> the categories it takes (AND across covariates).
|
|
||||||
SCENARIOS = {
|
|
||||||
"metabric": {
|
|
||||||
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
|
||||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
|
||||||
"Tamano_tumor": ["<=20 mm"]},
|
|
||||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
|
||||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
|
||||||
"< 45 años": {"Edad": ["<45"]},
|
|
||||||
"≥ 75 años": {"Edad": ["75+"]},
|
|
||||||
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
|
||||||
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
|
||||||
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
|
||||||
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
|
||||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
|
||||||
"Cirugia": ["BREAST CONSERVING"]},
|
|
||||||
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
|
||||||
},
|
|
||||||
"scanb": {
|
|
||||||
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
|
||||||
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
|
|
||||||
"Tamano_tumor": ["<=20 mm"]},
|
|
||||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
|
||||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
|
||||||
"< 45 años": {"Edad": ["<45"]},
|
|
||||||
"≥ 75 años": {"Edad": ["75+"]},
|
|
||||||
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
|
||||||
"HER2+ (luminal B HER2+ o no luminal)": {
|
|
||||||
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
|
||||||
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
|
||||||
"Luminal · 1-3 ganglios · lumpectomía": {
|
|
||||||
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
|
|
||||||
"Cirugia": ["Lumpectomy"]},
|
|
||||||
"Grado 3": {"Grado_histologico": ["3"]},
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
SCENARIOS["site"] = SCENARIOS["scanb"] # the site's cohort is described as SCAN-B's
|
|
||||||
|
|
||||||
|
|
||||||
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
||||||
@@ -143,10 +104,10 @@ def _curves(months, event, observed):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]:
|
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
|
||||||
"""The figure record of each scenario with enough recurrences, and its table rows."""
|
"""The figure record of each scenario with enough recurrences, and its table rows."""
|
||||||
source = fitted.cohort.source
|
source = fitted.cohort.source
|
||||||
scenarios = SCENARIOS[source] if scenarios is None else scenarios
|
scenarios = fitted.cohort.scenarios
|
||||||
risk = Risk(fitted)
|
risk = Risk(fitted)
|
||||||
found = masks(fitted.cohort.frame, scenarios)
|
found = masks(fitted.cohort.frame, scenarios)
|
||||||
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
|
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
|
||||||
@@ -169,7 +130,7 @@ def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[d
|
|||||||
records.append(
|
records.append(
|
||||||
{
|
{
|
||||||
"cohorte": source,
|
"cohorte": source,
|
||||||
"cohorte_nombre": LABELS[source],
|
"cohorte_nombre": fitted.cohort.label,
|
||||||
"escenario": name,
|
"escenario": name,
|
||||||
"condiciones": scenarios[name],
|
"condiciones": scenarios[name],
|
||||||
"n": n,
|
"n": n,
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
"""Each reference cohort as one table of categories, from its dataset as the platform loaded
|
"""A cohort as one table of categories: the patients with a known recurrence time and status,
|
||||||
it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
|
their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their covariates
|
||||||
`line` the order the file is published in): the patients with a known recurrence time and
|
as text. A missing or out-of-range value is a category of its own (UNKNOWN); nothing is imputed
|
||||||
status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
|
or dropped for it. Of each pair of nearly redundant covariates (Cramér's V >= V_MAX), the one
|
||||||
covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN);
|
with more unknowns is dropped."""
|
||||||
nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's
|
|
||||||
V >= V_MAX), the one with more unknowns is dropped."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
@@ -14,6 +12,7 @@ from scipy.stats.contingency import association
|
|||||||
UNKNOWN = "Desconocido"
|
UNKNOWN = "Desconocido"
|
||||||
V_MAX = 0.80
|
V_MAX = 0.80
|
||||||
DAYS_PER_MONTH = 30.4375
|
DAYS_PER_MONTH = 30.4375
|
||||||
|
HORIZONS = (12, 36, 60) # months
|
||||||
|
|
||||||
# Bands, closed on the left: [a, b).
|
# Bands, closed on the left: [a, b).
|
||||||
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
||||||
@@ -21,37 +20,6 @@ SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
|
|||||||
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
||||||
GRADES = {"1": "1", "2": "2", "3": "3"}
|
GRADES = {"1": "1", "2": "2", "3": "3"}
|
||||||
|
|
||||||
FIXED = {
|
|
||||||
"metabric": ["paciente", "tiempo_meses", "evento"],
|
|
||||||
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
|
||||||
}
|
|
||||||
TREATMENT = {
|
|
||||||
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
|
||||||
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
|
||||||
}
|
|
||||||
# Covariates taken as they come (our name: the dataset's column).
|
|
||||||
PASSTHROUGH = {
|
|
||||||
"metabric": {
|
|
||||||
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
|
||||||
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
|
|
||||||
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
|
|
||||||
"Estado_menopausico": "inferred_menopausal_state",
|
|
||||||
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
|
|
||||||
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
|
|
||||||
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
|
|
||||||
},
|
|
||||||
"scanb": {
|
|
||||||
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
|
||||||
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
|
||||||
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
|
||||||
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
|
||||||
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
|
||||||
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
|
||||||
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
|
||||||
|
|
||||||
|
|
||||||
def _number(s: pd.Series) -> pd.Series:
|
def _number(s: pd.Series) -> pd.Series:
|
||||||
return pd.to_numeric(s, errors="coerce")
|
return pd.to_numeric(s, errors="coerce")
|
||||||
@@ -66,47 +34,6 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
|
|||||||
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
||||||
|
|
||||||
|
|
||||||
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
|
||||||
|
|
||||||
|
|
||||||
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
|
||||||
d = d.reset_index(drop=True)
|
|
||||||
out = pd.DataFrame({"paciente": d["patient_id"]})
|
|
||||||
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
|
||||||
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
|
||||||
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
|
||||||
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
|
||||||
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
|
||||||
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
|
||||||
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
|
||||||
load = _number(d["mutation_count"])
|
|
||||||
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
|
||||||
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
|
||||||
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
|
||||||
for name, column in PASSTHROUGH["metabric"].items():
|
|
||||||
out[name] = _text(d[column])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
d = _in_order(rows)
|
|
||||||
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
|
||||||
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
|
||||||
out = pd.DataFrame({"paciente": d["patient_name"]})
|
|
||||||
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
|
||||||
out["evento"] = rfi.astype(int)
|
|
||||||
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
|
||||||
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
|
||||||
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
|
||||||
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
|
||||||
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
|
||||||
for name, column in PASSTHROUGH["scanb"].items():
|
|
||||||
out[name] = _text(d[column])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
||||||
table = pd.crosstab(a, b).to_numpy()
|
table = pd.crosstab(a, b).to_numpy()
|
||||||
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
||||||
@@ -143,21 +70,15 @@ class Cohort:
|
|||||||
covariates: list[str]
|
covariates: list[str]
|
||||||
treatment: list[str]
|
treatment: list[str]
|
||||||
eliminated: list[str]
|
eliminated: list[str]
|
||||||
|
label: str # as the reports name it
|
||||||
|
scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories
|
||||||
|
sampling: dict # how its patients were chosen (the MUESTREO record)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def intrinsic(self) -> list[str]:
|
def intrinsic(self) -> list[str]:
|
||||||
return [c for c in self.covariates if c not in self.treatment]
|
return [c for c in self.covariates if c not in self.treatment]
|
||||||
|
|
||||||
|
|
||||||
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
|
||||||
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
|
||||||
fixed, treatment = FIXED[source], TREATMENT[source]
|
|
||||||
covariates = [c for c in full.columns if c not in fixed]
|
|
||||||
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
|
||||||
kept = [c for c in covariates if c not in dropped]
|
|
||||||
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped)
|
|
||||||
|
|
||||||
|
|
||||||
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
||||||
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
||||||
followed past it), with `y` = recurred by then."""
|
followed past it), with `y` = recurred by then."""
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import numpy as np
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from models import factors as rated
|
from models import factors as rated
|
||||||
from models.cama.recurrence.calculator import SCENARIOS, masks
|
from models.cama.recurrence.calculator import masks
|
||||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
||||||
from models.cama.recurrence.modeling import CohortFit
|
from models.cama.recurrence.modeling import CohortFit
|
||||||
from models.factors import FREQ_MIN, ORDER
|
from models.factors import FREQ_MIN, ORDER
|
||||||
@@ -102,7 +102,7 @@ def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
|
|||||||
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
||||||
patients have (definitorios) or most have (mayoritarios)."""
|
patients have (definitorios) or most have (mayoritarios)."""
|
||||||
frame, source = fitted.cohort.frame, fitted.cohort.source
|
frame, source = fitted.cohort.frame, fitted.cohort.source
|
||||||
scenarios = SCENARIOS[source]
|
scenarios = fitted.cohort.scenarios
|
||||||
found = rated.classified(factors[factors["cohorte"] == source])
|
found = rated.classified(factors[factors["cohorte"] == source])
|
||||||
rows = []
|
rows = []
|
||||||
for name, mask in masks(frame, scenarios).items():
|
for name, mask in masks(frame, scenarios).items():
|
||||||
|
|||||||
@@ -20,10 +20,9 @@ from pgmpy.structure_score import BDeu
|
|||||||
from sklearn.metrics import roc_auc_score
|
from sklearn.metrics import roc_auc_score
|
||||||
from sklearn.model_selection import train_test_split
|
from sklearn.model_selection import train_test_split
|
||||||
|
|
||||||
from models.cama.recurrence.cohorts import Cohort, at_horizon
|
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
|
||||||
from models.factors import variable_of
|
from models.factors import variable_of
|
||||||
|
|
||||||
HORIZONS = (12, 36, 60) # months
|
|
||||||
SEED = 42
|
SEED = 42
|
||||||
TEST_SIZE = 0.3
|
TEST_SIZE = 0.3
|
||||||
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
||||||
@@ -32,7 +31,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
|
|||||||
MAX_STEPS = 200
|
MAX_STEPS = 200
|
||||||
COX_PENALIZER = 0.05
|
COX_PENALIZER = 0.05
|
||||||
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
||||||
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
|
N_BOOTSTRAP = {"site": 40}
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- logistic regression
|
# ---------------------------------------------------------------- logistic regression
|
||||||
|
|||||||
@@ -95,17 +95,6 @@ def metrics(auc: list[dict]) -> dict[str, float]:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
REFERENCE_SAMPLING = {
|
|
||||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
|
||||||
"origen": "METABRIC y SCAN-B (externas)",
|
|
||||||
}
|
|
||||||
SITE_SAMPLING = {
|
|
||||||
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
|
|
||||||
"libre de ella hasta su defunción o la fecha de corte",
|
|
||||||
"origen": "la sede (sus propias pacientes)",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
||||||
"""The five routine records a promotion reads."""
|
"""The five routine records a promotion reads."""
|
||||||
return {
|
return {
|
||||||
@@ -119,7 +108,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
|||||||
}
|
}
|
||||||
for s, c in cohorts.items()
|
for s, c in cohorts.items()
|
||||||
},
|
},
|
||||||
**(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING),
|
**next(iter(cohorts.values())).sampling,
|
||||||
},
|
},
|
||||||
"DATOS_FALTANTES": {
|
"DATOS_FALTANTES": {
|
||||||
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
||||||
|
|||||||
@@ -30,6 +30,30 @@ TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
|
|||||||
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
||||||
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
||||||
TREATMENT = ["Cirugia", *TREATMENTS]
|
TREATMENT = ["Cirugia", *TREATMENTS]
|
||||||
|
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
|
||||||
|
SCENARIOS = {
|
||||||
|
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||||
|
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
|
||||||
|
"Tamano_tumor": ["<=20 mm"]},
|
||||||
|
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||||
|
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||||
|
"< 45 años": {"Edad": ["<45"]},
|
||||||
|
"≥ 75 años": {"Edad": ["75+"]},
|
||||||
|
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
||||||
|
"HER2+ (luminal B HER2+ o no luminal)": {
|
||||||
|
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
||||||
|
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
||||||
|
"Luminal · 1-3 ganglios · lumpectomía": {
|
||||||
|
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
|
||||||
|
"Cirugia": ["Lumpectomy"]},
|
||||||
|
"Grado 3": {"Grado_histologico": ["3"]},
|
||||||
|
} # fmt: skip
|
||||||
|
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted
|
||||||
|
SAMPLING = {
|
||||||
|
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
|
||||||
|
"libre de ella hasta su defunción o la fecha de corte",
|
||||||
|
"origen": "la sede (sus propias pacientes)",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def subtype(er, pr, her2, ki67) -> str:
|
def subtype(er, pr, her2, ki67) -> str:
|
||||||
@@ -97,6 +121,18 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
|||||||
return out.reset_index(drop=True)
|
return out.reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def scarce(rows: pd.DataFrame) -> str | None:
|
||||||
|
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
|
||||||
|
patients recurred by it, or known free of it), or None."""
|
||||||
|
for h in cohorts.HORIZONS:
|
||||||
|
y = cohorts.at_horizon(rows, h)["y"]
|
||||||
|
fewest = min(int(y.sum()), int((y == 0).sum()))
|
||||||
|
if fewest < MIN_PER_CLASS:
|
||||||
|
return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, "
|
||||||
|
f"{MIN_PER_CLASS} of each needed") # fmt: skip
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def prepare(rows: pd.DataFrame) -> Cohort:
|
def prepare(rows: pd.DataFrame) -> Cohort:
|
||||||
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
|
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
|
||||||
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
|
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
|
||||||
@@ -106,4 +142,5 @@ def prepare(rows: pd.DataFrame) -> Cohort:
|
|||||||
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
|
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
|
||||||
kept = [c for c in covariates if c not in dropped]
|
kept = [c for c in covariates if c not in dropped]
|
||||||
treatment = [c for c in TREATMENT if c in kept]
|
treatment = [c for c in TREATMENT if c in kept]
|
||||||
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped)
|
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
|
||||||
|
SCENARIOS, SAMPLING) # fmt: skip
|
||||||
|
|||||||
@@ -9,8 +9,7 @@
|
|||||||
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
|
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
|
||||||
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
|
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
|
||||||
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
|
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
|
||||||
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py); slow (its bootstraps
|
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
|
||||||
take minutes), so it trains only when asked for by name."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import date
|
from datetime import date
|
||||||
@@ -96,15 +95,18 @@ class SiteRecurrence:
|
|||||||
|
|
||||||
name: str
|
name: str
|
||||||
cohort: str = "cama_cohort_recurrence"
|
cohort: str = "cama_cohort_recurrence"
|
||||||
slow: bool = True
|
|
||||||
reports: bool = True # it writes its own reports (models.jobs)
|
reports: bool = True # it writes its own reports (models.jobs)
|
||||||
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
||||||
|
|
||||||
def train(self, events, as_of=None) -> tuple:
|
def train(self, events, as_of=None) -> tuple:
|
||||||
from models.cama import recurrence
|
from models.cama import recurrence
|
||||||
from models.cama.recurrence import site
|
from models.cama.recurrence import site
|
||||||
|
from models.jobs import EmptyCohort
|
||||||
|
|
||||||
return recurrence.train_site(site.frame(events, as_of or date.today()))
|
rows = site.frame(events, as_of or date.today())
|
||||||
|
if reason := site.scarce(rows):
|
||||||
|
raise EmptyCohort(f"cama.recurrence: {reason}")
|
||||||
|
return recurrence.train_site(rows)
|
||||||
|
|
||||||
def predict(self, model, events) -> pd.DataFrame:
|
def predict(self, model, events) -> pd.DataFrame:
|
||||||
from models.cama.recurrence import calculator, site
|
from models.cama.recurrence import calculator, site
|
||||||
@@ -112,7 +114,7 @@ class SiteRecurrence:
|
|||||||
members = site.frame(events, date.today())
|
members = site.frame(events, date.today())
|
||||||
found = model.predict(members)
|
found = model.predict(members)
|
||||||
index = events.groupby("person_id")["index_date"].first()
|
index = events.groupby("person_id")["index_date"].first()
|
||||||
masks = calculator.masks(members, calculator.SCENARIOS["site"])
|
masks = calculator.masks(members, site.SCENARIOS)
|
||||||
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
||||||
for i in range(len(members))] # fmt: skip
|
for i in range(len(members))] # fmt: skip
|
||||||
rows = []
|
rows = []
|
||||||
|
|||||||
+57
-2
@@ -43,7 +43,7 @@ def _jobs(domain: str):
|
|||||||
|
|
||||||
class Training(dg.Config):
|
class Training(dg.Config):
|
||||||
domain: str
|
domain: str
|
||||||
models: list[str] = [] # default: every model of the domain but the slow ones
|
models: list[str] = [] # default: every model of the domain
|
||||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||||
|
|
||||||
|
|
||||||
@@ -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)
|
||||||
|
|||||||
+22
-9
@@ -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):
|
||||||
@@ -425,6 +423,9 @@ def run_link(p: str, node: Link):
|
|||||||
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
|
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
|
||||||
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
|
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
|
||||||
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
|
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
|
||||||
|
# Answers are kept by record; a person is known by any of hers, whatever joined since.
|
||||||
|
whose = persons.set_index("unique_id")["cluster_id"].to_dict()
|
||||||
|
answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
|
||||||
lone = set() # persons whose identifier is carried by one record only
|
lone = set() # persons whose identifier is carried by one record only
|
||||||
for f in ids:
|
for f in ids:
|
||||||
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
||||||
@@ -439,7 +440,7 @@ def run_link(p: str, node: Link):
|
|||||||
very same identifier on a record that says nothing else (a scan read only in part)."""
|
very same identifier on a record that says nothing else (a scan read only in part)."""
|
||||||
a, b = r.unique_id_l, r.unique_id_r
|
a, b = r.unique_id_l, r.unique_id_r
|
||||||
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||||
if frozenset((a, b)) in decided or any(
|
if frozenset((a, b)) in answered or any(
|
||||||
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
||||||
):
|
):
|
||||||
return None
|
return None
|
||||||
@@ -483,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):
|
||||||
@@ -503,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)
|
||||||
|
|||||||
+11
-9
@@ -35,18 +35,19 @@ 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:
|
||||||
return f"{self.domain}_events"
|
return f"{self.domain}_events"
|
||||||
|
|
||||||
def routine(self) -> list[str]:
|
def routine(self) -> list[str]:
|
||||||
"""The models a train run takes when none is named: all but the slow ones."""
|
"""The models a train run takes when none is named: all of them."""
|
||||||
return [n for n, s in self.models.items() if not getattr(s, "slow", False)]
|
return list(self.models)
|
||||||
|
|
||||||
def scored(self) -> list[str]:
|
def scored(self) -> list[str]:
|
||||||
"""The models a score run takes when none is named: all of them (only training is
|
"""The models a score run takes when none is named: all of them."""
|
||||||
slow)."""
|
|
||||||
return list(self.models)
|
return list(self.models)
|
||||||
|
|
||||||
def registered(self, name: str) -> str:
|
def registered(self, name: str) -> str:
|
||||||
@@ -56,9 +57,7 @@ class Jobs:
|
|||||||
"""A new registered version of the model, trained on its cohort's timelines up to
|
"""A new registered version of the model, trained on its cohort's timelines up to
|
||||||
`as_of` (default: today), with its metrics and its two generated reports."""
|
`as_of` (default: today), with its metrics and its two generated reports."""
|
||||||
spec, as_of = self.models[name], as_of or date.today()
|
spec, as_of = self.models[name], as_of or date.today()
|
||||||
if spec.cohort is None: # trained on reference data: it writes its own reports
|
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
||||||
fitted, metrics, found = spec.train(None, as_of)
|
|
||||||
elif getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
|
||||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||||
if events.empty:
|
if events.empty:
|
||||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||||
@@ -72,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)
|
||||||
@@ -82,8 +86,6 @@ class Jobs:
|
|||||||
def score(self, name: str) -> int | None:
|
def score(self, name: str) -> int | None:
|
||||||
"""The champion's risks for today's members of the model's cohort, saved as its risk
|
"""The champion's risks for today's members of the model's cohort, saved as its risk
|
||||||
batch; None when the model has no champion yet."""
|
batch; None when the model has no champion yet."""
|
||||||
if self.models[name].cohort is None: # scores no patient
|
|
||||||
return None
|
|
||||||
found = registry.champion(self.registered(name))
|
found = registry.champion(self.registered(name))
|
||||||
if found is None:
|
if found is None:
|
||||||
return None
|
return None
|
||||||
|
|||||||
+61
-2
@@ -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
|
||||||
|
|||||||
@@ -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]
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a
|
||||||
|
`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written,
|
||||||
|
column names as dlt names them, `line` the order the file is published in)."""
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from models.cama import recurrence
|
||||||
|
from models.cama.recurrence import site
|
||||||
|
from models.cama.recurrence.cohorts import (
|
||||||
|
AGE,
|
||||||
|
DAYS_PER_MONTH,
|
||||||
|
GRADES,
|
||||||
|
NODES,
|
||||||
|
SIZE,
|
||||||
|
Cohort,
|
||||||
|
_band,
|
||||||
|
_number,
|
||||||
|
_text,
|
||||||
|
collinear,
|
||||||
|
)
|
||||||
|
|
||||||
|
SOURCES = ("metabric", "scanb")
|
||||||
|
SAVED = "metabric"
|
||||||
|
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
|
||||||
|
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
|
||||||
|
SAMPLING = {
|
||||||
|
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
||||||
|
"origen": "METABRIC y SCAN-B (externas)",
|
||||||
|
}
|
||||||
|
SCENARIOS = {
|
||||||
|
"metabric": {
|
||||||
|
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||||
|
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
||||||
|
"Tamano_tumor": ["<=20 mm"]},
|
||||||
|
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||||
|
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||||
|
"< 45 años": {"Edad": ["<45"]},
|
||||||
|
"≥ 75 años": {"Edad": ["75+"]},
|
||||||
|
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
||||||
|
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
||||||
|
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
||||||
|
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
||||||
|
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
||||||
|
"Cirugia": ["BREAST CONSERVING"]},
|
||||||
|
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
||||||
|
},
|
||||||
|
"scanb": site.SCENARIOS,
|
||||||
|
} # fmt: skip
|
||||||
|
FIXED = {
|
||||||
|
"metabric": ["paciente", "tiempo_meses", "evento"],
|
||||||
|
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
||||||
|
}
|
||||||
|
TREATMENT = {
|
||||||
|
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
||||||
|
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
||||||
|
}
|
||||||
|
# Covariates taken as they come (our name: the dataset's column).
|
||||||
|
PASSTHROUGH = {
|
||||||
|
"metabric": {
|
||||||
|
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
||||||
|
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
|
||||||
|
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
|
||||||
|
"Estado_menopausico": "inferred_menopausal_state",
|
||||||
|
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
|
||||||
|
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
|
||||||
|
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
|
||||||
|
},
|
||||||
|
"scanb": {
|
||||||
|
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
||||||
|
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
||||||
|
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
||||||
|
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
||||||
|
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
||||||
|
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
||||||
|
},
|
||||||
|
} # fmt: skip
|
||||||
|
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
||||||
|
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
||||||
|
|
||||||
|
|
||||||
|
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
||||||
|
d = d.reset_index(drop=True)
|
||||||
|
out = pd.DataFrame({"paciente": d["patient_id"]})
|
||||||
|
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
||||||
|
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
||||||
|
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
||||||
|
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
||||||
|
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
||||||
|
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
||||||
|
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
||||||
|
load = _number(d["mutation_count"])
|
||||||
|
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
||||||
|
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
||||||
|
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
||||||
|
for name, column in PASSTHROUGH["metabric"].items():
|
||||||
|
out[name] = _text(d[column])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
d = _in_order(rows)
|
||||||
|
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
||||||
|
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
||||||
|
out = pd.DataFrame({"paciente": d["patient_name"]})
|
||||||
|
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
||||||
|
out["evento"] = rfi.astype(int)
|
||||||
|
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
||||||
|
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
||||||
|
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
||||||
|
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
||||||
|
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
||||||
|
for name, column in PASSTHROUGH["scanb"].items():
|
||||||
|
out[name] = _text(d[column])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
||||||
|
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
||||||
|
fixed, treatment = FIXED[source], TREATMENT[source]
|
||||||
|
covariates = [c for c in full.columns if c not in fixed]
|
||||||
|
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
||||||
|
kept = [c for c in covariates if c not in dropped]
|
||||||
|
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped,
|
||||||
|
LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple:
|
||||||
|
"""Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept."""
|
||||||
|
found = {s: prepare(s, raws[s]) for s in SOURCES}
|
||||||
|
return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
@@ -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']
|
||||||
@@ -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)
|
||||||
@@ -13,7 +13,10 @@ from pathlib import Path
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
from joblib import parallel_config
|
||||||
|
|
||||||
|
from models import curves, survival
|
||||||
|
from models.cacu import reports
|
||||||
from models.cacu.specs import MODELS
|
from models.cacu.specs import MODELS
|
||||||
|
|
||||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
||||||
@@ -78,12 +81,16 @@ 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()
|
||||||
|
|
||||||
|
|
||||||
def test_survival_matches_the_current_model_with_its_index_fixed():
|
def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monkeypatch):
|
||||||
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
|
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
|
||||||
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
|
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
|
||||||
that fixed); out: no birth date, a death by the biopsy."""
|
that fixed); out: no birth date, a death by the biopsy."""
|
||||||
@@ -99,12 +106,13 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
|||||||
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
|
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
|
||||||
events = events.merge(index, left_on="person_id", right_index=True)
|
events = events.merge(index, left_on="person_id", right_index=True)
|
||||||
|
|
||||||
model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
model, metrics, data = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
||||||
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
||||||
for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m",
|
for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m",
|
||||||
"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
|
||||||
@@ -113,6 +121,29 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
|||||||
("ci_high", "ic_alto")]: # fmt: skip
|
("ci_high", "ic_alto")]: # fmt: skip
|
||||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
|
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
|
||||||
|
|
||||||
|
monkeypatch.setattr(survival, "BOOTSTRAP", 3)
|
||||||
|
monkeypatch.setattr(curves, "fit_fractional", lambda d, c, k, lam: (1.0, 1.0, lam))
|
||||||
|
with parallel_config(backend="sequential"):
|
||||||
|
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"]
|
||||||
|
name = scenario["escenario"]
|
||||||
|
assert name == "Citología · HSIL+"
|
||||||
|
assert scenario["horizons_months"] == [12, 36, 60]
|
||||||
|
km = scenario["km"]
|
||||||
|
assert km["months"] and len(km["months"]) == len(km["low"]) == len(km["high"])
|
||||||
|
scored = found.drop_duplicates("person_id")
|
||||||
|
assert scored["scenarios"].str.contains(name, regex=False, na=False).sum() == scenario["n"]
|
||||||
|
assert "VPH negativo" in {row["escenario"] for row in report["escenarios_sin_curvas"]}
|
||||||
|
|
||||||
|
|
||||||
def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch):
|
def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch):
|
||||||
"""A site with no colposcopies has nobody in the post-colposcopy cohort: training that
|
"""A site with no colposcopies has nobody in the post-colposcopy cohort: training that
|
||||||
|
|||||||
@@ -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}]
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""A reviewer's "they are different people" is about the persons: it holds when more records
|
||||||
|
join one of them, whichever record the person is known by afterwards."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
PEOPLE = [("1001", "ANA LOPEZ RUIZ", "1980-01-01"), ("2002", "BEATRIZ MORA DIAZ", "1980-01-01")]
|
||||||
|
PEOPLE += [(f"9{k:03d}", f"PERSONA {k} DE RELLENO", f"19{50 + k}-0{1 + k % 9}-11")
|
||||||
|
for k in range(30)] # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def graph(db) -> dict:
|
||||||
|
fields = {"record_number": "num", "full_name": "nombre", "birth_date": "nac", "nss": "nss"}
|
||||||
|
return {"nodes": [
|
||||||
|
{"id": "people", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
|
||||||
|
"args": {"credentials": f"sqlite:///{db}", "table": "people"}},
|
||||||
|
{"id": "identity", "kind": "map", "inputs": ["people"], "fields": fields},
|
||||||
|
{"id": "persons", "kind": "link", "inputs": ["identity"], "fields": list(fields)},
|
||||||
|
]} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def insert(db, rows) -> None:
|
||||||
|
with sqlite3.connect(db) as con:
|
||||||
|
con.execute(
|
||||||
|
"create table if not exists people "
|
||||||
|
"(id integer primary key, num text, nombre text, nac text, nss text)"
|
||||||
|
)
|
||||||
|
con.executemany("insert into people (num, nombre, nac, nss) values (?, ?, ?, ?)", rows)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_answer_outlives_the_record_a_person_was_known_by(platform, tmp_path):
|
||||||
|
db, drawn = tmp_path / "people.db", tmp_path / "pipeline.json"
|
||||||
|
insert(db, [(*p, None) for p in PEOPLE])
|
||||||
|
drawn.write_text(json.dumps(graph(db)))
|
||||||
|
platform.save("pipelines", "site", drawn)
|
||||||
|
platform.ingest()
|
||||||
|
queue = "select person, candidate from bronze.n__site__persons__review"
|
||||||
|
((a, b),) = platform.query(queue)
|
||||||
|
platform.run("python", "-c", "from persistance import nodes; "
|
||||||
|
f"nodes.decide_persons({a!r}, {b!r}, False, 'reviewer')") # fmt: skip
|
||||||
|
platform.ingest()
|
||||||
|
assert platform.query(queue) == []
|
||||||
|
|
||||||
|
# Forty more documents of each woman: whichever of her records her person was known by,
|
||||||
|
# one of these is (almost surely) it now.
|
||||||
|
insert(db, [(num, None, None, f"{num}{k:07d}") for num in ("1001", "2002") for k in range(40)])
|
||||||
|
platform.ingest()
|
||||||
|
lowest = "select min(_record) from bronze.n__site__persons where record_number = '{}'"
|
||||||
|
known = {platform.query(lowest.format(n))[0][0] for n in ("1001", "2002")}
|
||||||
|
assert known != {a, b}
|
||||||
|
assert platform.query(queue) == []
|
||||||
@@ -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'
|
||||||
+11
-11
@@ -25,6 +25,7 @@ from pathlib import Path
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
import recurrence_reference as reference
|
||||||
from joblib.externals.loky import get_reusable_executor
|
from joblib.externals.loky import get_reusable_executor
|
||||||
from scipy.special import gammaln
|
from scipy.special import gammaln
|
||||||
|
|
||||||
@@ -71,14 +72,14 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
|
|||||||
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
||||||
out = folder / "datasets.pkl"
|
out = folder / "datasets.pkl"
|
||||||
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
||||||
"from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows("
|
f"pd.to_pickle({{s: pd.DataFrame(nodes.rows('cama_reference', s)) "
|
||||||
f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip
|
f"for s in {reference.SOURCES!r}}}, {str(out)!r})") # fmt: skip
|
||||||
return pd.read_pickle(out)
|
return pd.read_pickle(out)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def prepared(raws):
|
def prepared(raws):
|
||||||
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
|
return {s: reference.prepare(s, raw) for s, raw in raws.items()}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
@@ -155,7 +156,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
|
|||||||
# ---------------------------------------------------------------- fast
|
# ---------------------------------------------------------------- fast
|
||||||
|
|
||||||
|
|
||||||
def test_cohorts(prepared, raws):
|
def test_cohorts(prepared):
|
||||||
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
|
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
|
||||||
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
|
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
|
||||||
for source, c in prepared.items():
|
for source, c in prepared.items():
|
||||||
@@ -164,18 +165,17 @@ def test_cohorts(prepared, raws):
|
|||||||
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
||||||
assert c.covariates == list(missing[source])
|
assert c.covariates == list(missing[source])
|
||||||
assert cohorts.unknown_shares(c) == missing[source]
|
assert cohorts.unknown_shares(c) == missing[source]
|
||||||
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
|
|
||||||
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
||||||
|
|
||||||
|
|
||||||
def test_routines(prepared):
|
def test_routines(prepared):
|
||||||
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
|
found = reports.routines(prepared, reference.N_BOOTSTRAP)
|
||||||
for name, record in found.items():
|
for name, record in found.items():
|
||||||
assert record == _json(f"rutinas/{name}.json"), name
|
assert record == _json(f"rutinas/{name}.json"), name
|
||||||
|
|
||||||
|
|
||||||
def test_c_index_and_internal_auc(fits):
|
def test_c_index_and_internal_auc(fits):
|
||||||
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
|
rows = [r for s in reference.SOURCES for r in reports.auc_rows(fits[s])]
|
||||||
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
||||||
metrics = reports.metrics(rows)
|
metrics = reports.metrics(rows)
|
||||||
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
||||||
@@ -206,7 +206,7 @@ def test_saved_model(fits):
|
|||||||
def test_calculator(fits):
|
def test_calculator(fits):
|
||||||
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
||||||
records, rows = [], []
|
records, rows = [], []
|
||||||
for source in recurrence.SOURCES:
|
for source in reference.SOURCES:
|
||||||
found = calculator.calculator(fits[source])
|
found = calculator.calculator(fits[source])
|
||||||
records += found[0]
|
records += found[0]
|
||||||
rows += found[1]
|
rows += found[1]
|
||||||
@@ -220,12 +220,12 @@ def test_calculator(fits):
|
|||||||
def test_risk_factors(fits):
|
def test_risk_factors(fits):
|
||||||
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
||||||
table = pd.concat(
|
table = pd.concat(
|
||||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
|
[factors.risk_factors(fits[s], _reference_selection(s)) for s in reference.SOURCES],
|
||||||
ignore_index=True,
|
ignore_index=True,
|
||||||
)
|
)
|
||||||
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
||||||
FACTOR_TOLERANCE) # fmt: skip
|
FACTOR_TOLERANCE) # fmt: skip
|
||||||
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
summary = [r for s in reference.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||||
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
||||||
|
|
||||||
|
|
||||||
@@ -262,7 +262,7 @@ def test_fractional_weibull_solver_matches_the_series():
|
|||||||
@pytest.mark.slow
|
@pytest.mark.slow
|
||||||
@slow
|
@slow
|
||||||
def test_train_reproduces_v1(raws):
|
def test_train_reproduces_v1(raws):
|
||||||
model, metrics, found = recurrence.train(raws, bootstrap=True)
|
model, metrics, found = reference.train(raws, bootstrap=True)
|
||||||
assert metrics == VERSION["metrics"]
|
assert metrics == VERSION["metrics"]
|
||||||
for h in recurrence.HORIZONS:
|
for h in recurrence.HORIZONS:
|
||||||
mine = model.tables[h]
|
mine = model.tables[h]
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ FIELDS = {
|
|||||||
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
||||||
"eeg": ("study_date", "lab_record_id", "edf"),
|
"eeg": ("study_date", "lab_record_id", "edf"),
|
||||||
} # fmt: skip
|
} # fmt: skip
|
||||||
BOOLS = {"hpv", "hpv_16", "hpv_18"}
|
BOOLS = {f for s in catalog.studies().values() for f, d in s.fields.items() if d.type == "boolean"}
|
||||||
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user