Compare commits

...

31 Commits

Author SHA1 Message Date
edgar 17a60ff68d Añadir diagnóstico NUTS sintético opcional 2026-12-03 01:00:04 -06:00
edgar efa2c2793e Omitir la prueba que requiere PyMC cuando no está instalado 2026-12-03 00:55:50 -06:00
edgar 3a033efc1b Incorporar base bayesiana de investigación 2026-12-03 00:47:02 -06:00
edgar d27b585560 Evaluar regresiones de desarrollo con selección anidada 2026-12-03 00:44:47 -06:00
edgar 1feedad79a Agregar codificadores binarios de las variables CaCu a la fecha índice 2026-12-02 23:59:02 -06:00
edgar da14e4ea8e Publicar Kaplan-Meier por combinación de valores en supervivencia CaCu 2026-12-02 23:20:50 -06:00
edgar fe1f284e00 Guardar variables usadas en cada predicción 2026-12-02 23:13:55 -06:00
edgar d392cc02a5 Informar intervalos PIM no estimables 2026-12-02 23:04:01 -06:00
edgar 8a860c698f Declarar intervalos y motivos en curvas CaCu 2026-12-02 21:59:04 -06:00
edgar 6e6c5bb81b Contar etapas de descarte en cohortes CaCu 2026-12-02 21:59:04 -06:00
edgar d27319ad1f Agregar el job que reconstruye silver y gold sin ingerir 2026-12-02 21:57:33 -06:00
edgar b5480e8bbb Guardar la deserción de cada cohorte CaCu junto al modelo entrenado 2026-12-02 17:03:54 -06:00
edgar dbbea0b16e Conservar las fechas y referencias de origen en la ingesta FHIR 2026-12-02 15:38:09 -06:00
edgar 76e88d0779 Agregar curvas de supervivencia por grupo en CaCu 2026-12-02 09:35:36 -06:00
edgar 8548eb8d9e Aplicar la exclusión por histerectomía al seleccionar la citología 2026-12-02 09:35:25 -06:00
Roberto Treviño 1a1ea5c7a9 The silver test reads booleans from the catalog 2026-11-30 23:31:53 -06:00
Roberto Treviño 77350b8fec A reviewer's answer holds when more records join a person 2026-11-30 02:14:13 -06:00
Roberto Treviño a9945bc021 A training run takes every model; the public cohorts' code lives with the tests 2026-11-29 21:12:17 -06:00
Roberto Treviño 3a749ba8d1 A nightly Dagster job backs up the data folder 2026-11-29 12:38:56 -06:00
Roberto Treviño f369e8f2eb Survival rates its scenarios' risk factors as Luis's code does; recurrence shares the factor code 2026-11-29 12:38:56 -06:00
Roberto Treviño f3f79831bf Each domain's jobs name the models a score run takes 2026-11-29 07:03:08 -06:00
Roberto Treviño 43207fa3a5 Scoring runs every champion, slow models too 2026-11-29 06:43:08 -06:00
Roberto Treviño 7e8e8b44d8 Silver checks the site's recurrences and positive nodes 2026-11-29 01:50:23 -06:00
Roberto Treviño 5c781f2a52 The recurrence report names the site's own cohort 2026-11-29 01:20:40 -06:00
Roberto Treviño 8e9da2c73a The site cohort keeps redundant covariates for its scenarios 2026-11-29 00:41:24 -06:00
Roberto Treviño 53e6f77c9e Every model trains on the site: EEG age curves on the children with TEA ruled out, recurrence on the site's patients (St. Gallen subtype), and the EEG–ADOS-2 association 2026-11-28 21:28:36 -06:00
Roberto Treviño 924f662a21 Survival scores name the report's clinical scenarios each patient falls in 2026-11-28 09:29:59 -06:00
Roberto Treviño 1a46a5ba73 Link each distinct identity once, not every pair of a patient's records 2026-11-28 01:17:40 -06:00
Roberto Treviño 61eb3a30d0 Read works through files a batch at a time and keeps each batch 2026-11-27 22:29:23 -06:00
Roberto Treviño 0c78f8cf7d OCR only on the pages without text; otherwise routes; batches on Dask through its own API 2026-11-27 19:17:49 -06:00
Roberto Treviño 385cc5b80b Read keeps the file and says its format; extract takes fields from columns; EEG batches carry their recording, on Dask where it is installed 2026-11-27 16:25:01 -06:00
44 changed files with 3036 additions and 516 deletions
+38
View File
@@ -0,0 +1,38 @@
# 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.
## Diagnóstico sintético NUTS
El extra opcional `models[bayes]` instala PyMC y ArviZ; no se habilita en
la imagen habitual. En un entorno de desarrollo con ese extra se puede
generar un artefacto JSON aislado con:
```python
from models.cacu.bayes_development.synthetic_diagnostics import evaluate
evaluate("/tmp/diagnostico-bayes.json")
```
El generador usa únicamente datos simulados y el modelo transversal de
prevalencia original, no lee gold ni MLflow y no publica predicciones. El
artefacto incluye R-hat, ESS bulk/tail, divergencias, valores verdaderos,
intervalos y errores de recuperación. La comparación con el PIM actual se
marca como no comparable porque no comparten verosimilitud ni estimando.
Esta prueba no valida el modelo longitudinal ni su uso clínico.
@@ -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,51 @@
"""NUTS diagnostics on synthetic prevalence only; no patient or registry access."""
import json
from pathlib import Path
import numpy as np
from scipy.stats import norm
from models.cacu.bayes_development import prevalence_gibbs
def evaluate(path, *, seed=2026, n=300, draws=500, tune=500):
"""Write an isolated JSON artifact; the fitted model is not a longitudinal PIM."""
import arviz as az
import pymc as pm
rng = np.random.default_rng(seed)
truth = np.array([-1.2, 0.7])
kappa = 0.7
X = np.column_stack([np.ones(n), rng.integers(0, 2, n)])
disease = rng.random(n) < norm.cdf(X @ truth)
r = rng.binomial(1, 0.7, n)
y = np.where(r == 1, disease & (rng.random(n) < kappa), np.nan)
model = prevalence_gibbs.pymc_model(X, r, y, np.zeros(2), np.eye(2) * 4,
kappa_ab=(7000, 3000))
with model:
trace = pm.sample(draws=draws, tune=tune, chains=2, cores=1, random_seed=seed,
progressbar=False, compute_convergence_checks=False)
summary = az.summary(trace, var_names=['beta', 'kappa'], kind='all')
parameters = {}
for name, expected in [('beta[0]', truth[0]), ('beta[1]', truth[1]), ('kappa', kappa)]:
row = summary.loc[name]
samples = trace.posterior['kappa'].values if name == 'kappa' else trace.posterior['beta'].values[..., int(name[5])]
low, high = np.quantile(samples, [0.025, 0.975])
parameters[name] = {
'truth': float(expected), 'mean': float(row['mean']),
'error': float(row['mean'] - expected), 'interval_95': [float(low), float(high)],
'covers_truth': bool(low <= expected <= high), 'rhat': float(row['r_hat']),
'ess_bulk': float(row['ess_bulk']), 'ess_tail': float(row['ess_tail']),
}
result = {
'scope': 'synthetic_cross_sectional_prevalence_only', 'seed': seed, 'n': n,
'draws_per_chain': draws, 'tune_per_chain': tune, 'chains': 2,
'divergences': int(trace.sample_stats['diverging'].values.sum()),
'parameters': parameters,
'current_pim_comparison': {'status': 'not_comparable', 'reason':
'The prevalence probit model and the current interval-censored incidence PIM '
'do not have the same likelihood or estimand.'},
}
Path(path).write_text(json.dumps(result, indent=2, allow_nan=False) + '\n')
return result
+83
View File
@@ -0,0 +1,83 @@
"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
import warnings
import numpy as np
from scipy.optimize import brentq
from scipy.special import expit
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.exceptions import ConvergenceWarning
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
class ConvergenceError(RuntimeError):
"""Raised when the remaining Newton step fails the convergence check."""
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
"""Fit logistic regression and return the fitted solver and leverages.
Check the remaining Newton step directly because numerical precision can
affect the solver's convergence flag.
"""
y = np.asarray(y)
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
y = y.astype(int, copy=False)
from firthmodels import FirthLogisticRegression
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
X, y, sample_weight=sample_weight
)
design = np.column_stack([np.ones(len(y)), X])
weights = np.ones(len(y)) if sample_weight is None else sample_weight
p = expit(model.intercept_ + X @ model.coef_)
w = weights * p * (1 - p)
info = design.T @ (w[:, None] * design)
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
step = np.abs(np.linalg.solve(info, score)).max()
if not np.isfinite(step) or step >= 1e-4:
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
return model, h
class FirthFamily(ClassifierMixin, BaseEstimator):
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
def __init__(self, method="firth"):
self.method = method
def fit(self, X, y):
"""Fit the selected method to a binary outcome."""
if self.method not in ("firth", "flic", "flac"):
raise ValueError(f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'.")
X = np.asarray(X, float)
firth, h = solve_logistic(X, y)
y = np.asarray(y, int)
self.classes_ = np.array([0, 1])
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
if self.method == "flic":
eta = X @ self.coef_
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
elif self.method == "flac":
# Pseudo-observations use both outcomes, each with half the leverage.
g = np.repeat([0, 1, 1], len(y))
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
self.y_aug_ = np.concatenate([y, y, 1 - y])
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
# Predict on original observations, where the indicator is zero.
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
return self
def predict_proba(self, X):
"""Return probabilities for classes 0 and 1 in that order."""
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
return np.column_stack([1 - p, p])
+142
View File
@@ -0,0 +1,142 @@
"""Nested, exhaustive evaluation of a bounded set of CaCu binary encoders.
Development only. Selection, coverage screening, rank checks and imputation use training
partitions only. Methods follow edgar/camodels commit 2392d54fd4a3942b56dae803906586bc65600728.
"""
import itertools
import math
import time
import numpy as np
import pandas as pd
from scipy.special import expit, logit
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
from models.cacu.development_firth import FirthFamily
METHODS = ('firth', 'flic', 'flac')
def _candidates(X, coverage, limit):
eligible = []
for name in sorted(X.columns):
col = pd.to_numeric(X[name], errors='coerce')
known = col.dropna()
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
eligible.append((name, col.notna().mean()))
# Perfectly identical or complementary observed columns are not distinguishable.
chosen = []
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
a = X[name]
if any(((a == X[other]) | (a.isna() & X[other].isna())).all() or
((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
for other in chosen):
continue
chosen.append(name)
if len(chosen) == limit:
break
return chosen
def _matrix(train, test, columns):
tr = train[list(columns)].to_numpy(dtype=float)
te = test[list(columns)].to_numpy(dtype=float)
if tr.shape[1] and np.isnan(tr).all(axis=0).any():
raise ValueError('predictor absent in training partition')
median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([])
tr, te = np.where(np.isnan(tr), median, tr), np.where(np.isnan(te), median, te)
if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1:
raise ValueError('collinear predictors in training partition')
return tr, te
def _predict(train, y, test, columns, method):
tr, te = _matrix(train, test, columns)
if not columns:
return np.repeat(np.mean(y), len(test))
return FirthFamily(method).fit(tr, y).predict_proba(te)[:, 1]
def _metrics(y, probability):
y, p = np.asarray(y), np.asarray(probability)
valid = np.isfinite(p)
if valid.sum() != len(y) or len(np.unique(y)) != 2:
return {'auc': None, 'brier': None, 'calibration_intercept': None,
'calibration_slope': None, 'log_loss': None}
logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1)
calibration = LogisticRegression(C=1e6).fit(logits, y)
return {'auc': float(roc_auc_score(y, p)), 'brier': float(brier_score_loss(y, p)),
'calibration_intercept': float(calibration.intercept_[0]),
'calibration_slope': float(calibration.coef_[0, 0]),
'log_loss': float(log_loss(y, p, labels=[0, 1]))}
def evaluate(X: pd.DataFrame, y, *, coverage=0.7, candidate_limit=5, subset_limit=2,
outer_folds=3, inner_folds=2, seed=17, max_fits=100000):
"""Evaluate Firth/FLIC/FLAC with nested stratified CV and nested leave-one-out.
A fixed upper bound (default five candidates, pairs at most) permits at most 16 subsets
including the intercept. Each method selects a subset by inner out-of-fold log loss for
every outer split; all attempted subsets and failures are recorded.
"""
X = X.reset_index(drop=True).apply(pd.to_numeric, errors='coerce')
y = np.asarray(y)
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
raise ValueError('one known binary outcome is required per row')
if min(np.bincount(y.astype(int), minlength=2)) < max(outer_folds, inner_folds + 1):
raise ValueError('insufficient members of each outcome for nested CV and LOOCV')
if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit:
raise ValueError('candidate and subset limits exceed the supported bounds')
max_subsets = sum(math.comb(candidate_limit, k)
for k in range(min(candidate_limit, subset_limit) + 1))
estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1)
if estimated_fits > max_fits:
raise ValueError(f'estimated {estimated_fits} fits exceeds configured limit {max_fits}')
attempted, outputs = [], {}
started = time.monotonic()
plans = {'cv': StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
'loocv': LeaveOneOut().split(X, y)}
for plan, splits in plans.items():
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
selected = {m: [] for m in METHODS}
for fold, (train_idx, test_idx) in enumerate(splits):
train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int)
candidates = _candidates(train, coverage, candidate_limit)
subsets = [()] + [c for size in range(1, min(len(candidates), subset_limit) + 1)
for c in itertools.combinations(candidates, size)]
inner = list(StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain))
for method in METHODS:
ranking = []
for columns in subsets:
probs = np.full(len(train), np.nan)
error = None
try:
for a, b in inner:
probs[b] = _predict(train.iloc[a], ytrain[a], train.iloc[b], columns, method)
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
ranking.append((loss, len(columns), columns))
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
loss, error = None, type(exc).__name__
attempted.append({'validation': plan, 'fold': fold, 'method': method,
'variables': list(columns), 'inner_log_loss': loss, 'error': error})
_, _, best = min(ranking)
selected[method].append(list(best))
try:
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
except (ValueError, np.linalg.LinAlgError, RuntimeError):
pass
outputs[plan] = {m: {'metrics': _metrics(y, predictions[m]), 'selected': selected[m],
'unscored': int(np.isnan(predictions[m]).sum()),
'stability': {name: sum(name in cols for cols in selected[m])
for name in X.columns}}
for m in METHODS}
return {'development_only': True, 'candidate_limit': candidate_limit,
'subset_limit': subset_limit, 'coverage_minimum': coverage,
'max_subsets': max_subsets, 'maximum_fits': estimated_fits,
'estimated_seconds_at_50ms_per_fit': estimated_fits * 0.05,
'elapsed_seconds': time.monotonic() - started,
'source': 'edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728',
'attempts': attempted, 'validation': outputs}
+234
View File
@@ -0,0 +1,234 @@
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her
index date. NaN is missing: an absent value is never 0. No model reads these; they are
there for when one does.
Only what was available at the index is read (see `visible`): the index sample's results,
reported after it, are missing when the index is the sample day.
Inputs are the gold timeline with its `evidence_date` and `source_available_at`
(persistance.gold.evidence_timelines) and, for the form fields gold does not carry, the
wide silver cytology (persistance.gold.cervical_forms)."""
import numpy as np
import pandas as pd
from core import cacu, catalog
from models.cacu.features import _referral_grade, _worst, prepared
from models.cacu.specs import _REFERRAL
from models.survival import age_group, band
# What was done to her before the index: the index day's own is left out, as it may be
# (or follow from) the outcome.
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
GENOTYPES = cacu.HPV_GENOTYPE_FIELDS
EVIDENCE_TABLE = "cacu_eligibility_evidence"
def _codes(field: str) -> list[str]:
return list(catalog.studies()["cervical_cytology"].fields[field].codes)
FINDINGS = tuple(
name for name, f in catalog.studies()["cervical_cytology"].fields.items()
if name.startswith("finding_") and f.type == "boolean"
) # fmt: skip
def _day(values: pd.Series) -> pd.Series:
"""The calendar day of dates or ISO timestamps (as written); empty stays NaT."""
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's events available at her index, with her index date:
- dated (a result: reported) and, if it has one, clinically dated by the index;
- `source_available_at`, when the source gave it, by the index day. When it gave none,
the event's date stands, except for standalone eligibility evidence, dated by its
clinical onset: that is left out, as the cohort rules do;
- procedures and diagnoses strictly before the index day.
`known_at` (when the platform loaded it) is not read."""
found = events.drop(columns="index_date", errors="ignore").merge(
members[["person_id", "index_date"]], on="person_id"
)
index = pd.to_datetime(found["index_date"]).dt.normalize()
date, clinical = _day(found["date"]), _day(found["evidence_date"])
available = _day(found["source_available_at"])
keep = (date <= index) & (clinical.isna() | (clinical <= index))
undated = available.isna() & (found["source_table"] != EVIDENCE_TABLE)
keep &= undated | (available <= index)
earlier = (date < index) & (clinical.isna() | (clinical < index))
hysterectomy = (found["type"] == "gynecologic_condition") & (
found["value_code"] == "hysterectomy"
)
keep &= earlier | ~(found["type"].isin(PROCEDURES) | hysterectomy)
return prepared(found[keep])
def _flag(known: pd.Series, true: pd.Series) -> pd.Series:
"""1.0 / 0.0 where `known`, NaN elsewhere."""
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
def _one_hot(values: pd.Series, prefix: str, codes: list[str]) -> dict[str, pd.Series]:
"""One column per code; a value that is none of them is missing, not 0 in all."""
known = values.isin(codes)
return {f"{prefix}__{code}": _flag(known, values == code) for code in codes}
def _present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
"""1 when recorded; NaN otherwise (no record does not show it never happened)."""
return pd.Series(np.where(people.isin(events["person_id"]), 1.0, np.nan), index=people)
def _latest(events: pd.DataFrame, kind: str, people: pd.Index) -> pd.Series:
"""Each member's latest recorded value of one kind of event."""
found = events[(events["type"] == kind) & events["value_code"].notna()]
found = found.sort_values(["date", "source_id"], kind="stable")
return found.groupby("person_id")["value_code"].last().reindex(people)
def _latest_bethesda(events: pd.DataFrame, people: pd.Index) -> pd.Series:
"""The result of her latest report; the most severe when that day has several."""
codes = _codes("result")
found = events[(events["type"] == "bethesda") & events["value_code"].isin(codes)]
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
# severity is the order of the KPNC categories, not the catalog's
severity = {name: [name] for names in cacu.KPNC.values() for name in names if name in codes}
return _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
def _age(events: pd.DataFrame, members: pd.DataFrame) -> dict[str, pd.Series]:
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
keyed = members.set_index("person_id", drop=False)
keyed = keyed.assign(index_date=pd.to_datetime(keyed["index_date"]))
found = age_group(events, keyed, cuts)
labels = list(band(pd.Series([cuts[0] - 1, *cuts]), cuts))
return _one_hot(found, "age", labels)
def _cytology(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
result = _latest_bethesda(events, people)
columns = _one_hot(result, "bethesda", _codes("result"))
for name, codes in cacu.PROCEDURE_CYTOLOGY.items():
columns[f"cytology_{name}"] = _flag(result.notna(), result.isin(codes))
return columns
def _hpv(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
columns = {}
for kind in ("hpv", *GENOTYPES):
value = _latest(events, kind, people)
columns[f"{kind}_positive"] = _flag(
value.isin(["positive", "negative"]), value == "positive"
)
# From the two genotypes of one sample, not gold's `hpv_16_18`: that is 0 when one is
# negative and the other was not reported.
found = events[events["type"].isin(GENOTYPES) & events["value_code"].notna()]
wide = found.pivot_table(
index=["person_id", "date", "source_id"], columns="type", values="value_code",
aggfunc="first",
).reindex(columns=list(GENOTYPES)) # fmt: skip
latest = wide.sort_index().reset_index().drop_duplicates("person_id", keep="last")
latest = latest.set_index("person_id").reindex(people)[list(GENOTYPES)]
positive = (latest == "positive").any(axis=1)
both_negative = (latest == "negative").all(axis=1)
columns["hpv_16_or_18_positive"] = _flag(positive | both_negative, positive)
return columns
def _history(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
of = {kind: events[events["type"] == kind] for kind in (*PROCEDURES, "cytology")}
columns = {
"prior_cytology_sample": _present(
of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]], people
),
"prior_biopsy_order": _present(of["biopsy_order"], people),
"prior_biopsy_report": _present(of["biopsy"], people),
"prior_colposcopy": _present(of["colposcopy"], people),
"prior_treatment": _present(of["treatment"], people),
"prior_diagnosis_note": _present(of["diagnosis"], people),
"history_cancer_icd10": _present(of["history"], people),
"history_hysterectomy": _present(
events[(events["type"] == "gynecologic_condition")
& (events["value_code"] == "hysterectomy")], people
),
} # fmt: skip
rank = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY)}
worst = of["biopsy"]["value_code"].map(rank).groupby(of["biopsy"]["person_id"]).max()
worst = worst.reindex(people)
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "HSIL"), ("carcinoma", "carcinoma")):
columns[f"prior_biopsy_{name}"] = _flag(worst.notna(), worst >= rank[grade])
persons = pd.Series(people, index=people)
if events["type"].eq("colposcopy").any():
grade = _referral_grade(events, persons, _REFERRAL | {"cytology": cacu.KPNC_3})
else:
grade = pd.Series(None, index=people, dtype=object)
columns["referral_high_grade"] = _flag(grade.notna(), grade == "high")
return columns
def _forms(forms: pd.DataFrame | None, members: pd.DataFrame) -> dict[str, pd.Series]:
"""The cytology form's fields gold does not carry. Silver keeps no
`source_available_at` for them: what the sample form says counts from the sample day,
what the report says from the report day."""
people = pd.Index(members["person_id"])
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
*FINDINGS] # fmt: skip
if forms is None:
forms = pd.DataFrame(columns=columns)
found = forms[columns].merge(members[["person_id", "index_date"]], on="person_id")
index = pd.to_datetime(found["index_date"]).dt.normalize()
sampled = found[(_day(found["sample_date"]) <= index) & found["screening_history"].notna()]
sampled = sampled.sort_values("sample_date", key=_day, kind="stable")
history = sampled.groupby("person_id")["screening_history"].last().reindex(people)
reported = found[(_day(found["report_date"]) <= index) & (_day(found["sample_date"]) <= index)]
reported = reported.assign(r=_day(reported["report_date"]), s=_day(reported["sample_date"]))
# Her latest report, whole: a finding it does not state is unknown, whatever older
# reports said.
report = reported.sort_values(["r", "s"], kind="stable").drop_duplicates(
"person_id", keep="last"
)
report = report.set_index("person_id").reindex(people)
out = _one_hot(history, "screening_history", _codes("screening_history"))
adequacy = report["adequacy"]
out["sample_unsatisfactory"] = _flag(
adequacy.isin(_codes("adequacy")), adequacy == "unsatisfactory"
)
for name in FINDINGS:
value = report[name]
out[name] = _flag(value.notna(), value.eq(True))
return out
def encode(events: pd.DataFrame, forms: pd.DataFrame | None = None) -> pd.DataFrame:
"""One row per member of `events` (`person_id`, `index_date`): every encoder's column,
0.0, 1.0 or NaN. `events` needs `evidence_date` and `source_available_at`; without
`forms` their columns are all missing."""
missing = {"evidence_date", "source_available_at"} - set(events.columns)
if missing:
raise ValueError(f"timeline without availability columns: {', '.join(sorted(missing))}")
members = events[["person_id", "index_date"]].drop_duplicates().reset_index(drop=True)
if members["person_id"].duplicated().any():
raise ValueError("one index date per person")
people = pd.Index(members["person_id"], name="person_id")
seen = visible(events, members)
columns = _age(seen, members)
columns |= _cytology(seen, people)
columns |= _hpv(seen, people)
exam = seen[seen["source_table"] == "cervical_cytology"]
for field in EXAM_FIELDS:
columns |= _one_hot(_latest(exam, field, people), field, _codes(field))
columns |= _history(seen, people)
columns |= _forms(forms, members)
values = {name: column.to_numpy(dtype=float) for name, column in columns.items()}
return pd.concat([members, pd.DataFrame(values)], axis=1)
+7
View File
@@ -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
View File
@@ -1,8 +1,21 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports.""" """CaCu's training and scoring jobs (models.jobs) over its models and reports."""
from datetime import date
from models.cacu import reports from models.cacu import reports
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
from persistance import gold
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
def attrition(spec, as_of: date) -> dict | None:
"""The attrition of the spec's cohort; None when eligibility doesn't list that cohort."""
scenario = reports.COHORT_SCENARIOS.get(spec.cohort)
if scenario is None:
return None
rows = gold.cacu_eligibility_report(scenario, cutoff=as_of)
return reports.attrition(spec.cohort, rows, gold.people("cacu_events", as_of), as_of)
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability, attrition)
train, score = JOBS.train, JOBS.score train, score = JOBS.train, JOBS.score
+45 -4
View File
@@ -149,9 +149,20 @@ class Fit:
up[k] += step up[k] += step
down[k] -= step down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step) gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
covariance = np.nan_to_num(self.covariance, nan=0.0) free = np.isfinite(np.diag(self.covariance))
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient) variance = np.full((len(X), len(years)), np.nan)
return self.risk(X, Z, years), np.maximum(variance, 0.0) block = self.covariance[np.ix_(free, free)]
if block.size and np.isfinite(block).all() and np.allclose(block, block.T):
try:
positive = bool(np.all(np.linalg.eigvalsh(block) > 0))
except np.linalg.LinAlgError:
positive = False
if positive:
values = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free])
affected = np.any(np.abs(gradient[~free]) > 1e-10, axis=0)
valid = ~affected & np.isfinite(values) & (values >= 0)
variance[valid] = values[valid]
return self.risk(X, Z, years), variance
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
@@ -258,8 +269,38 @@ class Mixture(BaseEstimator):
point, variance = self.fits_[key].risk_with_variance( point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], self.horizons_years unique[:, :n_x], unique[:, n_x:], self.horizons_years
) )
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) relative = np.where(np.isfinite(variance),
np.sqrt(variance) / np.maximum(point, 1e-300), np.nan)
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1), band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
out[index[placed]] = band[inverse.ravel()] out[index[placed]] = band[inverse.ravel()]
return out return out
def variance_diagnostics(self, X: pd.DataFrame) -> dict:
"""Per stratum covariance properties and input rows without a complete interval."""
h = len(self.horizons_years)
result = []
for key, index in self._groups(X):
f = self.fits_.get(key)
predictions = self.predict(X.iloc[index])
missing = np.isnan(predictions[:, h:]).any(axis=1)
entry = {"stratum": [str(v) for v in key], "rows": len(index),
"rows_without_interval": int(missing.sum())}
if f is None:
entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[])
else:
diagonal = np.diag(f.covariance)
frozen = np.flatnonzero(np.abs(f.params) >= FROZEN).tolist()
negative = np.flatnonzero(np.isfinite(diagonal) & (diagonal < 0)).tolist()
free = np.isfinite(diagonal)
block = f.covariance[np.ix_(free, free)]
try:
positive = bool(block.size and np.isfinite(block).all()
and np.allclose(block, block.T)
and (np.linalg.eigvalsh(block) > 0).all())
except np.linalg.LinAlgError:
positive = False
entry.update(status="positive_definite" if positive else "not_estimable",
frozen_parameters=frozen, negative_variances=negative)
result.append(entry)
return {"strata": result, "horizons_years": list(self.horizons_years)}
+59 -1
View File
@@ -9,6 +9,8 @@ validation, is a document the clinical team adds). Both are data the governance
For the logistic regression, its coefficients and calibration by risk decile. For the logistic regression, its coefficients and calibration by risk decile.
""" """
from datetime import date
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from scipy.stats import norm from scipy.stats import norm
@@ -23,6 +25,61 @@ BOOTSTRAP = 200
SEED = 20261122 SEED = 20261122
Z = norm.ppf(0.975) Z = norm.ppf(0.975)
# The scenario of gold.cacu_eligibility that lists each cohort's candidates.
COHORT_SCENARIOS = {
"cacu_cohort_surveillance": "surveillance",
"cacu_cohort_post_colposcopy": "post_colposcopy",
"cacu_cohort_post_treatment": "post_treatment",
"cacu_cohort_survival": "survival",
}
# Reasons that a result still to arrive could lift.
AWAITING = {"unreported_biopsy", "no_index_result"}
# Clinical categories, not execution order: a candidate may belong to several stages.
REASON_STAGE = {
"hysterectomy": "eligibility", "under_18": "eligibility",
"no_birth_date": "eligibility", "died_by_index": "eligibility",
"prior_outcome": "history", "outcome_by_index": "history",
"cancer_history": "history", "prior_treatment": "history",
"outcome_before_index": "history", "no_pretreatment_biopsy": "history",
"no_referral": "index", "no_cotest": "index",
"no_index_result": "index", "unreported_biopsy": "index",
}
def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict:
"""Who a cohort lost and why, up to `as_of`. `rows`: its candidates' eligibility report (one
row per candidate and reason). A candidate with several reasons counts once in `excluded`
and once in each reason; `pending` are the excluded whose every reason awaits a result."""
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
key = ["person_id", "index_date", "index_sample_id"]
candidates = rows[key].drop_duplicates()
excluded = rows[rows["criterion"].notna()]
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
pending = int(sum(found <= AWAITING for found in reasons))
stages = excluded.assign(stage=excluded["criterion"].map(REASON_STAGE).fillna("unknown"))
return {
"cohort": cohort,
"scenario": COHORT_SCENARIOS[cohort],
"as_of": as_of.isoformat(),
"people": people,
"without_candidate": people - int(candidates["person_id"].nunique()),
"candidates": len(candidates),
"eligible": len(candidates) - len(reasons),
"excluded": len(reasons),
"pending": pending,
"by_reason": {
str(reason): int(count)
for reason, count in excluded["criterion"].value_counts().sort_index().items()
},
"by_stage": {
str(stage): len(group[key].drop_duplicates())
for stage, group in stages.groupby("stage", sort=True)
},
"stage_by_reason": {str(reason): REASON_STAGE.get(str(reason), "unknown")
for reason in sorted(excluded["criterion"].unique())},
"stage_counts_overlap": True,
}
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict: def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
if isinstance(spec, survival.Spec): if isinstance(spec, survival.Spec):
@@ -72,7 +129,8 @@ def _label(feature: str, value) -> str:
def _band(curve, variance) -> tuple[list, list]: def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) relative = np.where(np.isfinite(variance),
np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan)
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
+20 -6
View File
@@ -2,6 +2,7 @@
the prevalence-incidence mixture or a logistic regression. Training and scoring read the the prevalence-incidence mixture or a logistic regression. Training and scoring read the
patient timelines of the spec's cohort (see features).""" patient timelines of the spec's cohort (see features)."""
import json
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Literal from typing import Literal
@@ -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
+30 -32
View File
@@ -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,27 +49,35 @@ 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]: def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""Both cohorts' models, validation, calculator and risk factors, from their datasets' """The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
rows. reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors' factors' stability criterion, are then missing)."""
stability criterion, are then missing).""" from models.cama.recurrence import site
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {} return fit({"site": site.prepare(rows)}, "site", "site",
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
def fit(found: dict, saved: str, label: str,
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
"""The models of each prepared cohort, their validation, calculator and risk factors;
the `saved` cohort's is the model kept."""
sources = list(found)
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}
finally: finally:
joblib.externals.loky.get_reusable_executor().shutdown(wait=True) joblib.externals.loky.get_reusable_executor().shutdown(wait=True)
table = pd.concat([factors.risk_factors(fits[s]) for s in SOURCES], ignore_index=True) table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True)
summary = [row for s in SOURCES for row in factors.scenario_summary(fits[s], table)] summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)]
auc = [row for s in SOURCES for row in reports.auc_rows(fits[s])] auc = [row for s in sources for row in reports.auc_rows(fits[s])]
points = [row for s in SOURCES for row in drawn[s][1]] points = [row for s in sources for row in drawn[s][1]]
saved = fits[SAVED] kept = fits[saved]
model = Recurrence(SAVED, HORIZONS, saved.cohort.covariates, modeling.tables(saved)) model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept))
technical = { technical = {
"model": "recurrence", "model": "recurrence",
"cohort": "metabric+scanb", "cohort": label,
"method": "stepwise logistic regression + Bayesian network (BDeu), averaged", "method": "stepwise logistic regression + Bayesian network (BDeu), averaged",
"rutinas": reports.routines(found, n_bootstrap), "rutinas": reports.routines(found, n_bootstrap),
"recurrencia_desarrollo": reports.development(auc, table, points, summary), "recurrencia_desarrollo": reports.development(auc, table, points, summary),
@@ -87,7 +85,7 @@ def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurr
interpretability = { interpretability = {
"model": "recurrence", "model": "recurrence",
"kind": "scenarios", "kind": "scenarios",
"recurrencia": reports.figures([r for s in SOURCES for r in drawn[s][0]]), "recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
} }
reports_ = {"technical_validation": technical, "interpretability": interpretability} reports_ = {"technical_validation": technical, "interpretability": interpretability}
return model, reports.metrics(auc), reports_ return model, reports.metrics(auc), reports_
+3 -41
View File
@@ -21,44 +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"}
# 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
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
@@ -142,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
@@ -168,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,
+9 -88
View File
@@ -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."""
+26 -170
View File
@@ -1,35 +1,20 @@
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has. """The risk factors of recurrence by each horizon, and the ones each calculator scenario has
(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2),
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's the horizon's HBN parents give (3))."""
most frequent category by four criteria: (1) its adjusted odds ratio's 95 % CI excludes 1 and
its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least FREQ_MIN of
the time; (3) its covariate is a parent of the HBN; (4) its Kaplan-Meier recurrence-free
survival at the horizon differs from the reference's (95 % CI) in the odds ratio's direction.
"Robusto" needs (1) and three criteria, "sugerente" two. Treatments get their odds ratios,
adjusted for the intrinsic covariates, but no class: they are associations, not effects."""
import warnings import warnings
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import statsmodels.api as sm
from scipy.stats import false_discovery_control
from models.cama.recurrence.calculator import SCENARIOS, masks from models import factors as rated
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, variable_of from models.cama.recurrence.modeling import CohortFit
from models.curves import life_table from models.factors import FREQ_MIN, ORDER
ALPHA = 0.05 OR = "OR_recurrencia"
FREQ_MIN = 0.80 SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S")
Z = 1.96
ORDER = {
"riesgo robusto": 0,
"protector robusto": 1,
"riesgo sugerente": 2,
"protector sugerente": 3,
"no concluyente": 4,
}
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
COLUMNS = [ COLUMNS = [
"cohorte", "cohorte",
@@ -39,16 +24,14 @@ COLUMNS = [
"categoria", "categoria",
"referencia", "referencia",
"n_categoria", "n_categoria",
"OR_recurrencia", OR,
"IC95_inf", "IC95_inf",
"IC95_sup", "IC95_sup",
"p", "p",
"p_ajustado_BH", "p_ajustado_BH",
"freq_seleccion_bootstrap", "freq_seleccion_bootstrap",
"en_manta_markov", "en_manta_markov",
"S_libre_categoria", *SURVIVAL,
"S_libre_referencia",
"delta_S",
"delta_IC95_inf", "delta_IC95_inf",
"delta_IC95_sup", "delta_IC95_sup",
"c1_or", "c1_or",
@@ -58,39 +41,7 @@ COLUMNS = [
"criterios_cumplidos", "criterios_cumplidos",
"clasificacion", "clasificacion",
] ]
# Scenario presence: the share of the scenario's patients in the category. DESCRIBING = rated.DESCRIBING
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria")
def km_at(months, event, horizon) -> tuple[float, float]:
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
d, _, n = life_table(months, event)
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
last = min(horizon, len(d) - 1) + 1
S = float(np.prod(q[:last]))
return S, S * float(np.sqrt(np.sum(v[:last])))
def _odds_ratios(data: pd.DataFrame, y, variables, reference) -> pd.DataFrame:
"""Logistic GLM on every category but each covariate's reference (constant and
duplicated dummies dropped): odds ratios with Wald 95 % CI and p."""
X = pd.get_dummies(data[variables]).astype(float)
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = np.exp(m.conf_int().loc[X.columns])
return pd.DataFrame(
{
"termino": X.columns,
"OR_recurrencia": np.exp(m.params[X.columns].to_numpy()),
"IC95_inf": ci[0].to_numpy(),
"IC95_sup": ci[1].to_numpy(),
"p": m.pvalues[X.columns].to_numpy(),
}
)
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame: def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
@@ -103,72 +54,23 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy() event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
def complete(table, variables): def complete(table, variables):
"""Each term's covariate, category, BH p and survival difference to its reference.""" return rated.complete(table, variables, reference, everyone, months, event, horizon,
table = table.reset_index(drop=True) SURVIVAL) # fmt: skip
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
]
table["referencia"] = table["variable"].map(reference)
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
rows = []
for v, cat, ref in zip(
table["variable"], table["categoria"], table["referencia"], strict=True
):
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == ref).to_numpy()
(sa, ea), (sb, eb) = (
km_at(months[a], event[a], horizon),
km_at(months[b], event[b], horizon),
)
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
rows.append(
{
"n_categoria": int(a.sum()),
"S_libre_categoria": sa,
"S_libre_referencia": sb,
"delta_S": delta,
"delta_IC95_inf": delta - Z * se,
"delta_IC95_sup": delta + Z * se,
}
)
return pd.concat([table, pd.DataFrame(rows)], axis=1)
intrinsic, treatment = cohort.intrinsic, cohort.treatment intrinsic, treatment = cohort.intrinsic, cohort.treatment
tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic) tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
risk = tab["OR_recurrencia"] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab["delta_S"]) == np.where(risk, -1, 1))
hz = fitted.horizons[horizon] hz = fitted.horizons[horizon]
tab["freq_seleccion_bootstrap"] = tab["variable"].map( tab["freq_seleccion_bootstrap"] = tab["variable"].map(
lambda v: np.nan if selection is None else selection.get(v, 0.0) lambda v: np.nan if selection is None else selection.get(v, 0.0)
) )
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents) tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"] tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN)
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
tab["clasificacion"] = [
"no aplica (categoria desconocida)"
if cat == UNKNOWN
else f"{d} robusto"
if c1 and k >= 3
else f"{d} sugerente"
if k >= 2
else "no concluyente"
for cat, d, c1, k in zip(
tab["categoria"],
tab["direccion"],
tab["c1_or"],
tab["criterios_cumplidos"],
strict=True,
)
]
tab["tipo"] = "factor de riesgo" tab["tipo"] = "factor de riesgo"
if treatment: if treatment:
both = intrinsic + treatment both = intrinsic + treatment
tr = _odds_ratios(data, y, both, reference) tr = rated.odds_ratios(data, y, both, reference, OR)
of = tr["termino"].map(lambda x: variable_of(x, both)) of = tr["termino"].map(lambda x: rated.variable_of(x, both))
tr = complete( tr = complete(
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
) )
@@ -191,72 +93,26 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra
tab = pd.concat(found, ignore_index=True) tab = pd.concat(found, ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5) tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
keys = ["horizonte_meses", "_kind", "_order", "OR_recurrencia"] keys = ["horizonte_meses", "_kind", "_order", OR]
tab = tab.sort_values(keys, ascending=[True, True, True, False]) tab = tab.sort_values(keys, ascending=[True, True, True, False])
return tab[COLUMNS].round(4) return tab[COLUMNS].round(4)
def _presence(share: float) -> str:
if share >= DEFINING:
return "definitoria"
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
def _listing(part: pd.DataFrame) -> str:
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
`asociacion`."""
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join(
f"{v}={c} ({s}, {p:.0%})"
for v, c, s, p in zip(
part["variable"], part["categoria"], strength, part["share"], strict=True
)
)
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: 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 = factors[ found = rated.classified(factors[factors["cohorte"] == source])
(factors["cohorte"] == source)
& factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")
]
kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
)
found = found.assign(tipo_efecto=kind)
rows = [] rows = []
for name, mask in masks(frame, scenarios).items(): for name, mask in masks(frame, scenarios).items():
if not mask.any() or found.empty: if not mask.any() or found.empty:
continue continue
share = [
float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True)
]
detail = found.assign(share=share, presence=[_presence(s) for s in share])
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items()) definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
for h in fitted.horizons: for h in fitted.horizons:
d = detail[detail["horizonte_meses"] == h] rows.append({
row = { "cohorte": source, "escenario": name, "definicion": definition,
"cohorte": source, "n_escenario": int(mask.sum()), "horizonte_meses": h,
"escenario": name, **rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
"definicion": definition, }) # fmt: skip
"n_escenario": int(mask.sum()),
"horizonte_meses": h,
}
for k in ("riesgo", "protector", "tratamiento"):
for level, label in (
("definitoria", "definitorios"),
("mayoritaria", "mayoritarios"),
):
row[f"{k}_{label}"] = _listing(
d[(d["tipo_efecto"] == k) & (d["presence"] == level)]
)
included = (d["tipo_efecto"] == "riesgo") & d["presence"].isin(DESCRIBING)
row["n_factores_riesgo_incluidos"] = int(included.sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
rows.append(row)
return rows return rows
+3 -9
View File
@@ -20,9 +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
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
@@ -31,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} N_BOOTSTRAP = {"site": 40}
# ---------------------------------------------------------------- logistic regression # ---------------------------------------------------------------- logistic regression
@@ -203,12 +203,6 @@ def c_index(cohort: Cohort) -> float:
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"])) return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
def variable_of(term: str, covariates: list[str]) -> str:
"""The covariate a dummy belongs to (the longest name it starts with)."""
found = [c for c in covariates if term.startswith(c + "_")]
return max(found, key=len) if found else term
@dataclass @dataclass
class Horizon: class Horizon:
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each """A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
+2 -4
View File
@@ -15,7 +15,6 @@ from models.cama.recurrence.modeling import (
ESS, ESS,
HORIZONS, HORIZONS,
MAX_PARENTS, MAX_PARENTS,
N_BOOTSTRAP,
CohortFit, CohortFit,
) )
@@ -109,8 +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()
}, },
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", **next(iter(cohorts.values())).sampling,
"origen": "METABRIC y SCAN-B (externas)",
}, },
"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}»); "
@@ -137,7 +135,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por " "salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
"bootstrap", "bootstrap",
"replicas": { "replicas": {
**{s: n_bootstrap.get(s, 0) for s in N_BOOTSTRAP}, **{s: n_bootstrap.get(s, 0) for s in cohorts},
"calculadora": RESAMPLES, "calculadora": RESAMPLES,
}, },
"eventos_minimos_por_escenario": MIN_EVENTS, "eventos_minimos_por_escenario": MIN_EVENTS,
+146
View File
@@ -0,0 +1,146 @@
"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa
timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy
report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned
from), so the same fits, calculator and risk factors run on it.
- Time and event: months from the index to her first recurrence (any site) after it, else to
her death, else to the cut-off (the site records its recurrences: a patient without one is
taken as free of it up to then); `muerte_sin_recaida` when she died without one.
- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the
first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN):
age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or
more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate:
Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+,
Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them."""
import numpy as np
import pandas as pd
from models.cama.recurrence import cohorts
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
RESULT_DAYS = 30
TREATMENT_DAYS = 365
KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
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:
"""The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it."""
hormone = "positive" in (er, pr)
if her2 == "positive":
return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
if her2 != "negative":
return UNKNOWN
if not hormone:
return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN
if ki67 is None or ki67 != ki67:
return UNKNOWN
return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-"
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
"""One row per member: her time, event and covariates, as `cohorts.prepare` gives a
reference cohort's."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
members = events.groupby("person_id")["index_date"].first()
days = (events["date"] - events["index_date"]).dt.days
cut = pd.Timestamp(as_of)
after = events[(days > 0) & (events["date"] <= cut)]
first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min()
death = events[(events["type"] == "death") & (events["date"] <= cut)]
death = death.groupby("person_id")["date"].min().reindex(members.index)
end = first_recurrence.reindex(members.index).fillna(death).fillna(cut)
out = pd.DataFrame(index=members.index)
out["paciente"] = members.index
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members - birth.reindex(members.index)).dt.days / 365.25
out["Edad"] = _band(age, *cohorts.AGE)
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
*cohorts.NODES) # fmt: skip
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
ki67 = number("ki67_pct").reindex(members.index)
out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR))
out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR))
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
out["Subtipo_clinico"] = [subtype(*a) for a in zip(
receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index)
given = given.apply(lambda g: g if isinstance(g, set) else set())
out["Cirugia"] = given.apply(
lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None")
)
for name, kind in TREATMENTS.items():
out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No")
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:
"""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
scenarios name patients by them (the subtype, built from the receptors and Ki-67, is
redundant by construction)."""
covariates = [c for c in rows.columns if c not in FIXED]
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
kept = [c for c in covariates if c not in dropped]
treatment = [c for c in TREATMENT if c in kept]
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
SCENARIOS, SAMPLING) # fmt: skip
+35 -25
View File
@@ -7,17 +7,16 @@
known at it. A patient who dies before her treatment counts as untreated (immortal-time known at it. A patient who dies before her treatment counts as untreated (immortal-time
bias), which the technical report states. bias), which the technical report states.
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 two public reference - Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the (`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
`cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a (proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
quarter of an hour), so it trains only when asked for by name."""
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date
import pandas as pd import pandas as pd
from models.survival import DAYS_PER_YEAR, Spec, age_group, band from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
from persistance import nodes
# The index report's results (timeline types), read from a week before to RESULT_DAYS after. # The index report's results (timeline types), read from a week before to RESULT_DAYS after.
RESULTS = ("histologic_type", "grade", "er", "pr", "her2") RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
@@ -89,33 +88,43 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
@dataclass(frozen=True) @dataclass(frozen=True)
class ReferenceRecurrence: class SiteRecurrence:
"""The recurrence model over the reference cohorts the `pipeline` loaded: one source node """The recurrence model on the site's own patients (models.cama.recurrence.site): the
per cohort, named as the cohort.""" cohort's timelines in, its fits, calculator and risk factors out, with its own reports;
each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in."""
name: str name: str
pipeline: str = "cama_reference" cohort: str = "cama_cohort_recurrence"
cohort: None = None # trains on no gold cohort, and scores no patient reports: bool = True # it writes its own reports (models.jobs)
slow: bool = True
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.jobs import EmptyCohort
model, metrics, reports = recurrence.train(self.datasets()) rows = site.frame(events, as_of or date.today())
return model, metrics, reports if reason := site.scarce(rows):
raise EmptyCohort(f"cama.recurrence: {reason}")
def datasets(self) -> dict[str, pd.DataFrame]: return recurrence.train_site(rows)
"""Each reference cohort's rows, as the pipeline loaded them."""
from models.cama import recurrence
found = {s: pd.DataFrame(nodes.rows(self.pipeline, s)) for s in recurrence.SOURCES}
if any(r.empty for r in found.values()):
raise LookupError(f"load the reference cohorts first (pipeline {self.pipeline})")
return found
def predict(self, model, events) -> pd.DataFrame: def predict(self, model, events) -> pd.DataFrame:
return model.predict(events) from models.cama.recurrence import calculator, site
members = site.frame(events, date.today())
found = model.predict(members)
index = events.groupby("person_id")["index_date"].first()
masks = calculator.masks(members, site.SCENARIOS)
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
for i in range(len(members))] # fmt: skip
rows = []
for i, person in enumerate(members["paciente"]):
for h in model.horizons:
rows.append({"person_id": person,
"index_date": pd.Timestamp(index[person]).date(),
"horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
"ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
return pd.DataFrame(rows, columns=OUTPUT)
MODELS = { MODELS = {
@@ -146,6 +155,7 @@ MODELS = {
cap_months=24, cap_months=24,
scenarios=SCENARIOS, scenarios=SCENARIOS,
scenario_columns=("age",), scenario_columns=("age",),
treatments=("surgery", "chemotherapy", "radiotherapy"),
notes=( notes=(
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los " f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere " f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
@@ -153,5 +163,5 @@ MODELS = {
"efecto protector del tratamiento aparece mayor de lo que es.", "efecto protector del tratamiento aparece mayor de lo que es.",
), ),
), ),
"recurrence": ReferenceRecurrence("recurrence"), "recurrence": SiteRecurrence("recurrence"),
} }
+52
View File
@@ -0,0 +1,52 @@
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
task carries its data (a recording), so a cap paces a slow link."""
import os
from collections.abc import Callable, Iterable
from importlib.util import find_spec
from typing import Any
from joblib import Parallel, delayed
def jobs() -> int:
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
return int(os.environ.get("BATCH_JOBS", "-1"))
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
"""`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
drawn as tasks start, so at most `jobs()` of them are held at once."""
if find_spec("distributed") is None:
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
from distributed import Client, LocalCluster, as_completed
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
# one process per core, no dashboard port to collide with (8787 is often taken)
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
try:
with Client(where) as client:
limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
pending = iter(enumerate(arguments))
results: dict[int, Any] = {}
order: dict[Any, int] = {}
def submit() -> Any | None:
if (item := next(pending, None)) is None:
return None
future = client.submit(task, *item[1], pure=False)
order[future] = item[0]
return future
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
for done in running:
results[order.pop(done)] = done.result()
if (future := submit()) is not None:
running.add(future)
return [results[i] for i in range(len(results))]
finally:
if not address:
where.close()
+84 -3
View File
@@ -1,12 +1,14 @@
"""Dagster code location: every heavy step of the platform is a job defined here.""" """Dagster code location: every heavy step of the platform is a job defined here."""
import importlib import importlib
import os
from datetime import date from datetime import date
import dagster as dg import dagster as dg
from models import graph from models import graph
from models.jobs import EmptyCohort from models.jobs import EmptyCohort
from persistance import backup as backups
from persistance import config_log, silver from persistance import config_log, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite) WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
@@ -41,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)
@@ -76,7 +78,7 @@ class Scoring(dg.Config):
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict: def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt.""" """Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()} found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()}
for name, version in found.items(): for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion")) context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"]) silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
@@ -88,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
@@ -105,4 +148,42 @@ def analyze():
analyze_studies() analyze_studies()
defs = dg.Definitions(jobs=[ingest, train, score, analyze]) @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
def make_backup(context: dg.OpExecutionContext) -> str:
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
folder = backups.create()
context.log.info(f"backup {folder}")
return str(folder)
@dg.job(tags=WRITES) # holds the writing slot: nothing writes while it copies
def backup():
make_backup()
# Nightly by default; BACKUP_SCHEDULE is a cron expression (empty: no schedule).
nightly = (
[
dg.ScheduleDefinition(
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
)
] # fmt: skip
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
else []
)
defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup,
cacu_development_evaluation], schedules=nightly)
+178
View File
@@ -0,0 +1,178 @@
"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models.
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes
1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least
FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its
Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's
direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three
criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get
their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations,
not effects. Each clinical scenario then lists the classified factors nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import false_discovery_control
from models.curves import life_table
ALPHA = 0.05
FREQ_MIN = 0.80
Z = 1.96
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
ORDER = {
"riesgo robusto": 0,
"protector robusto": 1,
"riesgo sugerente": 2,
"protector sugerente": 3,
"no concluyente": 4,
}
UNKNOWN_CLASS = "no aplica (categoria desconocida)"
# Scenario presence: the share of the scenario's patients in the category.
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria")
def variable_of(term: str, covariates: list[str]) -> str:
"""The covariate a dummy belongs to (the longest name it starts with)."""
found = [c for c in covariates if term.startswith(c + "_")]
return max(found, key=len) if found else term
def km_at(months, event, horizon) -> tuple[float, float]:
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
d, _, n = life_table(months, event)
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
last = min(horizon, len(d) - 1) + 1
S = float(np.prod(q[:last]))
return S, S * float(np.sqrt(np.sum(v[:last])))
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
"""Logistic GLM on every category but each covariate's reference (constant and
duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p."""
X = pd.get_dummies(data[variables]).astype(float)
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = np.exp(m.conf_int().loc[X.columns])
return pd.DataFrame(
{
"termino": X.columns,
name: np.exp(m.params[X.columns].to_numpy()),
"IC95_inf": ci[0].to_numpy(),
"IC95_sup": ci[1].to_numpy(),
"p": m.pvalues[X.columns].to_numpy(),
}
)
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
survival columns)."""
table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
]
table["referencia"] = table["variable"].map(reference)
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
category, ref, delta_name = names
rows = []
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
sa, ea = km_at(months[a], event[a], horizon)
sb, eb = km_at(months[b], event[b], horizon)
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
rows.append({
"n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
"delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
}) # fmt: skip
return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
"delta_IC95_inf", "delta_IC95_sup"])],
axis=1) # fmt: skip
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
for the criteria `evaluated`."""
risk = tab[or_name] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1))
tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1)
robust = min(3, len(evaluated))
tab["clasificacion"] = [
UNKNOWN_CLASS
if cat == unknown
else f"{d} robusto"
if c1 and k >= robust
else f"{d} sugerente"
if k >= 2
else "no concluyente"
for cat, d, c1, k in zip(
tab["categoria"],
tab["direccion"],
tab["c1_or"],
tab["criterios_cumplidos"],
strict=True,
)
]
return tab
def presence(share: float) -> str:
if share >= DEFINING:
return "definitoria"
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
def listing(part: pd.DataFrame) -> str:
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
`asociacion`."""
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join(
f"{v}={c} ({s}, {p:.0%})"
for v, c, s, p in zip(
part["variable"], part["categoria"], strength, part["share"], strict=True
)
)
def classified(factors: pd.DataFrame) -> pd.DataFrame:
"""The factors a scenario can list (classified ones and treatments), with `tipo_efecto`:
riesgo, protector or tratamiento."""
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
)
return found.assign(tipo_efecto=kind)
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
"""What one scenario's patients (`mask` over `frame`) have of the `classified` factors:
the listings by kind and presence, and how many risk factors describe it."""
share = [
float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True)
]
detail = found.assign(share=share, presence=[presence(s) for s in share])
row = {}
for k in ("riesgo", "protector", "tratamiento"):
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
row[f"{k}_{label}"] = listing(
detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)]
)
included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING)
row["n_factores_riesgo_incluidos"] = int(included.sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
return row
+141 -41
View File
@@ -10,9 +10,11 @@ from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor from concurrent.futures import ProcessPoolExecutor
from functools import cache from functools import cache
import duckdb
import ocrmypdf import ocrmypdf
import pandas as pd import pandas as pd
import pdfplumber import pdfplumber
import pikepdf
import splink.comparison_library as cl import splink.comparison_library as cl
from markitdown import MarkItDown from markitdown import MarkItDown
from openai import OpenAI, OpenAIError from openai import OpenAI, OpenAIError
@@ -22,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,
@@ -45,14 +48,28 @@ from core.pipeline import (
) )
from persistance import config_log, files, nodes, silver from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
"text": {"data_type": "text", "nullable": True}, "text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"}, "ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True}, "error": {"data_type": "text", "nullable": True},
"format": {"data_type": "text", "nullable": True},
} }
def file_format(content: bytes) -> str:
"""What kind of file this is, from its first bytes, so a route can tell a PDF from an
EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose
version is "0"), or other (whatever MarkItDown reads)."""
if content.startswith(b"%PDF"):
return "pdf"
head = content[:256]
if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit():
return "edf"
return "other"
@cache @cache
def _reader() -> MarkItDown: def _reader() -> MarkItDown:
return MarkItDown() return MarkItDown()
@@ -64,52 +81,93 @@ def _lines(text: str) -> str:
def _text(content: bytes) -> str: def _text(content: bytes) -> str:
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each """Files other than PDFs, through MarkItDown."""
(spacing within a line collapsed); every other format through MarkItDown."""
if content.startswith(b"%PDF"):
with pdfplumber.open(io.BytesIO(content)) as pdf:
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
return _reader().convert_stream(io.BytesIO(content)).text_content return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]:
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
on one line each (spacing within a line collapsed)."""
with pdfplumber.open(io.BytesIO(content)) as pdf:
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
copied into a PDF of their own: a typed page keeps its own text layer."""
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers:
scans.pages.append(source.pages[n])
pages, sidecar = io.BytesIO(), io.BytesIO()
scans.save(pages)
pages.seek(0)
ocrmypdf.ocr(
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
) # fmt: skip
found = sidecar.getvalue().decode().split("\f")
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
def read_file(content: bytes) -> dict: def read_file(content: bytes) -> dict:
"""Text of one file, and whether OCR was needed. An unreadable file keeps its error.""" """Text of one file, its format, and whether OCR was needed. An unreadable file keeps
its error; a signal recording (EDF) has no text to read."""
kind = file_format(content)
if kind == "edf":
return {"text": None, "ocr": False, "error": None, "format": kind}
return {**_read_text(content), "format": kind}
def _read_text(content: bytes) -> dict:
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
typed form whose second page is a scan, say)."""
try: try:
found = _text(content) if not content.startswith(b"%PDF"):
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS return {"text": _text(content), "ocr": False, "error": None}
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page pages = _pdf_pages(content)
text = io.BytesIO() scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS]
ocrmypdf.ocr( if scanned:
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True, for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True, pages[i] = page
sidecar=text, return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
) # fmt: skip
found = _lines(text.getvalue().decode())
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read): def run_read(p: str, node: Read):
"""The input's rows with the file column replaced by its text; each file read once.""" """The input's rows with their file's text and format beside the file column (which
keeps the file, for a study that takes the file itself: an EEG's recording); each file
read once."""
rows = list(nodes.rows(p, node.inputs[0])) rows = list(nodes.rows(p, node.inputs[0]))
for row in rows: # the source kept the file; the row carries its hash for row in rows: # the source kept the file; the row carries its hash
row["key"] = row.pop(node.column) or None row["key"] = row.get(node.column) or None
keys = {r["key"] for r in rows} - {None} keys = {r["key"] for r in rows} - {None}
found = nodes.cached("read_cache", keys) found = nodes.cached("read_cache", keys)
new = {k: files.content(k) for k in keys - set(found)} legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats
with ProcessPoolExecutor() as pool: for k in legacy:
read = dict(zip(new, pool.map(read_file, new.values()), strict=True)) found[k]["format"] = file_format(files.content(k) or b"")
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS) nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
found |= read for k in legacy], READ_COLUMNS) # fmt: skip
new = sorted(keys - set(found))
with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept
for start in range(0, len(new), READ_BATCH):
batch = new[start : start + READ_BATCH]
read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
strict=True)) # fmt: skip
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
READ_COLUMNS) # fmt: skip
found |= read
for row in rows: for row in rows:
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"}) result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
row |= {k: result[k] for k in READ_COLUMNS} row |= {k: result[k] for k in READ_COLUMNS}
return nodes.write(p, node.id, rows, READ_COLUMNS) return nodes.write(p, node.id, rows, READ_COLUMNS)
def run_route(p: str, node: Route): def run_route(p: str, node: Route, others: list[Route] = ()):
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)]) """The input's rows the route takes; an `otherwise` route, those `others` don't."""
rows = nodes.rows(p, node.inputs[0])
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
return nodes.write(p, node.id, taken)
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
@@ -127,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):
@@ -191,8 +246,9 @@ def run_extract(p: str, node: Extract):
found = apply_patterns(node, text, codes) found = apply_patterns(node, text, codes)
else: else:
found = [({}, {}, ["no LLM answering and no patterns set"])] found = [({}, {}, ["no LLM answering and no patterns set"])]
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]): for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
out.append({**values, RECORD: row[RECORD], "_index": index, out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
QUOTES: json.dumps(quotes, ensure_ascii=False), QUOTES: json.dumps(quotes, ensure_ascii=False),
HELD: json.dumps(held) if held else None}) # fmt: skip HELD: json.dumps(held) if held else None}) # fmt: skip
return nodes.write(p, node.id, out) return nodes.write(p, node.id, out)
@@ -256,6 +312,28 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[
return frame[["unique_id", *present]], sources, written return frame[["unique_id", *present]], sources, written
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
"""Each record's stand-in: one record per identity that the rules join to itself (a
patient's 24 reports carrying one record number are one row to compare, not 24² pairs).
A record a reviewer judged stands for itself, and so does one the rules would not join
to an identical record (nothing compared was read, say)."""
fields = [c for c in records.columns if c != "unique_id"]
key = records[fields].astype(object).where(records[fields].notna(), None)
same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index)
stand_in = records.groupby(same, sort=False)["unique_id"].transform("first")
stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"])
joined = set()
if rules:
con = duckdb.connect()
con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
joins = " or ".join(f"({r})" for r in rules)
joined = set(con.sql(
f"select l.unique_id from candidates l join candidates r"
f" on l.unique_id = r.unique_id where {joins}"
).df()["unique_id"]) # fmt: skip
return stand_in.where(stand_in.isin(joined), records["unique_id"])
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame: def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
clusters = cluster_pairwise_predictions_at_threshold( clusters = cluster_pairwise_predictions_at_threshold(
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r" records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
@@ -274,22 +352,25 @@ def run_link(p: str, node: Link):
rules = [r for r in node.rules or node.default_rules() rules = [r for r in node.rules or node.default_rules()
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
comparisons = [_comparison(f) for f in fields] comparisons = [_comparison(f) for f in fields]
decided = nodes.person_decisions()
stand_in = _distinct(records, rules, set().union(*decided))
distinct = records[records["unique_id"].isin(set(stand_in))]
db = DuckDBAPI() db = DuckDBAPI()
linker = Linker( linker = Linker(
db.register(records), db.register(distinct),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons, SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=rules), blocking_rules_to_generate_predictions=rules),
log_level=None, log_level=None,
) # fmt: skip ) # fmt: skip
decided = nodes.person_decisions()
sure = linker.inference.deterministic_link().as_pandas_dataframe() sure = linker.inference.deterministic_link().as_pandas_dataframe()
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)} pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same} pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
known = set(records.unique_id) known = set(distinct.unique_id)
edges = pd.DataFrame( edges = pd.DataFrame(
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"] [sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
) )
persons = _persons(records, edges, db) cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
facts = [f for f in ("birth_date", "sex") if f in fields] facts = [f for f in ("birth_date", "sex") if f in fields]
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame() spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
@@ -342,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()
@@ -356,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
@@ -400,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):
@@ -420,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)
@@ -439,6 +535,10 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
for node in pipeline.order(): for node in pipeline.order():
if node.kind == "target": if node.kind == "target":
run_target(pipeline_id, node, kinds) run_target(pipeline_id, node, kinds)
elif node.kind == "route" and node.otherwise:
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
run_route(pipeline_id, node, others)
else: else:
RUNNERS[node.kind](pipeline_id, node) RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done") log(f"{node.id} ({node.kind}) done")
+18 -6
View File
@@ -35,14 +35,20 @@ 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 or score 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]:
"""The models a score run takes when none is named: all of them."""
return list(self.models)
def registered(self, name: str) -> str: def registered(self, name: str) -> str:
return f"{self.domain}.{name}" return f"{self.domain}.{name}"
@@ -51,8 +57,11 @@ 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) events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
fitted, metrics, found = spec.train(events, as_of)
else: else:
events = gold.timelines(self.events, spec.cohort, as_of) events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty: if events.empty:
@@ -62,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)
@@ -72,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
+164 -4
View File
@@ -9,6 +9,8 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi
category of its own (UNKNOWN). category of its own (UNKNOWN).
""" """
import json
import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
from itertools import pairwise from itertools import pairwise
@@ -220,7 +222,9 @@ class IntervalSurvival(BaseEstimator):
# ---------------------------------------------------------------- a model over gold timelines # ---------------------------------------------------------------- a model over gold timelines
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",
"scenarios"] # fmt: skip
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
@@ -265,6 +269,8 @@ class Spec:
# "in", value) on the members' covariates and `scenario_columns` (kept for them only). # "in", value) on the members' covariates and `scenario_columns` (kept for them only).
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict) scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = () scenario_columns: tuple[str, ...] = ()
# Features that are treatments: their odds ratios are reported as associations, unclassified.
treatments: tuple[str, ...] = ()
@property @property
def horizons(self) -> tuple[float, ...]: def horizons(self) -> tuple[float, ...]:
@@ -324,21 +330,31 @@ class Spec:
return model, metrics, {"train": train, "test": test} return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame: def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, and its interval when kept.""" """One row per member and horizon: her mortality by it, its interval when kept, and
the clinical scenarios of the report she falls in (the curves her record draws)."""
members = self.members(events) members = self.members(events)
mortality = 1.0 - model.survival(members) mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons) n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h) empty = ([np.nan] * h, [np.nan] * h)
ends = [model.intervals_.get(tuple(c), empty) ends = [model.intervals_.get(tuple(c), empty)
for c in self._combinations(members).itertuples(index=False)] # fmt: skip for c in self._combinations(members).itertuples(index=False)] # fmt: skip
return pd.DataFrame({ masks = scenario_masks(members, self.scenarios)
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
for i in range(n)] # fmt: skip
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),
"probability": mortality.ravel(), "probability": mortality.ravel(),
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(), "ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"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),
})[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)
@@ -419,6 +435,32 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
} # fmt: skip } # fmt: skip
def _combination_curves(spec: Spec, members: pd.DataFrame) -> list[dict]:
"""Kaplan-Meier of the members who share every covariate value: the one curve a patient with
those values is shown. Fewer than MIN_SCENARIO_EVENTS deaths: counts and why, no curve."""
from models import curves
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
keys = spec._combinations(members)
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:
until = int(months[rows].max())
km = curves.kaplan_meier(months[rows], event[rows], until)
entry["km"] = {
"months": list(range(until + 1)),
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)},
"interval": {"available": True, "level": 0.95, "method": "greenwood_log_log"},
}
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
@@ -476,7 +518,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,
@@ -496,4 +538,122 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"escenarios": scenarios, "escenarios": scenarios,
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths "escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS, "min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
**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, members)
return report
# ---------------------------------------------------------------- risk factors
FACTOR_COLUMNS = (
"tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov",
"c4_supervivencia", "criterios_cumplidos", "clasificacion",
) # fmt: skip
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
# The model has no variable selection to resample, so stability (2) is not evaluated.
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame:
"""The members' risk factors of death by the last horizon (`models.factors`, as the
SEER-trained original rates them): odds ratios of dying before it, among those dead before
it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at
`cap_months`); the Markov blanket is the HBN's parents in any interval."""
from models import factors as rated
horizon = spec.borders[-1]
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
died = event & (months < horizon)
known = died | (months >= horizon)
data = spec._combinations(members)[known].reset_index(drop=True)
y, months, event = died[known].astype(int), months[known], event[known]
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
if len(data) == 0 or y.min() == y.max():
return empty
features = list(spec.features)
treatment = [f for f in features if f in spec.treatments]
intrinsic = [f for f in features if f not in spec.treatments]
reference = {v: data[v].value_counts().idxmax() for v in features}
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
def complete(table, variables):
return rated.complete(table, variables, reference, data, months, event, horizon,
SURVIVAL_COLUMNS) # fmt: skip
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
try:
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
intrinsic) # fmt: skip
except (np.linalg.LinAlgError, ValueError):
return empty
tab["c2_estabilidad"] = np.nan
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket)
tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED)
tab["tipo"] = "factor de riesgo"
if treatment:
both = intrinsic + treatment
try:
tr = rated.odds_ratios(data, y, both, reference, "OR_muerte")
except (np.linalg.LinAlgError, ValueError):
tr = None
if tr is not None:
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)],
treatment) # fmt: skip
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
tab = pd.concat([tab, tr], ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False])
return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True)
def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]:
"""Per clinical scenario, the classified factors and treatments nearly all of its
members have (definitorios) or most have (mayoritarios)."""
from models import factors as rated
found = rated.classified(table) if len(table) else table
data = spec._combinations(members)
rows = []
for name, mask in scenario_masks(members, spec.scenarios).items():
if not mask.any() or found.empty:
continue
rows.append({
"escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
"n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found),
}) # fmt: skip
return rows
def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict:
"""The interpretability report's risk factors: the table and each scenario's summary."""
table = risk_factors(spec, model, members)
rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON
return {
"factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows},
"factores_escenarios": scenario_factors(spec, members, table),
} }
+389
View File
@@ -0,0 +1,389 @@
"""The EEG–ADOS-2 association (core.tea.association says what it relates): per biomarker,
zone and outcome, how a child's deviation from the age curve (z) goes with an altered
ADOS-2 item or a high CSS, adjusted for age and module.
- An item: Firth's penalised logistic regression of "altered" on z (the principal model; its
odds ratio, a 95 % profile-likelihood interval and a likelihood-ratio p), with a
cumulative-logit model of the item's level as sensitivity; the CSS the other way round.
- q: Benjamini–Hochberg within each biomarker.
- A child's probability: the principal model at her z (Firth's with the FLIC intercept, so
its probabilities average to the observed rate), and the reference child's (z = 0, the
cohort's mean age, the commonest module).
The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py)."""
import warnings
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from scipy import optimize, stats
from scipy.special import expit
from statsmodels.stats.multitest import multipletests
from core.tea import association as spec
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8
TOO_FEW = "too few data or no variation"
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
"""Item `number`'s algorithm score for each child whose module administers it."""
name, modules = spec.ITEMS[number]
if name not in frame or "module" not in frame:
return pd.Series(np.nan, index=frame.index)
v = pd.to_numeric(frame[name], errors="coerce")
v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2)
return v.where(frame["module"].isin(modules))
def has_items(frame: pd.DataFrame) -> bool:
scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1)
return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN
@dataclass
class Design:
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
the cohort's mean and each categorical one against its commonest level."""
predictor: str
numeric: dict[str, float] = field(default_factory=dict)
categorical: dict[str, list[str]] = field(default_factory=dict)
reference: dict[str, str] = field(default_factory=dict)
@classmethod
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
d = cls(predictor)
for a in (a for a in spec.ADJUST if a in t):
v = t[a]
if pd.api.types.is_numeric_dtype(v):
if v.astype(float).std() > 0:
d.numeric[a] = float(v.astype(float).mean())
continue
commonest = v.value_counts().index[0]
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
if levels:
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
return d
@property
def names(self) -> list[str]:
return [
"intercept",
self.predictor,
*self.numeric,
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
]
def matrix(self, t: pd.DataFrame) -> np.ndarray:
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()]
known = np.ones(len(t), bool)
for a, levels in self.categorical.items():
v = t[a].astype(str)
cols += [(v == x).to_numpy(float) for x in levels]
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy()
X = np.column_stack(cols)
X[~known] = np.nan
return X
def state(self) -> dict:
return {
"predictor": self.predictor,
"numeric": self.numeric,
"categorical": self.categorical,
"reference": self.reference,
}
@classmethod
def from_state(cls, s: dict) -> "Design":
return cls(
s["predictor"],
dict(s["numeric"]),
{k: list(v) for k, v in s["categorical"].items()},
dict(s["reference"]),
)
# Firth: the log-likelihood penalised by half the log-determinant of the information.
def _penalised(b, X, y) -> float:
eta = X @ b
w = expit(eta) * (1 - expit(eta))
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
def _gradient(b, X, y):
"""The penalised score and the information at `b`."""
p = expit(X @ b)
w = p * (1 - p)
info = X.T @ (X * w[:, None])
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
return X.T @ (y - p + leverage * (0.5 - p)), info
def _firth_fit(X, y, max_iter=200, tol=1e-10):
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
b = np.zeros(X.shape[1])
best = _penalised(b, X, y)
for _ in range(max_iter):
score, info = _gradient(b, X, y)
step, t = np.linalg.solve(info, score), 1.0
while t > 1e-8:
trial = _penalised(b + t * step, X, y)
if trial >= best - 1e-12:
break
t /= 2
b, best = b + t * step, trial
if np.max(np.abs(t * step)) < tol:
break
return b, best
def _firth_profile(value, j, X, y, start) -> float:
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
free = [k for k in range(X.shape[1]) if k != j]
def negative(bf):
b = np.empty(X.shape[1])
b[free], b[j] = bf, value
v = _penalised(b, X, y)
if not np.isfinite(v):
return 1e10, np.zeros(len(free))
return -v, -_gradient(b, X, y)[0][free]
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
each side of `centre`, searched in steps of `scale` (infinite if never)."""
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
limits = []
for sign in (-1, 1):
previous, limit = centre, sign * np.inf
for k in range(1, 80):
v = centre + sign * scale * k
if drop(v) > 0:
limit = optimize.brentq(drop, min(previous, v), max(previous, v))
break
previous = v
limits.append(limit)
return limits[0], limits[1]
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
return {
"model": model,
"n": n,
"coef": round(float(coef), 4),
"odds_ratio": round(float(np.exp(coef)), 4),
"ci_low": round(float(np.exp(low)), 4),
"ci_high": round(float(np.exp(high)), 4),
"p": round(p, 5),
"adjusted_for": ", ".join(design.names[2:]),
"reason": "",
**extra,
"state": {"design": design.state(), **state},
}
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW}
design = Design.of(d, predictor)
X = design.matrix(d)
b, top = _firth_fit(X, y)
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731
low, high = _interval(profile, b[1], top, max(se, 0.05))
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
# FLIC: the intercept refitted so the probabilities add up to the events.
eta = X[:, 1:] @ b[1:]
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing.
def _ordinal_nll(par, X, y, K) -> float:
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
eta = X @ par[K - 1 :]
n = len(y)
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
return -float(
np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None)))
)
def _ordinal_fit(X, y, K, fixed=None):
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
if fixed is None:
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
return r.x, float(r.fun)
j, value = fixed
free = [k for k in range(len(start)) if k != K - 1 + j]
def nll(q):
par = np.empty(len(start))
par[free], par[K - 1 + j] = q, value
return _ordinal_nll(par, X, y, K)
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW}
design = Design.of(d, predictor)
X = design.matrix(d)[:, 1:]
K = len(levels)
y = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _ordinal_fit(X, y, K)
beta = par[K - 1 :]
if abs(beta[0]) > 20:
return {**out, "reason": "does not converge (separation)"}
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731
low, high_ = _interval(profile, beta[0], -nll, 0.1)
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
inside = 0 < k < K
state = {
"beta": [float(v) for v in beta],
"threshold": float(theta[k - 1]) if inside else None,
"always": None if inside else float(k == 0),
}
return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K)
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
"""Each child's probability of the outcome under `fit`, and the reference child's."""
s = fit["state"]
X = Design.from_state(s["design"]).matrix(t)
if fit["model"] == "firth":
return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float(
expit(s["intercept"])
)
if s["threshold"] is None:
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]
return (
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
float(1 - expit(s["threshold"])),
)
def _guarded(fit, *args) -> dict:
try:
return fit(*args)
except (np.linalg.LinAlgError, ValueError) as error:
model = "firth" if fit is firth else "ordinal"
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
"""Every pair's principal and sensitivity models and its q: what the association is."""
if level == "auto":
level = "item" if has_items(cohort) else "domain"
rows = []
for pair in spec.pairs(level):
if pair["predictor"] not in cohort:
continue
d = cohort.copy()
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
if pair["kind"] == "item":
d["_level"] = item_scores(cohort, pair["outcome"])
d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna())
principal = _guarded(firth, d, "_yes", pair["predictor"])
sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED)
else:
d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce")
d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna())
principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH)
sensitivity = _guarded(firth, d, "_yes", pair["predictor"])
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
biomarkers = np.array([r["biomarker"] for r in rows])
q = np.full(len(rows), np.nan)
for b in dict.fromkeys(biomarkers):
mine = (biomarkers == b) & np.isfinite(p)
if mine.any():
q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5)
for r, v in zip(rows, q, strict=True):
r["q"] = None if np.isnan(v) else float(v)
return {"level": level, "n": len(cohort), "rows": rows}
def outcome_code(row: dict) -> str:
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
def associations(fitted: dict) -> list[dict]:
"""One row per pair: what the governance report and the record show."""
out = []
for r in fitted["rows"]:
f, s = r["principal"], r["sensitivity"]
ratio, other = f.get("odds_ratio"), s.get("odds_ratio")
out.append(
{
"biomarker": r["biomarker"],
"zone": r["zone"],
"kind": r["kind"],
"outcome": r["outcome"],
"outcome_code": outcome_code(r),
"event": f">={spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH}",
"model": f["model"],
"n": f["n"],
"odds_ratio": ratio,
"ci_low": f.get("ci_low"),
"ci_high": f.get("ci_high"),
"p": f.get("p"),
"q": r["q"],
"sens_model": s["model"],
"sens_odds_ratio": other,
"same_direction": None
if ratio is None or other is None
else bool(np.sign(ratio - 1) == np.sign(other - 1)),
"reason": f.get("reason", ""),
}
)
return out
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]:
"""Each child's probability under every estimated pair, and the reference child's."""
out = []
for r in fitted["rows"]:
f = r["principal"]
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
continue
t = cohort
if r["kind"] == "item":
t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])]
t = t[t[r["predictor"]].notna()]
if not len(t):
continue
found, reference = probability(f, t)
for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True):
if np.isfinite(p):
out.append(
{
"key": key,
"biomarker": r["biomarker"],
"zone": r["zone"],
"outcome_code": outcome_code(r),
"z": float(z),
"probability": round(float(p), 4),
"reference_probability": round(reference, 4),
}
)
return out
+8 -10
View File
@@ -8,12 +8,11 @@ mains, with the table's age) in worker processes; `tables` gives each scenario's
from the valid studies. from the valid studies.
""" """
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path from pathlib import Path
import pandas as pd import pandas as pd
from models import cluster
from models.tea.eeg.analysis import analyze from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS from models.tea.eeg.curves import SCENARIOS
@@ -34,9 +33,8 @@ def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path,
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(study: tuple[str, Path, float]) -> dict: def _one(key: str, edf: bytes, age: float) -> dict:
key, path, age = study a = analyze(edf, age_months=age, mains_hz=MAINS_HZ)
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=MAINS_HZ)
return { return {
"key": key, "key": key,
"age_months": age, "age_months": age,
@@ -46,11 +44,11 @@ def _one(study: tuple[str, Path, float]) -> dict:
} }
def measure(studies, workers: int = 4) -> list[dict]: def measure(studies) -> list[dict]:
"""Each study's verdict and features, in listing order.""" """Each study's verdict and features, in listing order, each a task on the cluster
context = multiprocessing.get_context("spawn") (models.cluster)."""
with ProcessPoolExecutor(workers, mp_context=context) as pool: # each task carries its recording: workers see no local folder
return list(pool.map(_one, studies)) return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]: def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
+143 -48
View File
@@ -1,27 +1,27 @@
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves """TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and (models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age. children whose diagnosis ruled TEA out, persistance.eeg.ruled_out) and scoring every
analysed EEG against the child's age. The math is the old platform's, proved on its HK1K
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its cohort by models/tests/test_eeg.py."""
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
or ages table that changes is measured again."""
import hashlib import hashlib
import json
import os
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date from datetime import date
from pathlib import Path
import mlflow.pyfunc import mlflow.pyfunc
import pandas as pd import pandas as pd
from joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
from core.tea import ados2
from core.tea import association as relation
from models import cluster
from models.jobs import EmptyCohort
from models.tea import association
from models.tea.eeg import analysis, curves, reference from models.tea.eeg import analysis, curves, reference
from persistance import eeg, registry, silver from persistance import eeg, registry, silver
MODELS = curves.SCENARIOS CURVES = curves.SCENARIOS
ASSOCIATION = "eeg-ados2" # trained on the champion curves' z: after they are promoted
MODELS = [*CURVES, ASSOCIATION]
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk) GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
@@ -40,39 +40,18 @@ class Baseline(mlflow.pyfunc.PythonModel):
for r in rows]) # fmt: skip for r in rows]) # fmt: skip
def _analyze(edf: str, birth) -> tuple[str, analysis.Analysis]:
return edf, analysis.analyze(eeg.signal(edf), birth)
def analyze() -> int: def analyze() -> int:
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt.""" """Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
pending = eeg.pending() pending = eeg.pending()
found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"]) done = cluster.run(
for r in pending)) # fmt: skip analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
get_reusable_executor().shutdown(wait=True) ) # one task per EEG
found = dict(zip((r["edf"] for r in pending), done, strict=True))
eeg.save_analyses(found) eeg.save_analyses(found)
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
return len(found) return len(found)
def _reference() -> tuple[str, list[dict]]:
"""The reference cohort's hash and each study's verdict and features, cached."""
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
studies = reference.listing(folder, ages)
digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text())
measured = reference.measure(studies, workers=os.cpu_count() or 4)
measured = [{**m, "key": str(m["key"])} for m in measured]
if path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(measured))
return digest, measured
@dataclass(frozen=True) @dataclass(frozen=True)
class Jobs: class Jobs:
"""The domain's model jobs (models.definitions): every curve is routine.""" """The domain's model jobs (models.definitions): every curve is routine."""
@@ -80,6 +59,9 @@ class Jobs:
def routine(self) -> list[str]: def routine(self) -> list[str]:
return list(MODELS) return list(MODELS)
def scored(self) -> list[str]:
return list(MODELS) # the curves, then the association on their scores
JOBS = Jobs() JOBS = Jobs()
@@ -89,27 +71,43 @@ def registered(name: str) -> str:
def train(name: str, as_of: date | None = None) -> int: def train(name: str, as_of: date | None = None) -> int:
"""A new version of one age curve, trained on the reference cohort's valid studies, if name == ASSOCIATION:
with its two reports: the cohort it learned from, and its centile curves.""" return _train_association(as_of)
digest, measured = _reference() return _train_curve(name, as_of)
def _train_curve(name: str, as_of: date | None = None) -> int:
"""A new version of one age curve, trained on the site's reference group as known on
`as_of` (today by default), with its two reports: the group it learned from, and its
centile curves."""
day = as_of or date.today()
measured = eeg.ruled_out(day)
if not measured:
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
table = reference.tables(measured)[name] table = reference.tables(measured)[name]
baseline = curves.train(table, name) baseline = curves.train(table, name)
valid = [m for m in measured if m["valid"] and m["error"] is None] ages = [m["age_months"] for m in measured]
technical = { technical = {
"model": name, "method": "age curves (weighted centiles on log age)", "model": name, "method": "age curves (weighted centiles on log age)",
"cohort": reference.NAME, "cohort_sha256": digest, "studies": len(measured), "cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day),
"valid_studies": len(valid), "studies": len(measured), "valid_studies": len(measured),
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)], "ages_months": [min(ages), max(ages)], "features": sorted(baseline),
"features": sorted(baseline),
} # fmt: skip } # fmt: skip
interpretability = {"model": name, "kind": "age_curves", "curves": baseline} interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))} metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
params = {"cohort": reference.NAME, "cohort_sha256": digest} params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
reports = {"technical_validation": technical, "interpretability": interpretability} reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
def score(name: str) -> int | None: def score(name: str) -> int | None:
if name == ASSOCIATION:
return _score_association()
return _score_curve(name)
def _score_curve(name: str) -> int | None:
"""The champion curve's scores of every analysed EEG: the metric's value, and each """The champion curve's scores of every analysed EEG: the metric's value, and each
electrode and zone it measures; None without a champion.""" electrode and zone it measures; None without a champion."""
found = registry.champion(registered(name)) found = registry.champion(registered(name))
@@ -117,7 +115,7 @@ def score(name: str) -> int | None:
return None return None
version, model = found version, model = found
baseline = model.unwrap_python_model().baseline baseline = model.unwrap_python_model().baseline
scenario, label = MODELS[name], f"{registered(name)}/{version}" scenario, label = CURVES[name], f"{registered(name)}/{version}"
rows = [] rows = []
for one in eeg.analysed(): for one in eeg.analysed():
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None) metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
@@ -139,3 +137,100 @@ def score(name: str) -> int | None:
"part": part, "site": site or None, **s}) # fmt: skip "part": part, "site": site or None, **s}) # fmt: skip
eeg.save_scores(name, rows) eeg.save_scores(name, rows)
return version return version
class Association(mlflow.pyfunc.PythonModel):
"""The fitted association as MLflow serves it: a cohort in, each child's probabilities."""
def __init__(self, fitted: dict):
self.fitted = fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return pd.DataFrame(association.score(self.fitted, model_input))
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""(fit, scored): every valid EEG of a child with an ADOS-2 (known by `as_of`), her age,
module, items, CSS and the z of each biomarker; fitted on each child's first EEG with
any z, every EEG scored."""
day = str(as_of) if as_of else None
rows = []
for r in eeg.association_inputs(relation.BIOMARKERS):
a = r["ados2"]
evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None
if day and (r["study_date"] > day or (evaluated and evaluated > day)):
continue
css = None
if evaluated and r["birth_date"]:
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
rows.append({"key": r["edf"], "person": r["person_id"], "age_months": r["age_months"],
"module": a.get("module"), "css": css,
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
**{k: v for k, v in r.items() if k.startswith("z_")}}) # fmt: skip
scored = pd.DataFrame(rows)
if scored.empty:
return scored, scored
predictors = [c for c in scored.columns if c.startswith("z_")]
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
return fit.drop(columns=["person"]), scored.drop(columns=["person"])
def _train_association(as_of: date | None = None) -> int:
"""A new version of the association, fitted on the site's children, with its reports:
the cohort and pairs it estimated, and the pairs themselves."""
fit, _ = association_cohort(as_of)
if fit.empty:
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
fitted = association.fit(fit)
pairs = association.associations(fitted)
estimated = [p for p in pairs if p["odds_ratio"] is not None]
technical = {
"model": ASSOCIATION, "method": "Firth logistic (items) / cumulative logit (CSS), "
"adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
"cohort": "site: children with an ADOS-2 and a valid EEG",
"as_of": str(as_of or date.today()),
"children": int(fitted["n"]), "level": fitted["level"], "pairs": len(pairs),
"estimated": len(estimated), "clear": sum(1 for p in estimated if (p["q"] or 1) < 0.05),
} # fmt: skip
interpretability = {"model": ASSOCIATION, "kind": "associations", "level": fitted["level"],
"children": int(fitted["n"]), "rows": pairs} # fmt: skip
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports)
def _score_association() -> int | None:
"""The champion association's probabilities for every scored EEG; None without one."""
found = registry.champion(registered(ASSOCIATION))
if found is None:
return None
version, model = found
fitted = model.unwrap_python_model().fitted
label = f"{registered(ASSOCIATION)}/{version}"
_, scored = association_cohort()
kept = ("biomarker", "zone", "kind", "outcome_code", "event", "n", "odds_ratio", "ci_low",
"ci_high", "p", "q", "sens_odds_ratio", "same_direction", "reason") # fmt: skip
pairs = [{**{k: p[k] for k in kept}, "model": label,
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
"metric": relation.BIOMARKERS[p["biomarker"]], "principal": p["model"],
"sensitivity": p["sens_model"]}
for p in association.associations(fitted) if p["odds_ratio"] is not None] # fmt: skip
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, or the CSS
if not scored.empty:
keys = scored["key"].tolist()
for n in relation.ITEMS:
items = association.item_scores(scored, n).tolist()
observed[relation.item_code(n)] = dict(zip(keys, items, strict=True))
observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), strict=True))
scores = []
for one in association.score(fitted, scored) if not scored.empty else []:
seen = observed.get(one["outcome_code"], {}).get(one["key"])
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
shown = None if seen is None or seen != seen else float(seen)
scores.append({**one, "edf": one["key"], "model": label, "key": f"{one['key']}|{pair}",
"observed": shown}) # fmt: skip
eeg.save_association(label, pairs, scores)
return version
+11
View File
@@ -11,8 +11,10 @@ dependencies = [
"mlflow-skinny", "mlflow-skinny",
"openai>=3.59.0", "openai>=3.59.0",
"splink>=5.0.0", "splink>=5.0.0",
"duckdb>=2.0.1",
"markitdown[docx,xlsx]>=0.1.9", "markitdown[docx,xlsx]>=0.1.9",
"ocrmypdf>=17.14.2", "ocrmypdf>=17.14.2",
"pikepdf>=10.0",
"pdfplumber>=0.11.11", "pdfplumber>=0.11.11",
"scikit-learn>=1.9.1", "scikit-learn>=1.9.1",
"scipy>=1.18.1", "scipy>=1.18.1",
@@ -22,6 +24,15 @@ 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]
# Where a Dask cluster runs the long batches (testing here); the product runs without it.
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
bayes = [
"arviz>=0.17",
"pymc>=5.10",
] ]
[build-system] [build-system]
+135
View File
@@ -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 {})
+34
View File
@@ -0,0 +1,34 @@
"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once."""
from datetime import date
import pandas as pd
from models.cacu import reports
def test_a_candidate_with_two_reasons_is_excluded_once():
"""Pins the totals, the pending rule, the people without a candidate and the as-of cut."""
rows = pd.DataFrame(
[
("eligible", "2025-01-01", None, None),
("two", "2025-01-01", None, "hysterectomy"),
("two", "2025-01-01", None, "under_18"),
("waiting", "2025-01-01", None, "no_index_result"),
("waiting_and_out", "2025-01-01", None, "no_index_result"),
("waiting_and_out", "2025-01-01", None, "prior_outcome"),
("after", "2025-07-01", None, "hysterectomy"),
],
columns=["person_id", "index_date", "index_sample_id", "criterion"],
)
found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30))
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
assert (found["pending"], found["without_candidate"]) == (1, 6)
assert found["by_reason"] == {
"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1,
} # fmt: skip
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
assert found["stage_by_reason"]["no_index_result"] == "index"
assert found["stage_counts_overlap"] is True
+21
View File
@@ -0,0 +1,21 @@
import json
import pytest
pytest.importorskip('pymc')
pytest.importorskip('arviz')
from models.cacu.bayes_development.synthetic_diagnostics import evaluate
def test_nuts_synthetic_artifact(tmp_path):
path = tmp_path / 'diagnostics.json'
report = evaluate(path, n=80, draws=40, tune=40, seed=31)
assert json.loads(path.read_text()) == report
assert report['scope'] == 'synthetic_cross_sectional_prevalence_only'
assert report['current_pim_comparison']['status'] == 'not_comparable'
assert report['chains'] == 2 and report['divergences'] >= 0
for parameter in report['parameters'].values():
assert parameter['ess_bulk'] > 0 and parameter['ess_tail'] > 0
assert parameter['rhat'] > 0
assert parameter['error'] == pytest.approx(parameter['mean'] - parameter['truth'])
+114
View File
@@ -0,0 +1,114 @@
import pytest
import numpy as np
from scipy.stats import norm
from models.cacu.bayes_development import prevalence_gibbs as PG
def test_normal_posterior_is_least_squares_under_a_flat_prior():
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no information."""
rng = np.random.default_rng(1)
X = np.column_stack([np.ones(200), rng.normal(size=200)])
z = X @ [0.5, -1.0] + rng.normal(size=200)
m, L = PG.normal_posterior(X, z, np.zeros(2), np.eye(2) * 1e-10)
assert np.allclose(m, np.linalg.lstsq(X, z, rcond=None)[0], atol=1e-6)
assert np.allclose(L @ L.T, np.linalg.inv(X.T @ X), rtol=1e-6)
def test_latent_sign_follows_g():
"""Fails if a truncated latent falls on the wrong side of zero."""
rng = np.random.default_rng(2)
g = rng.random(1000) < 0.5
z = PG.draw_latent(rng.normal(size=1000) * 3, g, rng)
assert np.all((z > 0) == g)
def test_prob_g_by_observation():
"""Fails if a tested positive is not certainly diseased, an untested woman does not keep her prior, or a tested
negative is not discounted by 1 - kappa."""
p, k = np.full(3, 0.2), 0.7
out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k)
assert out[0] == 1.0 and np.isclose(out[1], 0.2)
assert np.isclose(out[2], 0.2 * 0.3 / (0.2 * 0.3 + 0.8))
def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
"""Fails if, with kappa pinned by a strong prior, the chain misses the true probit coefficients of a simulated
cross-sectional sample (60 % tested, one test each)."""
rng = np.random.default_rng(3)
n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7
X = np.column_stack([np.ones(n), rng.random(n) < 0.4])
g = rng.random(n) < norm.cdf(X @ beta)
r = (rng.random(n) < 0.6).astype(int)
y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan)
out = PG.gibbs(X, r, y, np.zeros(2), np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=4)
assert np.allclose(out["beta"].mean(0), beta, atol=0.12)
assert abs(out["kappa"].mean() - 0.7) < 0.02
def test_referral_odds():
"""Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) / Phi(eta) for a tested woman
and the same with the survival function for an untested one."""
eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8
out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0]))
assert np.isclose(out[0], 1.0)
assert np.isclose(out[1], norm.cdf(-0.2) / norm.cdf(-1.0))
assert np.isclose(out[2], norm.sf(1.3) / norm.sf(0.5))
def _referral_sample(n=8000, seed=5):
"""Two cells: the protocol refers the abnormal one (84 %); the normal one is referred mostly when diseased
(3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell: Phi(-1.6) = 5.5 %."""
rng = np.random.default_rng(seed)
abnormal = (rng.random(n) < 0.2).astype(float)
X = np.column_stack([np.ones(n), abnormal])
g = rng.random(n) < norm.cdf(X @ [-1.6, 1.2])
U = np.column_stack([np.ones(n), abnormal])
arc = 1.0 - abnormal
r = (rng.random(n) < norm.cdf(U @ [-1.8, 2.8] + 1.5 * arc * g)).astype(int)
y = np.where(r == 1, g & (rng.random(n) < 0.7), np.nan)
return X, r, y, U, arc
def test_the_arc_removes_the_selection_bias():
"""Fails if ignoring who gets referred does not overstate the prevalence of the unreferred cell, or if the arc
with an informative prior on gamma_g does not bring it back to the truth (5.5 %)."""
X, r, y, U, arc = _referral_sample()
common = dict(b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6)
without = PG.gibbs(X, r, y, **common)
with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common)
assert norm.cdf(without["beta"][:, 0]).mean() > 0.2
assert abs(norm.cdf(with_arc["beta"][:, 0]).mean() - norm.cdf(-1.6)) < 0.02
assert abs(with_arc["delta"][:, -1].mean() - 1.5) < 0.3
def test_split_rhat():
"""Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different levels do not exceed 1.1."""
rng = np.random.default_rng(7)
assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01
assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1
def test_patterns_keep_every_woman():
"""Fails if collapsing identical women loses anyone or merges different observations."""
X, r, y, U, arc = _referral_sample(n=500)
d = PG.patterns(X, r, y, U, arc)
assert d["n"].sum() == 500
assert len(d["n"]) == len(np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0))
def test_summed_likelihood_matches_a_direct_sum():
pytest.importorskip("pymc") # optional dependency, not in the production environment
"""Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g) woman by woman."""
X, r, y, U, arc = _referral_sample(n=400)
beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2])
model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3))
point = model.initial_point()
point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta})
got = model.compile_logp(vars=model.potentials)(point)
p = norm.cdf(X @ beta)
pr = lambda shift: np.where(r == 1, norm.cdf(shift), norm.sf(shift))
py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0)
py0 = np.where((r == 1) & (y == 1), 0.0, 1.0)
direct = np.log(p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0).sum()
assert np.isclose(got, direct)
+83
View File
@@ -0,0 +1,83 @@
import numpy as np
import pandas as pd
import pytest
from models.cacu.development_firth import FirthFamily
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
@pytest.mark.parametrize('method', METHODS)
def test_methods_fit_simulated_data(method):
X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float)
y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0])
prediction = FirthFamily(method).fit(X, y).predict_proba(X)[:, 1]
assert np.isfinite(prediction).all() and ((prediction > 0) & (prediction < 1)).all()
def test_candidates_and_imputation_use_only_training_rows():
train = pd.DataFrame({'a': [0., 1., np.nan, 1.], 'copy': [0., 1., np.nan, 1.],
'absent': [np.nan] * 4})
assert _candidates(train, 0.7, 5) == ['a']
a, b = _matrix(train, pd.DataFrame({'a': [np.nan]}), ['a'])
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
def test_nested_cv_and_loocv_record_every_attempt():
X = pd.DataFrame({'a': [0, 0, 1, 1, 0, 1, 0, 1],
'b': [0, 1, 0, 1, 1, 0, 0, 1]})
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2)
assert report['development_only'] and report['max_subsets'] == 4
assert set(report['validation']) == {'cv', 'loocv'}
assert {a['method'] for a in report['attempts']} == set(METHODS)
assert all('variables' in a and 'error' in a for a in report['attempts'])
assert all(len(report['validation']['loocv'][m]['selected']) == len(X) for m in METHODS)
def test_budget_rejects_large_loocv_before_fitting():
X = pd.DataFrame({'a': [0, 1] * 10})
with pytest.raises(ValueError, match='exceeds configured limit'):
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
def test_development_job_is_not_a_production_score():
from core.models import DEVELOPMENT
from models.definitions import defs
assert 'cacu.cin2_firth_development' in DEVELOPMENT
job = defs.get_job_def('cacu_development_evaluation')
assert job.name == 'cacu_development_evaluation'
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
import dagster as dg
import mlflow
from mlflow.tracking._tracking_service import utils as tracking_utils
from models.cacu import development_selection, encoders, features
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
from persistance import gold
monkeypatch.setenv('MLFLOW_TRACKING_URI', (tmp_path / 'mlruns').as_uri())
monkeypatch.setenv('MLFLOW_ALLOW_FILE_STORE', 'true')
monkeypatch.setattr(tracking_utils, '_tracking_uri', tracking_utils._tracking_uri)
mlflow.set_tracking_uri((tmp_path / 'mlruns').as_uri())
patients = [str(i) for i in range(8)]
events = pd.DataFrame({'person_id': patients, 'date': ['2025-01-01'] * 8,
'index_date': ['2025-01-01'] * 8})
encoded = pd.DataFrame({'person_id': patients, 'index_date': ['2025-01-01'] * 8,
'factor': [0, 0, 1, 1, 0, 1, 0, 1]})
outcomes = pd.DataFrame({'person_id': patients, 'known': [True] * 8,
'y': [0, 1, 0, 1, 0, 1, 1, 0]})
monkeypatch.setattr(gold, 'evidence_timelines', lambda *a: events)
monkeypatch.setattr(gold, 'cervical_forms', lambda *a: pd.DataFrame())
monkeypatch.setattr(encoders, 'encode', lambda *a: encoded)
monkeypatch.setattr(features, 'windowed_outcome', lambda *a: outcomes)
real = development_selection.evaluate
monkeypatch.setattr(development_selection, 'evaluate',
lambda X, y, **kw: real(X, y, candidate_limit=1, subset_limit=1,
outer_folds=2, inner_folds=2, **kw))
with dg.build_op_context() as context:
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of='2026-01-01'))
artifacts = mlflow.MlflowClient().list_artifacts(run_id, 'reports')
assert [a.path for a in artifacts] == ['reports/development_evaluation.json']
+129
View File
@@ -0,0 +1,129 @@
"""The binary encoders read only what was available at the index, and never turn an
absent value into 0."""
import numpy as np
import pandas as pd
import pytest
from models.cacu.encoders import FINDINGS, encode
INDEX = "2025-06-10"
def event(day, kind, code=None, person="p1", table="cervical_cytology", sample=None,
clinical=None, available=None): # fmt: skip
return {
"person_id": person, "index_date": INDEX, "date": day, "type": kind,
"value_code": code, "value_num": np.nan, "source_table": table,
"source_id": sample or day, "evidence_date": clinical, "source_available_at": available,
} # fmt: skip
def form(sample, report, person="p1", **fields):
empty = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
return {"person_id": person, "sample_date": sample, "report_date": report} | empty | fields
def row(events, forms=None, person="p1"):
found = encode(pd.DataFrame(events), None if forms is None else pd.DataFrame(forms))
return found.set_index("person_id").loc[person].drop("index_date").astype(float)
def test_nothing_known_is_all_missing():
found = row([event(INDEX, "cytology", "satisfactory")])
assert found.isna().all()
def test_values_and_missing():
found = row([
event("1980-06-11", "birth", table="person"),
event("2025-01-15", "bethesda", "LSIL", sample="2025-01-10"),
event("2025-01-15", "hpv", "positive", sample="2025-01-10"),
event("2025-01-15", "hpv_16", "negative", sample="2025-01-10"),
event(INDEX, "cervix_appearance", "lesion"),
event(INDEX, "presenting_symptom", "not-a-code"),
]) # fmt: skip
assert found["age__35-44"] == 1 and found["age__45-54"] == 0
assert found["bethesda__LSIL"] == 1 and found["bethesda__HSIL"] == 0
assert found["cytology_ascus_plus"] == 1 and found["cytology_hsil_plus"] == 0
assert found["hpv_positive"] == 1 and found["hpv_16_positive"] == 0
assert np.isnan(found["hpv_18_positive"])
# one genotype negative and the other unreported is unknown, not negative
assert np.isnan(found["hpv_16_or_18_positive"])
assert found["cervix_appearance__lesion"] == 1 and found["cervix_appearance__healthy"] == 0
assert found.filter(like="presenting_symptom").isna().all() # ambiguous value
assert found.filter(like="prior_").isna().all()
@pytest.mark.parametrize("positive, other, expected", [
("positive", None, 1.0), ("negative", "negative", 0.0), ("negative", "positive", 1.0),
]) # fmt: skip
def test_genotypes_combined(positive, other, expected):
events = [event("2025-01-15", "hpv_16", positive)]
if other:
events.append(event("2025-01-15", "hpv_18", other))
assert row(events)["hpv_16_or_18_positive"] == expected
def test_nothing_later_than_the_index_is_read():
base = [event(INDEX, "cytology", "satisfactory")]
later = [
event("2025-06-20", "bethesda", "HSIL", sample=INDEX), # the index sample's report
event("2025-06-20", "hpv", "positive", sample=INDEX),
event("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
event("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
# procedures of the index day may be the outcome
event(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
event(INDEX, "colposcopy", table="clinical_note"),
event(INDEX, "treatment", table="clinical_note"),
event("2025-08-01", "history", table="clinical_note"),
# standalone evidence without an availability date: its onset says nothing of it
event("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence"),
] # fmt: skip
forms = [form(INDEX, "2025-06-20", adequacy="unsatisfactory", finding_atrophy=True)]
pd.testing.assert_series_equal(row(base + later, forms), row(base))
def test_available_by_the_index_day_is_read():
found = row([
event("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
event("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence", available="2024-01-01"),
]) # fmt: skip
assert found["cytology_hsil_plus"] == 1 and found["history_hysterectomy"] == 1
def test_prior_procedures_and_referral():
found = row([
event("2025-01-15", "bethesda", "HSIL", sample="2025-01-10"),
event("2025-03-01", "colposcopy", table="clinical_note"),
event("2025-03-01", "biopsy_order", table="cervical_biopsy"),
event("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
]) # fmt: skip
assert found["prior_colposcopy"] == 1 and found["prior_biopsy_order"] == 1
assert found["prior_biopsy_lsil_plus"] == 1 and found["prior_biopsy_hsil_plus"] == 0
assert found["referral_high_grade"] == 1
assert np.isnan(found["prior_treatment"])
def test_form_fields_come_from_the_latest_report():
forms = [
form("2024-01-10", "2024-01-20", screening_history="never", finding_atrophy=True),
form("2025-01-10", "2025-01-20", adequacy="satisfactory", finding_candida=1),
]
found = row([event(INDEX, "cytology")], forms)
assert found["screening_history__never"] == 1
assert found["sample_unsatisfactory"] == 0 and found["finding_candida"] == 1
assert np.isnan(found["finding_atrophy"])
def test_members_are_kept_apart():
events = [event("2025-01-15", "hpv", "positive"), event(INDEX, "cytology", person="p2")]
assert np.isnan(row(events, person="p2")["hpv_positive"])
def test_a_timeline_without_availability_is_refused():
events = pd.DataFrame([event(INDEX, "cytology")]).drop(columns="source_available_at")
with pytest.raises(ValueError, match="source_available_at"):
encode(events)
+30 -3
View File
@@ -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,25 @@ 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)
(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
+18
View File
@@ -0,0 +1,18 @@
import json
import numpy as np
import pandas as pd
from models.cacu.specs import _rows
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
members = pd.DataFrame([
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
])
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5),
("cytology", "hpv"))
assert [json.loads(v) for v in result.input_values] == [
{"cytology": "NILM", "hpv": 0}, {"cytology": "NILM", "hpv": 0},
{"cytology": "HSIL", "hpv": 1}, {"cytology": "HSIL", "hpv": 1}]
+1 -1
View File
@@ -263,7 +263,7 @@ def test_metric_values(analyses):
def _measure_reference(): def _measure_reference():
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv") studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
measured = reference.measure(studies, WORKERS) measured = reference.measure(studies)
CACHE.parent.mkdir(parents=True, exist_ok=True) CACHE.parent.mkdir(parents=True, exist_ok=True)
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured})) CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
return measured return measured
+51
View File
@@ -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) == []
+40
View File
@@ -0,0 +1,40 @@
import numpy as np
import pandas as pd
from models.cacu.pim import Fit, ISpline, Mixture
def test_unestimable_covariances_never_produce_zero_width_intervals():
baseline = ISpline((0.0, 1.0, 2.0), 2)
params = np.zeros(1 + baseline.n_params)
X, Z = np.ones((1, 1)), np.empty((1, 0))
good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True)
assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all()
for covariance in (np.full((len(params), len(params)), np.nan),
-np.eye(len(params)), np.zeros((len(params), len(params)))):
broken = Fit(1, 0, baseline, params, covariance, 0, True)
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
def test_frozen_parameter_only_invalidates_horizons_it_affects():
baseline = ISpline((0.0, 1.0, 2.0), 2)
params = np.zeros(1 + baseline.n_params)
covariance = np.eye(len(params))
covariance[1, :] = np.nan
covariance[:, 1] = np.nan
fitted = Fit(1, 0, baseline, params, covariance, 0, True)
variance = fitted.risk_with_variance(np.ones((1, 1)), np.empty((1, 0)), [0, 1])[1]
assert np.isfinite(variance[0, 0])
assert np.isnan(variance[0, 1])
def test_diagnostics_count_rows_without_intervals():
baseline = ISpline((0.0, 1.0, 2.0), 2)
params = np.zeros(1 + baseline.n_params)
model = Mixture((0, 1), (), (), {})
model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)}
model.seen_ = {(): {}}
report = model.variance_diagnostics(pd.DataFrame(index=range(2)))
assert report['strata'][0]['rows_without_interval'] == 2
assert report['strata'][0]['negative_variances']
assert report['strata'][0]['status'] == 'not_estimable'
+13 -12
View File
@@ -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
@@ -68,16 +69,17 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW))) drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW)))
platform.save("pipelines", "cama_reference", drawn) platform.save("pipelines", "cama_reference", drawn)
platform.ingest("cama_reference") platform.ingest("cama_reference")
# What the training job reads (models.cama.specs), from that platform. # 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 models.cama.specs import MODELS; " platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
f"pd.to_pickle(MODELS['recurrence'].datasets(), {str(out)!r})") # fmt: skip f"pd.to_pickle({{s: pd.DataFrame(nodes.rows('cama_reference', s)) "
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")
@@ -154,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():
@@ -163,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}
@@ -205,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]
@@ -219,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"])
@@ -261,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]
+13 -7
View File
@@ -6,7 +6,8 @@ one SQL Server table, the institute's forms beside what outsourced labs send bac
is a document of its own on its cytology's order; pathology comes scanned, the name surname is a document of its own on its cytology's order; pathology comes scanned, the name surname
first and no birth date; some forms say "MA." for María or misspell the name and leave the first and no birth date; some forms say "MA." for María or misspell the name and leave the
employee number out; some HPV reports were re-issued the other way; two women share a name. employee number out; some HPV reports were re-issued the other way; two women share a name.
Medical notes (the colposcopy clinic's, oncology's) and death notes are the institute's forms. Medical notes (the colposcopy clinic's, oncology's, neurology's), death notes and TEA's
M-CHAT, ADOS-2 and EEG reports are the institute's forms.
""" """
import json import json
@@ -15,19 +16,24 @@ from datetime import date
from core import catalog from core import catalog
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
FIELDS = { FIELDS = {
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16", "cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18"), "hpv_18"),
"cervical_biopsy": ("request_date", "report_date", "histology"), "cervical_biopsy": ("request_date", "report_date", "histology"),
"mammography": ("exam_date", "report_date", "adequacy", "birads"), "mammography": ("exam_date", "report_date", "adequacy", "birads"),
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade", "breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"), "er", "pr", "her2", "ki67_pct", "size_mm", "positive_nodes", "stage"),
"breast_treatment": ("start_date", "kind"), "breast_treatment": ("start_date", "kind"),
"breast_recurrence": ("diagnosis_date", "site"),
"clinical_note": ("note_date", "specialty", "icd10"), "clinical_note": ("note_date", "specialty", "icd10"),
"death": ("death_date",), "death": ("death_date",),
"mchat": ("screening_date", "score"),
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
"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"} NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
def value(field, v): def value(field, v):
@@ -104,7 +110,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
# the documents say is read (a scan's columns can come back out of order, and a value its # the documents say is read (a scan's columns can come back out of order, and a value its
# pattern doesn't find is left out, never guessed). A scan can misread one valid code as # pattern doesn't find is left out, never guessed). A scan can misread one valid code as
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's # another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
# values, each listed. # values (one, on a site too small for a rate), each listed.
at = {r["where"]: r for r in truth} at = {r["where"]: r for r in truth}
place = {r: f"ResultadoSubrogado:{i}" place = {r: f"ResultadoSubrogado:{i}"
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
@@ -118,7 +124,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
): ):
got = next((v for v in values if v is not None), None) got = next((v for v in values if v is not None), None)
mine.setdefault(record, {})[field] = value(field, got) mine.setdefault(record, {})[field] = value(field, got)
assert mine, entity assert mine or not any(said(r, entity) for r in truth), entity
stated = read = scanned = 0 stated = read = scanned = 0
missed: Counter = Counter() missed: Counter = Counter()
wrong = [] wrong = []
@@ -134,7 +140,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
stated, read = stated + len(truly), read + len(got) stated, read = stated + len(truly), read + len(got)
missed.update(set(truly) - set(got)) missed.update(set(truly) - set(got))
assert read >= 0.95 * stated, (entity, read, stated, missed) assert read >= 0.95 * stated, (entity, read, stated, missed)
assert len(wrong) <= 0.01 * scanned, (entity, wrong) assert len(wrong) <= max(1, 0.01 * scanned), (entity, wrong)
# A row a rule held because of a value (a scan misread) is held because it is wrong: # A row a rule held because of a value (a scan misread) is held because it is wrong:
# never loaded, and a reviewer sees it. # never loaded, and a reviewer sees it.
+29
View File
@@ -180,3 +180,32 @@ def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")] original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max() gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max()
print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}") print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}")
# The original's names for the categories both rate alike (stage, grade, receptors).
SAME = {
("Estadio", "IV"): ("stage", "IV"), ("Estadio", "III"): ("stage", "III"),
("Estadio", "II"): ("stage", "II"), ("Estadio", "0 (in situ)"): ("stage", "0"),
("Grado_histologico", "G3"): ("grade", "3"), ("Grado_histologico", "G1"): ("grade", "1"),
("Receptor_progesterona", "Negativo"): ("pr", "negative"),
} # fmt: skip
def test_risk_factors_rate_as_the_originals(trained):
"""The risk factors of death by 18 months (models.factors, as `06_factores_riesgo.py`)
on the same SEER cases: the same direction for every category both rate, the same class
for stage and grade, odds ratios within 20 % and 18-month survival within 0.05. The
original also rates the stability of its stepwise selection and reads the Markov blanket
of a learned network; the platform's model has neither stepwise selection nor PR among
its network's parents, so PR negative is "sugerente" here and "robusto" there."""
spec, model, _, data = trained
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
ours = survival.risk_factors(spec, model, members).set_index(["variable", "categoria"])
theirs = _original("factores_riesgo.csv").set_index(["variable", "categoria"])
for key, mine in SAME.items():
a, b = theirs.loc[key], ours.loc[mine]
assert b["clasificacion"].split()[0] == a["clasificacion"].split()[0], key
if key[0] != "Receptor_progesterona":
assert b["clasificacion"] == a["clasificacion"], key
assert b["OR_muerte"] == pytest.approx(a["OR_muerte"], rel=0.2), key
assert b["S_categoria"] == pytest.approx(a["S18_categoria"], abs=0.05), key