Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc78cb52c1 | |||
| cc5cfd1792 | |||
| 984d168da7 | |||
| daff410b46 | |||
| 04c9b3124b | |||
| f99cca5176 | |||
| aca4c9d58a | |||
| a1e2e07e0c | |||
| 17a60ff68d | |||
| efa2c2793e | |||
| 3a033efc1b | |||
| d27b585560 | |||
| 1feedad79a | |||
| da14e4ea8e | |||
| fe1f284e00 | |||
| d392cc02a5 | |||
| 8a860c698f | |||
| 6e6c5bb81b | |||
| d27319ad1f | |||
| b5480e8bbb | |||
| dbbea0b16e | |||
| 76e88d0779 | |||
| 8548eb8d9e | |||
| 1a1ea5c7a9 |
@@ -0,0 +1,20 @@
|
||||
# Fundamento bayesiano en desarrollo
|
||||
|
||||
`prevalence_gibbs.py` y sus pruebas proceden de `edgar/bayes-pim`, commit
|
||||
`1cef69be90a7a9ea30378118cd2a2c9fa312943e`. Solo se cambió el import de las
|
||||
pruebas. El módulo incluye Gibbs de prevalencia transversal y funciones NUTS
|
||||
con importación diferida de PyMC; no está conectado a producción ni a Dagster.
|
||||
|
||||
Esto **no implementa todavía** el modelo longitudinal: faltan los módulos de
|
||||
Markov y Klausch, el adaptador de visitas gold con fecha de disponibilidad,
|
||||
la ejecución NUTS, y el artefacto de diagnóstico y comparación. El original
|
||||
usa CIN3+ y categorías de biopsia que esta plataforma no puede identificar
|
||||
por separado; no se deben transformar HSIL o CIN2+ en CIN3+. Su fitting
|
||||
además importa `models.cacu.cin2_pim.likelihood`, que no existe aquí: hay que
|
||||
verificar matemáticamente la equivalencia con el PIM actual antes de conectar
|
||||
las verosimilitudes. La disponibilidad temporal y la definición del desenlace
|
||||
se deben resolver antes de entrenar con datos reales.
|
||||
|
||||
No se añadieron PyMC ni otras dependencias al entorno de producción. El modelo
|
||||
se mantiene únicamente como código de investigación, sin registro, promoción,
|
||||
servicio de predicciones ni entrenamiento con datos de pacientes.
|
||||
@@ -0,0 +1,267 @@
|
||||
"""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)
|
||||
|
||||
def log_phi(v):
|
||||
# log Phi(v), stable in the tails
|
||||
return pm.logcdf(pm.Normal.dist(0.0, 1.0), v)
|
||||
|
||||
with pm.Model() as model:
|
||||
beta = pm.MvNormal("beta", mu=np.asarray(b0, float), cov=np.asarray(B0, float))
|
||||
kappa = pm.Beta("kappa", *kappa_ab)
|
||||
eta = pt.as_tensor(d["X"]) @ beta
|
||||
log_g1, log_g0 = log_phi(eta), log_phi(-eta) # log P(g=1), log P(g=0)
|
||||
log_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,85 @@
|
||||
"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import brentq
|
||||
from scipy.special import expit
|
||||
from sklearn.base import BaseEstimator, ClassifierMixin
|
||||
from sklearn.exceptions import ConvergenceWarning
|
||||
|
||||
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
|
||||
|
||||
|
||||
class ConvergenceError(RuntimeError):
|
||||
"""Raised when the remaining Newton step fails the convergence check."""
|
||||
|
||||
|
||||
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
|
||||
"""Fit logistic regression and return the fitted solver and leverages.
|
||||
|
||||
Check the remaining Newton step directly because numerical precision can
|
||||
affect the solver's convergence flag.
|
||||
"""
|
||||
y = np.asarray(y)
|
||||
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
|
||||
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
|
||||
y = y.astype(int, copy=False)
|
||||
|
||||
from firthmodels import FirthLogisticRegression
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", ConvergenceWarning)
|
||||
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
|
||||
X, y, sample_weight=sample_weight
|
||||
)
|
||||
design = np.column_stack([np.ones(len(y)), X])
|
||||
weights = np.ones(len(y)) if sample_weight is None else sample_weight
|
||||
p = expit(model.intercept_ + X @ model.coef_)
|
||||
w = weights * p * (1 - p)
|
||||
info = design.T @ (w[:, None] * design)
|
||||
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
|
||||
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
|
||||
step = np.abs(np.linalg.solve(info, score)).max()
|
||||
if not np.isfinite(step) or step >= 1e-4:
|
||||
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
|
||||
return model, h
|
||||
|
||||
|
||||
class FirthFamily(ClassifierMixin, BaseEstimator):
|
||||
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
|
||||
|
||||
def __init__(self, method="firth"):
|
||||
self.method = method
|
||||
|
||||
def fit(self, X, y):
|
||||
"""Fit the selected method to a binary outcome."""
|
||||
if self.method not in ("firth", "flic", "flac"):
|
||||
raise ValueError(
|
||||
f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'."
|
||||
)
|
||||
X = np.asarray(X, float)
|
||||
firth, h = solve_logistic(X, y)
|
||||
y = np.asarray(y, int)
|
||||
self.classes_ = np.array([0, 1])
|
||||
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
|
||||
|
||||
if self.method == "flic":
|
||||
eta = X @ self.coef_
|
||||
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
|
||||
|
||||
elif self.method == "flac":
|
||||
# Pseudo-observations use both outcomes, each with half the leverage.
|
||||
g = np.repeat([0, 1, 1], len(y))
|
||||
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
|
||||
self.y_aug_ = np.concatenate([y, y, 1 - y])
|
||||
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
|
||||
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
|
||||
# Predict on original observations, where the indicator is zero.
|
||||
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
|
||||
return self
|
||||
|
||||
def predict_proba(self, X):
|
||||
"""Return probabilities for classes 0 and 1 in that order."""
|
||||
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
|
||||
return np.column_stack([1 - p, p])
|
||||
@@ -0,0 +1,193 @@
|
||||
"""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 as expit
|
||||
from scipy.special import logit
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
|
||||
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
|
||||
|
||||
from models.cacu.development_firth import FirthFamily
|
||||
|
||||
METHODS = ("firth", "flic", "flac")
|
||||
|
||||
|
||||
def _candidates(X, coverage, limit):
|
||||
eligible = []
|
||||
for name in sorted(X.columns):
|
||||
col = pd.to_numeric(X[name], errors="coerce")
|
||||
known = col.dropna()
|
||||
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
|
||||
eligible.append((name, col.notna().mean()))
|
||||
# Perfectly identical or complementary observed columns are not distinguishable.
|
||||
chosen = []
|
||||
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
|
||||
a = X[name]
|
||||
if any(
|
||||
((a == X[other]) | (a.isna() & X[other].isna())).all()
|
||||
or ((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
|
||||
for other in chosen
|
||||
):
|
||||
continue
|
||||
chosen.append(name)
|
||||
if len(chosen) == limit:
|
||||
break
|
||||
return chosen
|
||||
|
||||
|
||||
def _matrix(train, test, columns):
|
||||
tr = train[list(columns)].to_numpy(dtype=float)
|
||||
te = test[list(columns)].to_numpy(dtype=float)
|
||||
if tr.shape[1] and np.isnan(tr).all(axis=0).any():
|
||||
raise ValueError("predictor absent in training partition")
|
||||
median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([])
|
||||
tr, te = np.where(np.isnan(tr), median, tr), np.where(np.isnan(te), median, te)
|
||||
if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1:
|
||||
raise ValueError("collinear predictors in training partition")
|
||||
return tr, te
|
||||
|
||||
|
||||
def _predict(train, y, test, columns, method):
|
||||
tr, te = _matrix(train, test, columns)
|
||||
if not columns:
|
||||
return np.repeat(np.mean(y), len(test))
|
||||
return FirthFamily(method).fit(tr, y).predict_proba(te)[:, 1]
|
||||
|
||||
|
||||
def _metrics(y, probability):
|
||||
y, p = np.asarray(y), np.asarray(probability)
|
||||
valid = np.isfinite(p)
|
||||
if valid.sum() != len(y) or len(np.unique(y)) != 2:
|
||||
return {
|
||||
"auc": None,
|
||||
"brier": None,
|
||||
"calibration_intercept": None,
|
||||
"calibration_slope": None,
|
||||
"log_loss": None,
|
||||
}
|
||||
logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1)
|
||||
calibration = LogisticRegression(C=1e6).fit(logits, y)
|
||||
return {
|
||||
"auc": float(roc_auc_score(y, p)),
|
||||
"brier": float(brier_score_loss(y, p)),
|
||||
"calibration_intercept": float(calibration.intercept_[0]),
|
||||
"calibration_slope": float(calibration.coef_[0, 0]),
|
||||
"log_loss": float(log_loss(y, p, labels=[0, 1])),
|
||||
}
|
||||
|
||||
|
||||
def evaluate(
|
||||
X: pd.DataFrame,
|
||||
y,
|
||||
*,
|
||||
coverage=0.7,
|
||||
candidate_limit=5,
|
||||
subset_limit=2,
|
||||
outer_folds=3,
|
||||
inner_folds=2,
|
||||
seed=17,
|
||||
max_fits=100000,
|
||||
):
|
||||
"""Evaluate Firth/FLIC/FLAC with nested stratified CV and nested leave-one-out.
|
||||
|
||||
A fixed upper bound (default five candidates, pairs at most) permits at most 16 subsets
|
||||
including the intercept. Each method selects a subset by inner out-of-fold log loss for
|
||||
every outer split; all attempted subsets and failures are recorded.
|
||||
"""
|
||||
X = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce")
|
||||
y = np.asarray(y)
|
||||
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
|
||||
raise ValueError("one known binary outcome is required per row")
|
||||
if min(np.bincount(y.astype(int), minlength=2)) < max(outer_folds, inner_folds + 1):
|
||||
raise ValueError("insufficient members of each outcome for nested CV and LOOCV")
|
||||
if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit:
|
||||
raise ValueError("candidate and subset limits exceed the supported bounds")
|
||||
max_subsets = sum(
|
||||
math.comb(candidate_limit, k) for k in range(min(candidate_limit, subset_limit) + 1)
|
||||
)
|
||||
estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1)
|
||||
if estimated_fits > max_fits:
|
||||
raise ValueError(f"estimated {estimated_fits} fits exceeds configured limit {max_fits}")
|
||||
attempted, outputs = [], {}
|
||||
started = time.monotonic()
|
||||
plans = {
|
||||
"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
|
||||
"loocv": LeaveOneOut().split(X, y),
|
||||
}
|
||||
for plan, splits in plans.items():
|
||||
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
|
||||
selected = {m: [] for m in METHODS}
|
||||
for fold, (train_idx, test_idx) in enumerate(splits):
|
||||
train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int)
|
||||
candidates = _candidates(train, coverage, candidate_limit)
|
||||
subsets = [()] + [
|
||||
c
|
||||
for size in range(1, min(len(candidates), subset_limit) + 1)
|
||||
for c in itertools.combinations(candidates, size)
|
||||
]
|
||||
inner = list(
|
||||
StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain)
|
||||
)
|
||||
for method in METHODS:
|
||||
ranking = []
|
||||
for columns in subsets:
|
||||
probs = np.full(len(train), np.nan)
|
||||
error = None
|
||||
try:
|
||||
for a, b in inner:
|
||||
probs[b] = _predict(
|
||||
train.iloc[a], ytrain[a], train.iloc[b], columns, method
|
||||
)
|
||||
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
|
||||
ranking.append((loss, len(columns), columns))
|
||||
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
|
||||
loss, error = None, type(exc).__name__
|
||||
attempted.append(
|
||||
{
|
||||
"validation": plan,
|
||||
"fold": fold,
|
||||
"method": method,
|
||||
"variables": list(columns),
|
||||
"inner_log_loss": loss,
|
||||
"error": error,
|
||||
}
|
||||
)
|
||||
_, _, best = min(ranking)
|
||||
selected[method].append(list(best))
|
||||
try:
|
||||
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
|
||||
except (ValueError, np.linalg.LinAlgError, RuntimeError):
|
||||
pass
|
||||
outputs[plan] = {
|
||||
m: {
|
||||
"metrics": _metrics(y, predictions[m]),
|
||||
"selected": selected[m],
|
||||
"unscored": int(np.isnan(predictions[m]).sum()),
|
||||
"stability": {
|
||||
name: sum(name in cols for cols in selected[m]) for name in X.columns
|
||||
},
|
||||
}
|
||||
for m in METHODS
|
||||
}
|
||||
return {
|
||||
"development_only": True,
|
||||
"candidate_limit": candidate_limit,
|
||||
"subset_limit": subset_limit,
|
||||
"coverage_minimum": coverage,
|
||||
"max_subsets": max_subsets,
|
||||
"maximum_fits": estimated_fits,
|
||||
"estimated_seconds_at_50ms_per_fit": estimated_fits * 0.05,
|
||||
"elapsed_seconds": time.monotonic() - started,
|
||||
"source": "edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728",
|
||||
"attempts": attempted,
|
||||
"validation": outputs,
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her
|
||||
index date. NaN is missing: an absent value is never 0. No model reads these; they are
|
||||
there for when one does.
|
||||
|
||||
Only what was available at the index is read (see `visible`): the index sample's results,
|
||||
reported after it, are missing when the index is the sample day.
|
||||
|
||||
Inputs are the gold timeline with its `evidence_date` and `source_available_at`
|
||||
(persistance.gold.evidence_timelines) and, for the form fields gold does not carry, the
|
||||
wide silver cytology (persistance.gold.cervical_forms)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu, catalog
|
||||
from models.cacu.features import _referral_grade, _worst, prepared
|
||||
from models.cacu.specs import _REFERRAL
|
||||
from models.survival import age_group, band
|
||||
|
||||
# What was done to her before the index: the index day's own is left out, as it may be
|
||||
# (or follow from) the outcome.
|
||||
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
|
||||
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
|
||||
GENOTYPES = cacu.HPV_GENOTYPE_FIELDS
|
||||
EVIDENCE_TABLE = "cacu_eligibility_evidence"
|
||||
|
||||
|
||||
def _codes(field: str) -> list[str]:
|
||||
return list(catalog.studies()["cervical_cytology"].fields[field].codes)
|
||||
|
||||
|
||||
FINDINGS = tuple(
|
||||
name for name, f in catalog.studies()["cervical_cytology"].fields.items()
|
||||
if name.startswith("finding_") and f.type == "boolean"
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _day(values: pd.Series) -> pd.Series:
|
||||
"""The calendar day of dates or ISO timestamps (as written); empty stays NaT."""
|
||||
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
|
||||
|
||||
|
||||
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each member's events available at her index, with her index date:
|
||||
|
||||
- dated (a result: reported) and, if it has one, clinically dated by the index;
|
||||
- `source_available_at`, when the source gave it, by the index day. When it gave none,
|
||||
the event's date stands, except for standalone eligibility evidence, dated by its
|
||||
clinical onset: that is left out, as the cohort rules do;
|
||||
- procedures and diagnoses strictly before the index day.
|
||||
|
||||
`known_at` (when the platform loaded it) is not read."""
|
||||
found = events.drop(columns="index_date", errors="ignore").merge(
|
||||
members[["person_id", "index_date"]], on="person_id"
|
||||
)
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
date, clinical = _day(found["date"]), _day(found["evidence_date"])
|
||||
available = _day(found["source_available_at"])
|
||||
keep = (date <= index) & (clinical.isna() | (clinical <= index))
|
||||
undated = available.isna() & (found["source_table"] != EVIDENCE_TABLE)
|
||||
keep &= undated | (available <= index)
|
||||
earlier = (date < index) & (clinical.isna() | (clinical < index))
|
||||
hysterectomy = (found["type"] == "gynecologic_condition") & (
|
||||
found["value_code"] == "hysterectomy"
|
||||
)
|
||||
keep &= earlier | ~(found["type"].isin(PROCEDURES) | hysterectomy)
|
||||
return prepared(found[keep])
|
||||
|
||||
|
||||
def _flag(known: pd.Series, true: pd.Series) -> pd.Series:
|
||||
"""1.0 / 0.0 where `known`, NaN elsewhere."""
|
||||
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
|
||||
|
||||
|
||||
def _one_hot(values: pd.Series, prefix: str, codes: list[str]) -> dict[str, pd.Series]:
|
||||
"""One column per code; a value that is none of them is missing, not 0 in all."""
|
||||
known = values.isin(codes)
|
||||
return {f"{prefix}__{code}": _flag(known, values == code) for code in codes}
|
||||
|
||||
|
||||
def _present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""1 when recorded; NaN otherwise (no record does not show it never happened)."""
|
||||
return pd.Series(np.where(people.isin(events["person_id"]), 1.0, np.nan), index=people)
|
||||
|
||||
|
||||
def _latest(events: pd.DataFrame, kind: str, people: pd.Index) -> pd.Series:
|
||||
"""Each member's latest recorded value of one kind of event."""
|
||||
found = events[(events["type"] == kind) & events["value_code"].notna()]
|
||||
found = found.sort_values(["date", "source_id"], kind="stable")
|
||||
return found.groupby("person_id")["value_code"].last().reindex(people)
|
||||
|
||||
|
||||
def _latest_bethesda(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""The result of her latest report; the most severe when that day has several."""
|
||||
codes = _codes("result")
|
||||
found = events[(events["type"] == "bethesda") & events["value_code"].isin(codes)]
|
||||
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
|
||||
# severity is the order of the KPNC categories, not the catalog's
|
||||
severity = {name: [name] for names in cacu.KPNC.values() for name in names if name in codes}
|
||||
return _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
|
||||
|
||||
|
||||
def _age(events: pd.DataFrame, members: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
|
||||
keyed = members.set_index("person_id", drop=False)
|
||||
keyed = keyed.assign(index_date=pd.to_datetime(keyed["index_date"]))
|
||||
found = age_group(events, keyed, cuts)
|
||||
labels = list(band(pd.Series([cuts[0] - 1, *cuts]), cuts))
|
||||
return _one_hot(found, "age", labels)
|
||||
|
||||
|
||||
def _cytology(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
result = _latest_bethesda(events, people)
|
||||
columns = _one_hot(result, "bethesda", _codes("result"))
|
||||
for name, codes in cacu.PROCEDURE_CYTOLOGY.items():
|
||||
columns[f"cytology_{name}"] = _flag(result.notna(), result.isin(codes))
|
||||
return columns
|
||||
|
||||
|
||||
def _hpv(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
columns = {}
|
||||
for kind in ("hpv", *GENOTYPES):
|
||||
value = _latest(events, kind, people)
|
||||
columns[f"{kind}_positive"] = _flag(
|
||||
value.isin(["positive", "negative"]), value == "positive"
|
||||
)
|
||||
# From the two genotypes of one sample, not gold's `hpv_16_18`: that is 0 when one is
|
||||
# negative and the other was not reported.
|
||||
found = events[events["type"].isin(GENOTYPES) & events["value_code"].notna()]
|
||||
wide = found.pivot_table(
|
||||
index=["person_id", "date", "source_id"], columns="type", values="value_code",
|
||||
aggfunc="first",
|
||||
).reindex(columns=list(GENOTYPES)) # fmt: skip
|
||||
latest = wide.sort_index().reset_index().drop_duplicates("person_id", keep="last")
|
||||
latest = latest.set_index("person_id").reindex(people)[list(GENOTYPES)]
|
||||
positive = (latest == "positive").any(axis=1)
|
||||
both_negative = (latest == "negative").all(axis=1)
|
||||
columns["hpv_16_or_18_positive"] = _flag(positive | both_negative, positive)
|
||||
return columns
|
||||
|
||||
|
||||
def _history(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
of = {kind: events[events["type"] == kind] for kind in (*PROCEDURES, "cytology")}
|
||||
columns = {
|
||||
"prior_cytology_sample": _present(
|
||||
of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]], people
|
||||
),
|
||||
"prior_biopsy_order": _present(of["biopsy_order"], people),
|
||||
"prior_biopsy_report": _present(of["biopsy"], people),
|
||||
"prior_colposcopy": _present(of["colposcopy"], people),
|
||||
"prior_treatment": _present(of["treatment"], people),
|
||||
"prior_diagnosis_note": _present(of["diagnosis"], people),
|
||||
"history_cancer_icd10": _present(of["history"], people),
|
||||
"history_hysterectomy": _present(
|
||||
events[(events["type"] == "gynecologic_condition")
|
||||
& (events["value_code"] == "hysterectomy")], people
|
||||
),
|
||||
} # fmt: skip
|
||||
|
||||
rank = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY)}
|
||||
worst = of["biopsy"]["value_code"].map(rank).groupby(of["biopsy"]["person_id"]).max()
|
||||
worst = worst.reindex(people)
|
||||
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "CIN2"), ("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)
|
||||
+17
-3
@@ -48,7 +48,8 @@ def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) ->
|
||||
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
|
||||
"""Per patient: the cytology category and HPV result of her index sample (the first
|
||||
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
|
||||
when `history` asks for it."""
|
||||
when `history` asks for it. A patient without an HPV result is left out: she is not
|
||||
evaluated, never read as negative."""
|
||||
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
|
||||
wide = near.sort_values("date", kind="stable").pivot_table(
|
||||
index="person_id", columns="type", values="value_code", aggfunc="first"
|
||||
@@ -59,8 +60,10 @@ def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = N
|
||||
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
|
||||
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
|
||||
if history:
|
||||
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
|
||||
return members
|
||||
# graded in gold, from the cytology linked to her colposcopy
|
||||
grades = events[events["type"] == "referral_grade"].groupby("person_id")["value_code"]
|
||||
members[history["feature"]] = members["person_id"].map(grades.first()).astype(object)
|
||||
return members[wide["hpv"].notna().to_numpy()].reset_index(drop=True)
|
||||
|
||||
|
||||
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
|
||||
@@ -115,6 +118,17 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
||||
key = ["person_id", "source_table", "source_id"]
|
||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||
[*key, "date"]] # fmt: skip
|
||||
hysterectomy = (
|
||||
events.loc[
|
||||
(events["source_table"] == "cervical_cytology")
|
||||
& (events["type"] == "gynecologic_condition")
|
||||
& (events["value_code"] == "hysterectomy")
|
||||
]
|
||||
.groupby("person_id")["date"]
|
||||
.min()
|
||||
)
|
||||
recorded = samples["person_id"].map(hysterectomy)
|
||||
samples = samples[recorded.isna() | (samples["date"] < recorded)]
|
||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||
has = has.reindex(columns=list(RESULTS))
|
||||
|
||||
+14
-1
@@ -1,8 +1,21 @@
|
||||
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from models.cacu import reports
|
||||
from models.cacu.specs import MODELS
|
||||
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
|
||||
|
||||
+57
-4
@@ -149,9 +149,20 @@ class Fit:
|
||||
up[k] += step
|
||||
down[k] -= 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)
|
||||
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
||||
return self.risk(X, Z, years), np.maximum(variance, 0.0)
|
||||
free = np.isfinite(np.diag(self.covariance))
|
||||
variance = np.full((len(X), len(years)), np.nan)
|
||||
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:
|
||||
@@ -251,6 +262,8 @@ class Mixture(BaseEstimator):
|
||||
continue
|
||||
members = X.iloc[index]
|
||||
placed = self._placed(members, self.seen_[key])
|
||||
if not placed.any(): # nobody to score: they keep no value
|
||||
continue
|
||||
prevalence, incidence = self._design(members[placed], self.seen_[key])
|
||||
design = np.column_stack([prevalence, incidence])
|
||||
unique, inverse = np.unique(design, axis=0, return_inverse=True)
|
||||
@@ -258,8 +271,48 @@ class Mixture(BaseEstimator):
|
||||
point, variance = self.fits_[key].risk_with_variance(
|
||||
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),
|
||||
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
||||
out[index[placed]] = band[inverse.ravel()]
|
||||
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)}
|
||||
|
||||
+70
-1
@@ -9,6 +9,8 @@ validation, is a document the clinical team adds). Both are data the governance
|
||||
For the logistic regression, its coefficients and calibration by risk decile.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import norm
|
||||
@@ -23,6 +25,71 @@ BOOTSTRAP = 200
|
||||
SEED = 20261122
|
||||
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",
|
||||
"referral_not_graded": "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:
|
||||
if isinstance(spec, survival.Spec):
|
||||
@@ -72,7 +139,9 @@ def _label(feature: str, value) -> str:
|
||||
|
||||
|
||||
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(),
|
||||
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
||||
|
||||
|
||||
+24
-6
@@ -2,6 +2,7 @@
|
||||
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
|
||||
patient timelines of the spec's cohort (see features)."""
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
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)
|
||||
TRAIN_FRACTION = 0.7
|
||||
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."""
|
||||
h = len(horizons)
|
||||
scored = ~np.isnan(risks[:, :h]).any(axis=1)
|
||||
@@ -38,7 +49,14 @@ 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()
|
||||
else:
|
||||
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)
|
||||
@@ -110,7 +128,7 @@ class Pim:
|
||||
events = events.assign(index_date=events["person_id"].map(chosen))
|
||||
members = f.index_results(events, self.cytology, self._history())
|
||||
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)
|
||||
@@ -156,14 +174,14 @@ class Logistic:
|
||||
members = f.index_sample(f.prepared(events), list(self.predictors))
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
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:
|
||||
"""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."""
|
||||
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"]]
|
||||
names = list(cacu.KPNC)
|
||||
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
||||
@@ -200,6 +218,6 @@ MODELS = {
|
||||
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
||||
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
||||
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
||||
interval_level=0.95),
|
||||
interval_level=0.95, scenarios=SURVIVAL_SCENARIOS),
|
||||
]
|
||||
} # fmt: skip
|
||||
|
||||
@@ -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()
|
||||
+68
-191
@@ -1,45 +1,19 @@
|
||||
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
||||
|
||||
import hashlib
|
||||
import importlib
|
||||
import inspect
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
import dagster as dg
|
||||
|
||||
from core.domains import Domain
|
||||
from models import execution, graph
|
||||
from models import graph
|
||||
from models.jobs import EmptyCohort
|
||||
from models.tea import jobs as tea_jobs
|
||||
from models.tea import preview as tea_preview_analysis
|
||||
from persistance import backup as backups
|
||||
from persistance import bundle, cluster, config_log, eeg, previews, silver
|
||||
from persistance import config_log, silver
|
||||
|
||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||
|
||||
|
||||
class ExecutionConfig(dg.Config):
|
||||
mode: str | None = None
|
||||
scheduler: str | None = None
|
||||
|
||||
def model(self) -> cluster.Execution:
|
||||
return cluster.Execution(**self.model_dump())
|
||||
|
||||
|
||||
class ScopeConfig(dg.Config):
|
||||
mode: str = "pending"
|
||||
n: int | None = None
|
||||
ids: list[str] = []
|
||||
|
||||
def model(self) -> eeg.Scope:
|
||||
return eeg.Scope(**self.model_dump())
|
||||
|
||||
|
||||
class PipelineRun(dg.Config):
|
||||
pipeline: str
|
||||
version: int | None = None # default: the latest saved
|
||||
@@ -67,20 +41,10 @@ def _jobs(domain: str):
|
||||
raise ValueError(f"{domain} has no models") from e
|
||||
|
||||
|
||||
class ReferenceConfig(dg.Config):
|
||||
name: str
|
||||
line_hz: int = 50
|
||||
|
||||
def model(self) -> cluster.Reference:
|
||||
return cluster.Reference(**self.model_dump())
|
||||
|
||||
|
||||
class Training(dg.Config):
|
||||
domain: str
|
||||
models: list[str] = [] # default: every model of the domain
|
||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
reference: ReferenceConfig | None = None
|
||||
|
||||
|
||||
@dg.op
|
||||
@@ -88,21 +52,15 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
|
||||
"""A new registered version of each model (MLflow), with its reports."""
|
||||
jobs = _jobs(config.domain)
|
||||
as_of = date.fromisoformat(config.as_of) if config.as_of else None
|
||||
options = {}
|
||||
if config.reference is not None:
|
||||
if "reference" not in inspect.signature(jobs.train).parameters:
|
||||
raise ValueError(f"{config.domain} models take no reference cohort")
|
||||
options["reference"] = config.reference.model()
|
||||
found = {}
|
||||
with execution.running(context, config.execution.model()):
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of, **options)
|
||||
except EmptyCohort as e:
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of)
|
||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
return found
|
||||
|
||||
|
||||
@@ -120,7 +78,7 @@ class Scoring(dg.Config):
|
||||
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
|
||||
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
|
||||
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():
|
||||
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
|
||||
@@ -132,16 +90,58 @@ def score():
|
||||
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):
|
||||
domain: str
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
|
||||
|
||||
@dg.op
|
||||
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
|
||||
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
|
||||
with execution.running(context, config.execution.model()):
|
||||
found = _jobs(config.domain).analyze()
|
||||
found = _jobs(config.domain).analyze()
|
||||
context.log.info(f"{config.domain}: {found} analysed")
|
||||
return found
|
||||
|
||||
@@ -151,155 +151,33 @@ def analyze():
|
||||
analyze_studies()
|
||||
|
||||
|
||||
class TeaAnalysis(dg.Config):
|
||||
scope: ScopeConfig = ScopeConfig()
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict:
|
||||
with execution.running(context, config.execution.model()):
|
||||
found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False)
|
||||
context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})")
|
||||
return {"analysed": found}
|
||||
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+", "+nci_risk_lookup", "nci_risk_estimate"])
|
||||
context.log.info("silver and gold rebuilt")
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
|
||||
found = tea_jobs.score_curves()
|
||||
for name, version in found.items():
|
||||
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||
return {"scored": found}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
|
||||
version = tea_jobs.relate()
|
||||
context.log.info("ados2_association: " + (f"version {version}" if version else "no champion"))
|
||||
return {"ados2_association": version}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict:
|
||||
silver.build(tea_jobs.GOLD_SELECT)
|
||||
context.log.info("gold rebuilt")
|
||||
return {"built": tea_jobs.GOLD_SELECT}
|
||||
|
||||
|
||||
class Preview(dg.Config):
|
||||
edf: str
|
||||
ados2: str | None = None
|
||||
birth_date: str | None = None
|
||||
pipeline: str = "tea"
|
||||
|
||||
|
||||
@dg.op
|
||||
def preview_study(context: dg.OpExecutionContext, config: Preview) -> dict:
|
||||
try:
|
||||
previews.sweep()
|
||||
result = tea_preview_analysis.preview(
|
||||
previews.get(config.edf),
|
||||
previews.get(config.ados2) if config.ados2 else None,
|
||||
date.fromisoformat(config.birth_date) if config.birth_date else None,
|
||||
config.pipeline,
|
||||
)
|
||||
context.add_output_metadata(
|
||||
{"result": dg.MetadataValue.json(json.loads(result.model_dump_json()))}
|
||||
)
|
||||
for warning in result.warnings:
|
||||
context.log.warning(warning)
|
||||
return {"valid": result.eeg.valid, "warnings": len(result.warnings)}
|
||||
finally:
|
||||
previews.discard([config.edf, config.ados2])
|
||||
|
||||
|
||||
@dg.job(tags={"domain": "tea"})
|
||||
def tea_preview():
|
||||
preview_study()
|
||||
|
||||
|
||||
@dg.job(tags={**WRITES, "domain": "tea"})
|
||||
def tea_eeg():
|
||||
tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies())))
|
||||
|
||||
|
||||
def pending_eegs() -> bool:
|
||||
return bool(eeg.pending())
|
||||
|
||||
|
||||
def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason:
|
||||
if not has_pending():
|
||||
return dg.SkipReason("the ingest brought no EEG to analyse")
|
||||
return dg.RunRequest(
|
||||
run_key=f"after-ingest-{run_id}",
|
||||
run_config={"ops": {"tea_analyze_studies": {"config": {"scope": {"mode": "pending"}}}}},
|
||||
tags={"domain": "tea", "triggered_by": run_id},
|
||||
)
|
||||
|
||||
|
||||
@dg.run_status_sensor(
|
||||
name="tea_eeg_after_ingest",
|
||||
run_status=dg.DagsterRunStatus.SUCCESS,
|
||||
monitored_jobs=[ingest],
|
||||
request_job=tea_eeg,
|
||||
minimum_interval_seconds=10,
|
||||
default_status=dg.DefaultSensorStatus.RUNNING,
|
||||
)
|
||||
def tea_eeg_after_ingest(context: dg.RunStatusSensorContext):
|
||||
return after_ingest(context.dagster_run.run_id, pending_eegs)
|
||||
|
||||
|
||||
class BundleImport(dg.Config):
|
||||
domain: str
|
||||
sha256: str
|
||||
|
||||
|
||||
@dg.op
|
||||
def import_bundle_files(context: dg.OpExecutionContext, config: BundleImport) -> dict:
|
||||
path = bundle.staged(config.sha256)
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != config.sha256:
|
||||
raise bundle.BundleError("the staged file's SHA-256 does not match the run config")
|
||||
result = bundle.import_(Domain(config.domain), data)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
manifest = json.loads(archive.read(bundle.MANIFEST))
|
||||
skipped = set(result.skipped)
|
||||
sources = sorted(
|
||||
(item["name"], item["version"])
|
||||
for item in manifest["versions"]
|
||||
if (item["name"], item["version"]) not in skipped
|
||||
)
|
||||
for (_, source), (name, version) in zip(sources, result.imported, strict=True):
|
||||
context.log.info(f"{name}: source v{source} -> version {version}")
|
||||
for name, version in result.skipped:
|
||||
context.log.warning(f"{name} v{version}: already registered, skipped")
|
||||
return {
|
||||
"imported": [list(item) for item in result.imported],
|
||||
"skipped": [list(item) for item in result.skipped],
|
||||
}
|
||||
|
||||
|
||||
@dg.job
|
||||
def import_bundle():
|
||||
import_bundle_files()
|
||||
@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)
|
||||
@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(
|
||||
@@ -311,7 +189,6 @@ nightly = (
|
||||
)
|
||||
|
||||
defs = dg.Definitions(
|
||||
jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle, backup],
|
||||
sensors=[tea_eeg_after_ingest],
|
||||
jobs=[ingest, train, score, analyze, rebuild, backup, cacu_development_evaluation],
|
||||
schedules=nightly,
|
||||
)
|
||||
|
||||
@@ -1,374 +0,0 @@
|
||||
import contextvars
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC, datetime
|
||||
from itertools import islice
|
||||
|
||||
import dagster as dg
|
||||
import psutil
|
||||
|
||||
from persistance import cluster
|
||||
from persistance.cluster import (
|
||||
PROGRESS_TAG,
|
||||
ClusterVersionError,
|
||||
Execution,
|
||||
ExecutionError,
|
||||
Health,
|
||||
Options,
|
||||
Progress,
|
||||
Resolved,
|
||||
Tasks,
|
||||
Worker,
|
||||
health,
|
||||
options,
|
||||
resolve,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ClusterVersionError",
|
||||
"Execution",
|
||||
"ExecutionError",
|
||||
"Health",
|
||||
"Options",
|
||||
"Progress",
|
||||
"Resolved",
|
||||
"health",
|
||||
"map",
|
||||
"options",
|
||||
"resolve",
|
||||
"running",
|
||||
]
|
||||
|
||||
SAMPLE_S = 2.0
|
||||
_SINGLE_THREAD = {
|
||||
"OMP_NUM_THREADS": "1",
|
||||
"OPENBLAS_NUM_THREADS": "1",
|
||||
"MKL_NUM_THREADS": "1",
|
||||
}
|
||||
|
||||
|
||||
class Eta:
|
||||
def __init__(self, alpha: float = 0.3, min_done: int = 3):
|
||||
self.alpha, self.min_done = alpha, min_done
|
||||
self.rate: float | None = None
|
||||
self._last: tuple[float, int] | None = None
|
||||
|
||||
def update(self, elapsed_s: float, done: int) -> None:
|
||||
last, self._last = self._last, (elapsed_s, done)
|
||||
if last is None or elapsed_s <= last[0]:
|
||||
return
|
||||
rate = (done - last[1]) / (elapsed_s - last[0])
|
||||
self.rate = rate if self.rate is None else self.alpha * rate + (1 - self.alpha) * self.rate
|
||||
|
||||
def eta_s(self, total: int) -> float | None:
|
||||
done = self._last[1] if self._last else 0
|
||||
if done < self.min_done or not self.rate or self.rate <= 0:
|
||||
return None
|
||||
return max(0, total - done) / self.rate
|
||||
|
||||
|
||||
class _Ambient:
|
||||
def __init__(self, context, execution: Execution | None):
|
||||
self.context, self.execution = context, execution
|
||||
self.client = None
|
||||
self.cluster = None
|
||||
self.phases: list[dict] = []
|
||||
self.peak_cpu_pct = 0.0
|
||||
self.peak_memory_bytes = 0
|
||||
|
||||
def close(self) -> None:
|
||||
_close(self.client, self.cluster)
|
||||
self.client = self.cluster = None
|
||||
|
||||
|
||||
_ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
|
||||
"execution_ambient", default=None
|
||||
)
|
||||
|
||||
|
||||
def _close(client, local_cluster) -> None:
|
||||
for closable in (client, local_cluster):
|
||||
if closable is not None:
|
||||
try:
|
||||
closable.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _counts(dask_scheduler) -> dict:
|
||||
counts: dict = {}
|
||||
for task in dask_scheduler.tasks.values():
|
||||
counts[task.state] = counts.get(task.state, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def _connect(resolved: Resolved, workers: int | None):
|
||||
from distributed import Client, LocalCluster
|
||||
|
||||
if resolved.mode == "local":
|
||||
local = LocalCluster(
|
||||
n_workers=cluster.local_workers(workers),
|
||||
threads_per_worker=1,
|
||||
processes=True,
|
||||
memory_limit=cluster.memory_per_worker(),
|
||||
dashboard_address=None,
|
||||
env=_SINGLE_THREAD,
|
||||
)
|
||||
try:
|
||||
return Client(local), local
|
||||
except BaseException:
|
||||
_close(None, local)
|
||||
raise
|
||||
try:
|
||||
client = Client(resolved.scheduler, timeout=10)
|
||||
except Exception as e:
|
||||
raise ExecutionError(f"cannot reach the Dask scheduler {resolved.scheduler}: {e}") from e
|
||||
detail = cluster.versions_error(client)
|
||||
if detail is not None:
|
||||
_close(client, None)
|
||||
raise ClusterVersionError(
|
||||
f"Dask workers differ from this server: {detail}. "
|
||||
"Rebuild the worker image from the same commit."
|
||||
)
|
||||
return client, None
|
||||
|
||||
|
||||
class _Monitor:
|
||||
def __init__(self, ambient, resolved, phase, total, log, client):
|
||||
self.ambient, self.resolved, self.phase = ambient, resolved, phase
|
||||
self.total, self.log, self.client = total, log, client
|
||||
self.done = 0
|
||||
self.started = time.monotonic()
|
||||
self.eta = Eta()
|
||||
self.tasks: Tasks | None = None
|
||||
self.last_tenth = 0
|
||||
self.peak_cpu = 0.0
|
||||
self.peak_memory = 0
|
||||
self._lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self._process = psutil.Process()
|
||||
|
||||
def item_done(self) -> None:
|
||||
with self._lock:
|
||||
self.done += 1
|
||||
|
||||
def start(self) -> None:
|
||||
self.report(force_log=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, *, final: bool) -> None:
|
||||
self._stop.set()
|
||||
self._thread.join()
|
||||
if final:
|
||||
self.report(force_log=True)
|
||||
|
||||
def _loop(self) -> None:
|
||||
while not self._stop.wait(SAMPLE_S):
|
||||
self.report()
|
||||
|
||||
def _cluster_state(self) -> list[Worker]:
|
||||
if self.client is None:
|
||||
cpu = self._process.cpu_percent()
|
||||
self.peak_cpu = max(self.peak_cpu, cpu)
|
||||
self.peak_memory = max(self.peak_memory, self._process.memory_info().rss)
|
||||
return []
|
||||
workers = []
|
||||
try:
|
||||
info = self.client.scheduler_info()["workers"]
|
||||
for w in info.values():
|
||||
m = w.get("metrics", {})
|
||||
workers.append(
|
||||
Worker(
|
||||
name=str(w.get("name", "")),
|
||||
cpu_pct=float(m.get("cpu", 0.0)),
|
||||
memory_bytes=int(m.get("memory", 0)),
|
||||
memory_limit=w.get("memory_limit"),
|
||||
executing=int(m.get("executing", 0)),
|
||||
threads=int(w.get("nthreads", 1)),
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
try:
|
||||
counts = self.client.run_on_scheduler(_counts)
|
||||
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
|
||||
except Exception:
|
||||
pass
|
||||
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
|
||||
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
|
||||
return workers
|
||||
|
||||
def report(self, *, force_log: bool = False) -> None:
|
||||
workers = self._cluster_state()
|
||||
with self._lock:
|
||||
done = self.done
|
||||
elapsed = time.monotonic() - self.started
|
||||
self.eta.update(elapsed, done)
|
||||
progress = Progress(
|
||||
phase=self.phase,
|
||||
done=done,
|
||||
total=self.total,
|
||||
elapsed_s=round(elapsed, 1),
|
||||
eta_s=self.eta.eta_s(self.total),
|
||||
mode=self.resolved.mode,
|
||||
scheduler=self.resolved.scheduler,
|
||||
workers=workers,
|
||||
tasks=self.tasks,
|
||||
updated_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
||||
)
|
||||
tenth = done * 10 // self.total
|
||||
if force_log or tenth > self.last_tenth:
|
||||
self.last_tenth = tenth
|
||||
self.log(f"{self.phase}: {done}/{self.total}")
|
||||
context = self.ambient.context if self.ambient else None
|
||||
if context is not None:
|
||||
context.instance.add_run_tags(
|
||||
context.run_id, {PROGRESS_TAG: progress.model_dump_json()}
|
||||
)
|
||||
|
||||
|
||||
def _default_log(ambient) -> Callable[[str], None]:
|
||||
return ambient.context.log.info if ambient and ambient.context else print
|
||||
|
||||
|
||||
def _run_sync(fn, iterator, monitor, on_error):
|
||||
results = []
|
||||
for item in iterator:
|
||||
try:
|
||||
results.append(fn(item))
|
||||
except Exception as e:
|
||||
if on_error is None:
|
||||
raise
|
||||
results.append(on_error(item, e))
|
||||
monitor.item_done()
|
||||
return results
|
||||
|
||||
|
||||
def _run_dask(fn, iterator, client, monitor, on_error):
|
||||
from distributed import as_completed
|
||||
|
||||
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
|
||||
limit = max(4, 2 * threads)
|
||||
results: dict[int, object] = {}
|
||||
pending: dict = {}
|
||||
completed = as_completed([])
|
||||
numbered = enumerate(iterator)
|
||||
try:
|
||||
while True:
|
||||
for index, item in islice(numbered, max(0, limit - len(pending))):
|
||||
future = client.submit(fn, item, pure=False, retries=1)
|
||||
pending[future] = (index, item)
|
||||
completed.add(future)
|
||||
if not pending:
|
||||
break
|
||||
future = next(completed)
|
||||
index, item = pending.pop(future)
|
||||
try:
|
||||
results[index] = future.result()
|
||||
except Exception as e:
|
||||
if on_error is None:
|
||||
raise
|
||||
results[index] = on_error(item, e)
|
||||
monitor.item_done()
|
||||
except BaseException:
|
||||
try:
|
||||
client.cancel(list(pending), force=True)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return [results[i] for i in range(len(results))]
|
||||
|
||||
|
||||
def map[T, R]( # noqa: A001
|
||||
fn: Callable[[T], R],
|
||||
items: Iterable[T],
|
||||
*,
|
||||
execution: Execution | None = None,
|
||||
log: Callable[[str], None] | None = None,
|
||||
phase: str = "working",
|
||||
total: int | None = None,
|
||||
workers: int | None = None,
|
||||
on_error: Callable[[T, Exception], R] | None = None,
|
||||
) -> list[R]:
|
||||
ambient = _ambient.get()
|
||||
if execution is None and ambient is not None:
|
||||
execution = ambient.execution
|
||||
resolved = resolve(execution)
|
||||
log = log or _default_log(ambient)
|
||||
if total is None:
|
||||
try:
|
||||
total = len(items) # type: ignore[arg-type]
|
||||
except TypeError:
|
||||
raise ValueError("total is needed when items has no length") from None
|
||||
iterator = iter(items)
|
||||
if total == 0:
|
||||
return []
|
||||
monitor = None
|
||||
client, local = (ambient.client, None) if ambient else (None, None)
|
||||
opened_here = False
|
||||
ok = False
|
||||
try:
|
||||
if resolved.mode != "sync" and client is None:
|
||||
client, local = _connect(resolved, workers)
|
||||
if ambient is not None:
|
||||
ambient.client, ambient.cluster = client, local
|
||||
else:
|
||||
opened_here = True
|
||||
monitor = _Monitor(ambient, resolved, phase, total, log, client)
|
||||
monitor.start()
|
||||
if resolved.mode == "sync":
|
||||
results = _run_sync(fn, iterator, monitor, on_error)
|
||||
else:
|
||||
results = _run_dask(fn, iterator, client, monitor, on_error)
|
||||
ok = True
|
||||
return results
|
||||
finally:
|
||||
if monitor is not None:
|
||||
monitor.stop(final=ok)
|
||||
if ambient is not None:
|
||||
ambient.phases.append(
|
||||
{
|
||||
"phase": phase,
|
||||
"done": monitor.done,
|
||||
"total": total,
|
||||
"elapsed_s": round(time.monotonic() - monitor.started, 1),
|
||||
}
|
||||
)
|
||||
ambient.peak_cpu_pct = max(ambient.peak_cpu_pct, monitor.peak_cpu)
|
||||
ambient.peak_memory_bytes = max(ambient.peak_memory_bytes, monitor.peak_memory)
|
||||
if opened_here:
|
||||
_close(client, local)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
|
||||
ambient = _Ambient(context, execution)
|
||||
token = _ambient.set(ambient)
|
||||
failed = True
|
||||
try:
|
||||
yield
|
||||
failed = False
|
||||
finally:
|
||||
_ambient.reset(token)
|
||||
ambient.close()
|
||||
try:
|
||||
resolved = resolve(execution)
|
||||
context.add_output_metadata(
|
||||
{
|
||||
"mode": dg.MetadataValue.text(resolved.mode),
|
||||
"scheduler": (
|
||||
dg.MetadataValue.text(resolved.scheduler)
|
||||
if resolved.scheduler
|
||||
else dg.MetadataValue.null()
|
||||
),
|
||||
"phases": dg.MetadataValue.json(ambient.phases),
|
||||
"peak_cpu_pct": dg.MetadataValue.float(ambient.peak_cpu_pct),
|
||||
"peak_memory_bytes": dg.MetadataValue.int(ambient.peak_memory_bytes),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
if not failed:
|
||||
raise
|
||||
+26
-47
@@ -24,11 +24,11 @@ from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||
|
||||
from core import catalog, concept_map, fhir_in
|
||||
from core.pipeline import (
|
||||
FIELD_EVIDENCE,
|
||||
HELD,
|
||||
IDENTIFIERS,
|
||||
QUOTES,
|
||||
RECORD,
|
||||
Edf,
|
||||
Extract,
|
||||
Fhir,
|
||||
Join,
|
||||
@@ -46,7 +46,6 @@ from core.pipeline import (
|
||||
matches,
|
||||
validate,
|
||||
)
|
||||
from models.tea.eeg import read
|
||||
from persistance import config_log, files, nodes, silver
|
||||
|
||||
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
|
||||
@@ -59,13 +58,10 @@ READ_COLUMNS = { # declared, so a load where every file read cleanly still has
|
||||
}
|
||||
|
||||
|
||||
EDF_COLUMNS = {f"edf_{name}": {"data_type": kind, "nullable": True} for name, kind in (
|
||||
("patient_code", "text"), ("sex", "text"), ("birth_date", "text"), ("study_date", "text"),
|
||||
("record_code", "text"), ("duration_s", "double"), ("channels", "bigint"), ("error", "text"),
|
||||
)} # fmt: skip
|
||||
|
||||
|
||||
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]
|
||||
@@ -167,36 +163,8 @@ def run_read(p: str, node: Read):
|
||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||
|
||||
|
||||
def run_edf(p: str, node: Edf):
|
||||
rows = list(nodes.rows(p, node.inputs[0]))
|
||||
empty = dict.fromkeys(EDF_COLUMNS)
|
||||
found = {None: {**empty, "edf_error": "empty"}}
|
||||
for key in {row.get(node.column) for row in rows} - {None}:
|
||||
content = files.content(key)
|
||||
if content is None:
|
||||
found[key] = {**empty, "edf_error": "no file"}
|
||||
continue
|
||||
try:
|
||||
h = read.header(content)
|
||||
except read.FileNotValid as exc:
|
||||
found[key] = {**empty, "edf_error": str(exc)}
|
||||
continue
|
||||
found[key] = {
|
||||
"edf_patient_code": h.patient_code,
|
||||
"edf_sex": h.sex,
|
||||
"edf_birth_date": h.birthdate.isoformat() if h.birthdate else None,
|
||||
"edf_study_date": h.start_date.isoformat() if h.start_date else None,
|
||||
"edf_record_code": h.record_code,
|
||||
"edf_duration_s": h.duration_s,
|
||||
"edf_channels": h.channels,
|
||||
"edf_error": None,
|
||||
}
|
||||
for row in rows:
|
||||
row.update(found[row.get(node.column)])
|
||||
return nodes.write(p, node.id, rows, EDF_COLUMNS)
|
||||
|
||||
|
||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||
"""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)
|
||||
@@ -217,14 +185,11 @@ def run_map(p: str, node: Map):
|
||||
|
||||
|
||||
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 []
|
||||
found: dict[str, dict] = {}
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
bundle = json.loads(row[node.column])
|
||||
for r in fhir_in.rows(bundle, node.entity, p, maps):
|
||||
found[r[RECORD]] = r
|
||||
return nodes.write(p, node.id, list(found.values()))
|
||||
stored = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or ""))
|
||||
bundle = fhir_in.combined(json.loads(row[node.column]) for row in stored)
|
||||
return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps))
|
||||
|
||||
|
||||
def run_join(p: str, node: Join):
|
||||
@@ -519,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)}
|
||||
person = {k: r["person_id"] for k, r in linked.items()}
|
||||
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
|
||||
observations, held_rows = [], []
|
||||
for i in (i for i in node.inputs if i != link):
|
||||
@@ -539,9 +505,20 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
continue
|
||||
clean = model.model_validate(values)
|
||||
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():
|
||||
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
|
||||
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||
@@ -549,7 +526,7 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
|
||||
RUNNERS: dict[str, Callable] = {
|
||||
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
|
||||
"join": run_join, "extract": run_extract, "link": run_link, "edf": run_edf, "fhir": run_fhir,
|
||||
"join": run_join, "extract": run_extract, "link": run_link, "fhir": run_fhir,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
@@ -566,5 +543,7 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
||||
RUNNERS[node.kind](pipeline_id, node)
|
||||
log(f"{node.id} ({node.kind}) done")
|
||||
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
||||
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
||||
silver.build(
|
||||
["silver+", "+nci_risk_lookup"]
|
||||
) # every entity (empty if never staged) and what derives
|
||||
log(f"silver and gold, from {', '.join(entities)}")
|
||||
|
||||
@@ -35,12 +35,19 @@ class Jobs:
|
||||
models: dict
|
||||
technical_validation: 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
|
||||
def events(self) -> str:
|
||||
return f"{self.domain}_events"
|
||||
|
||||
def routine(self) -> list[str]:
|
||||
"""The models a train run takes when none is named: all of them."""
|
||||
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:
|
||||
@@ -64,9 +71,15 @@ class Jobs:
|
||||
"technical_validation": self.technical_validation(spec, metrics, 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
|
||||
# for its idle workers to time out (5 minutes) before it can end.
|
||||
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()}
|
||||
model = Predictor(spec, fitted)
|
||||
return registry.register(self.registered(name), model, params, metrics, found)
|
||||
|
||||
+78
-2
@@ -341,7 +341,7 @@ class Spec:
|
||||
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
|
||||
return pd.DataFrame({
|
||||
result = pd.DataFrame({
|
||||
"person_id": np.repeat(members["person_id"].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),
|
||||
@@ -350,6 +350,15 @@ class Spec:
|
||||
"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
|
||||
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)
|
||||
@@ -430,6 +439,43 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def _combination_curves(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> list[dict]:
|
||||
"""The curves of the members who share every covariate value, the ones a patient with those
|
||||
values is shown: Kaplan-Meier, Weibull, fractional Weibull and the model's points for those
|
||||
values (its bootstrap band where training saw them). Fewer than MIN_SCENARIO_EVENTS deaths:
|
||||
counts and why, no curve."""
|
||||
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
||||
keys = spec._combinations(members)
|
||||
intervals = getattr(model, "intervals_", {})
|
||||
found = []
|
||||
for values, rows in keys.groupby(list(spec.features), sort=True).indices.items():
|
||||
values = values if isinstance(values, tuple) else (values,)
|
||||
entry = {"valores": dict(zip(spec.features, values, strict=True)), "n": len(rows),
|
||||
"fallecidos": int(event[rows].sum())} # fmt: skip
|
||||
if entry["fallecidos"] < MIN_SCENARIO_EVENTS:
|
||||
entry["reason"] = "insufficient_deaths"
|
||||
else:
|
||||
entry |= _scenario_curves(months[rows], event[rows], spec.cap_months)
|
||||
point = {"S": model.survival(members.iloc[rows[:1]])[0].tolist()}
|
||||
band = intervals.get(values)
|
||||
if band: # kept as mortality: survival's limits are its complements, swapped
|
||||
point |= {"low": [1 - v for v in band[1]], "high": [1 - v for v in band[0]]}
|
||||
point["interval"] = {"available": bool(band),
|
||||
"level": spec.interval_level if band else None,
|
||||
"method": "bootstrap_percentile" if band else None} # fmt: skip
|
||||
entry["points"] = {"COMB": point}
|
||||
entry["horizons_months"] = list(spec.borders[1:])
|
||||
entry["km"]["interval"] = {
|
||||
"available": True,
|
||||
"level": 0.95,
|
||||
"method": "greenwood_log_log",
|
||||
}
|
||||
for name in ("weibull", "weibull_fractional"):
|
||||
entry[name]["interval"] = {"available": False, "level": None, "method": None}
|
||||
found.append(entry)
|
||||
return found
|
||||
|
||||
|
||||
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
"""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
|
||||
@@ -487,7 +533,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
for n, m in masks.items() if n not in drawn] # fmt: skip
|
||||
combinations = spec._combinations(train).value_counts().reset_index(name="members")
|
||||
survival = model.survival(combinations.replace(UNKNOWN, None))
|
||||
return {
|
||||
report = {
|
||||
"model": spec.name,
|
||||
"kind": "curves",
|
||||
"curves": curves,
|
||||
@@ -509,6 +555,36 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
"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, model, members)
|
||||
return report
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- risk factors
|
||||
|
||||
+240
-449
@@ -1,225 +1,94 @@
|
||||
from __future__ import annotations
|
||||
"""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 json
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
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 ADOS2_ITEMS
|
||||
from models.tea.eeg.spindles import ZONES
|
||||
|
||||
ASSOCIATION_COLUMNS = (
|
||||
"biomarker",
|
||||
"zone",
|
||||
"kind",
|
||||
"outcome",
|
||||
"outcome_code",
|
||||
"event",
|
||||
"model",
|
||||
"n",
|
||||
"odds_ratio",
|
||||
"ci_low",
|
||||
"ci_high",
|
||||
"p",
|
||||
"q",
|
||||
"sens_model",
|
||||
"sens_odds_ratio",
|
||||
"same_direction",
|
||||
"reason",
|
||||
)
|
||||
SCORE_COLUMNS = (
|
||||
"key",
|
||||
"biomarker",
|
||||
"zone",
|
||||
"outcome_code",
|
||||
"z",
|
||||
"probability",
|
||||
"reference_probability",
|
||||
)
|
||||
ADJUST = ("age_months", "ados_module")
|
||||
|
||||
ITEMS = {
|
||||
1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}),
|
||||
2: ("Señalar", "SA", {"toddler", "module_1", "module_2"}),
|
||||
3: ("Gestos", "SA", {"toddler", "module_1", "module_2"}),
|
||||
4: ("Contacto visual inusual", "SA", {"toddler", "module_1", "module_2"}),
|
||||
5: ("Expresiones faciales dirigidas a otros", "SA", {"toddler", "module_1", "module_2"}),
|
||||
6: ("Integración de la mirada con otras conductas", "SA", {"toddler", "module_1"}),
|
||||
7: ("Disfrute compartido en la interacción", "SA", {"toddler", "module_1", "module_2"}),
|
||||
8: ("Respuesta al nombre", "SA", {"toddler"}),
|
||||
9: ("Búsqueda de atención cuando se le ignora", "SA", {"toddler"}),
|
||||
10: ("Pedir", "SA", {"toddler"}),
|
||||
11: ("Mostrar", "SA", {"toddler", "module_1", "module_2"}),
|
||||
12: (
|
||||
"Iniciación espontánea de la atención conjunta",
|
||||
"SA",
|
||||
{"toddler", "module_1", "module_2"},
|
||||
),
|
||||
13: ("Respuesta a la atención conjunta", "SA", {"toddler", "module_1"}),
|
||||
14: ("Calidad de los acercamientos sociales", "SA", {"toddler", "module_1", "module_2"}),
|
||||
15: ("Cantidad de acercamientos sociales al cuidador", "SA", {"toddler"}),
|
||||
16: ("Cantidad de comunicación social recíproca", "SA", {"module_2"}),
|
||||
17: ("Calidad general de la relación", "SA", {"toddler", "module_2"}),
|
||||
18: ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"toddler", "module_1"}),
|
||||
19: ("Uso estereotipado o idiosincrático de palabras", "RRB", {"module_1", "module_2"}),
|
||||
20: ("Interés sensorial inusual", "RRB", {"toddler", "module_1", "module_2"}),
|
||||
21: ("Manierismos de manos y dedos", "RRB", {"toddler", "module_1", "module_2"}),
|
||||
22: (
|
||||
"Intereses repetitivos o conductas estereotipadas",
|
||||
"RRB",
|
||||
{"toddler", "module_1", "module_2"},
|
||||
),
|
||||
}
|
||||
|
||||
ZONE_ITEMS = {
|
||||
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
|
||||
"frontal_right": (4, 5, 7, 14, 22),
|
||||
"frontal_midline": (6, 11, 12, 13, 14),
|
||||
"central": (21,),
|
||||
"parietal": (6, 13, 20),
|
||||
"temporal_left": (1, 16, 18, 19),
|
||||
"temporal_right": (4, 5, 8),
|
||||
"occipital": (4, 20),
|
||||
}
|
||||
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
|
||||
RHYTHM_ITEMS = (20, 22)
|
||||
|
||||
CSS = "CSS"
|
||||
CSS_HIGH = 8
|
||||
ALTERED = 1
|
||||
|
||||
|
||||
def item_code(n: int) -> str:
|
||||
return f"ados2_item_{n:02d}"
|
||||
|
||||
|
||||
def pairs(level: str) -> list[dict]:
|
||||
out = []
|
||||
for zone in ZONES:
|
||||
outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "spikes",
|
||||
"zone": zone,
|
||||
"predictor": f"z_spikes_{zone}",
|
||||
"kind": k,
|
||||
"outcome": o,
|
||||
}
|
||||
for k, o in outcomes
|
||||
]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "spindles",
|
||||
"zone": zone,
|
||||
"predictor": f"z_spindles_{zone}",
|
||||
"kind": "domain",
|
||||
"outcome": CSS,
|
||||
}
|
||||
for zone in SPINDLE_ZONES
|
||||
]
|
||||
rhythm = [("item", n) for n in RHYTHM_ITEMS] if level == "item" else [("domain", CSS)]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "posterior_rhythm",
|
||||
"zone": "posterior",
|
||||
"predictor": "z_posterior_rhythm",
|
||||
"kind": k,
|
||||
"outcome": o,
|
||||
}
|
||||
for k, o in rhythm
|
||||
]
|
||||
out.append(
|
||||
{
|
||||
"biomarker": "gradient",
|
||||
"zone": "global",
|
||||
"predictor": "z_gradient",
|
||||
"kind": "domain",
|
||||
"outcome": CSS,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def algorithm_score(v) -> pd.Series:
|
||||
v = pd.to_numeric(pd.Series(v), errors="coerce")
|
||||
return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2)
|
||||
|
||||
|
||||
def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
|
||||
column = ADOS2_ITEMS[n - 1]
|
||||
if "ados_module" not in cohort or column not in cohort:
|
||||
return pd.Series(np.nan, index=cohort.index)
|
||||
return algorithm_score(cohort[column]).where(cohort["ados_module"].isin(ITEMS[n][2]))
|
||||
|
||||
|
||||
def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool:
|
||||
scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1)
|
||||
return int(scores.notna().any(axis=1).sum()) >= minimum
|
||||
|
||||
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, adjust) -> Design:
|
||||
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
|
||||
d = cls(predictor)
|
||||
for a in adjust:
|
||||
if a not in t:
|
||||
continue
|
||||
for a in (a for a in spec.ADJUST if a in t):
|
||||
v = t[a]
|
||||
if pd.api.types.is_numeric_dtype(v):
|
||||
v = v.astype(float)
|
||||
if v.std() > 0:
|
||||
d.numeric[a] = float(v.mean())
|
||||
else:
|
||||
ref = v.value_counts().index[0]
|
||||
levels = [lv for lv in sorted(set(v) - {ref}) if 0 < (v == lv).sum() < len(v)]
|
||||
if levels:
|
||||
d.categorical[a] = [str(lv) for lv in levels]
|
||||
d.reference[a] = str(ref)
|
||||
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}={lv}" for a, levels in self.categorical.items() for lv in levels
|
||||
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)]
|
||||
for a, mean in self.numeric.items():
|
||||
cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan))
|
||||
for a, levels in self.categorical.items():
|
||||
v = t[a].astype(str) if a in t else pd.Series([None] * len(t))
|
||||
for lv in levels:
|
||||
cols.append((v == lv).to_numpy(float))
|
||||
X = np.column_stack(cols)
|
||||
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():
|
||||
seen = {self.reference[a], *levels}
|
||||
known &= (
|
||||
t[a].astype(str).isin(seen).to_numpy() & t[a].notna().to_numpy()
|
||||
if a in t
|
||||
else False
|
||||
)
|
||||
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 to_dict(self) -> dict:
|
||||
def state(self) -> dict:
|
||||
return {
|
||||
"predictor": self.predictor,
|
||||
"numeric": self.numeric,
|
||||
@@ -228,371 +97,293 @@ class Design:
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d: dict) -> Design:
|
||||
def from_state(cls, s: dict) -> "Design":
|
||||
return cls(
|
||||
d["predictor"],
|
||||
dict(d["numeric"]),
|
||||
{k: list(v) for k, v in d["categorical"].items()},
|
||||
dict(d["reference"]),
|
||||
s["predictor"],
|
||||
dict(s["numeric"]),
|
||||
{k: list(v) for k, v in s["categorical"].items()},
|
||||
dict(s["reference"]),
|
||||
)
|
||||
|
||||
|
||||
def _pl(b, X, y):
|
||||
# Firth: the log-likelihood penalised by half the log-determinant of the information.
|
||||
def _penalised(b, X, y) -> float:
|
||||
eta = X @ b
|
||||
p = expit(eta)
|
||||
w = p * (1 - p)
|
||||
w = expit(eta) * (1 - expit(eta))
|
||||
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
|
||||
if sign <= 0:
|
||||
return -np.inf
|
||||
return float(np.sum(y * eta - np.logaddexp(0, eta)) + 0.5 * logdet)
|
||||
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
|
||||
|
||||
|
||||
def _score(b, X, y):
|
||||
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])
|
||||
h = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||
return X.T @ (y - p + h * (0.5 - p)), info
|
||||
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 _fit_firth(X, y, max_iter=200, tol=1e-10):
|
||||
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])
|
||||
pl = _pl(b, X, y)
|
||||
best = _penalised(b, X, y)
|
||||
for _ in range(max_iter):
|
||||
U, info = _score(b, X, y)
|
||||
step = np.linalg.solve(info, U)
|
||||
t = 1.0
|
||||
score, info = _gradient(b, X, y)
|
||||
step, t = np.linalg.solve(info, score), 1.0
|
||||
while t > 1e-8:
|
||||
nb = b + t * step
|
||||
npl = _pl(nb, X, y)
|
||||
if npl >= pl - 1e-12:
|
||||
trial = _penalised(b + t * step, X, y)
|
||||
if trial >= best - 1e-12:
|
||||
break
|
||||
t /= 2
|
||||
b, pl = nb, npl
|
||||
b, best = b + t * step, trial
|
||||
if np.max(np.abs(t * step)) < tol:
|
||||
break
|
||||
return b, pl
|
||||
return b, best
|
||||
|
||||
|
||||
def _profile_firth(value, j, X, y, b0):
|
||||
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 f(bf):
|
||||
def negative(bf):
|
||||
b = np.empty(X.shape[1])
|
||||
b[free], b[j] = bf, value
|
||||
v = _pl(b, X, y)
|
||||
v = _penalised(b, X, y)
|
||||
if not np.isfinite(v):
|
||||
return 1e10, np.zeros(len(free))
|
||||
U, _ = _score(b, X, y)
|
||||
return -v, -U[free]
|
||||
return -v, -_gradient(b, X, y)[0][free]
|
||||
|
||||
return -float(optimize.minimize(f, b0[free], jac=True, method="BFGS").fun)
|
||||
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
||||
|
||||
|
||||
def _interval(profile, centre, maximum, scale):
|
||||
g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
||||
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 g(v) > 0:
|
||||
limit = optimize.brentq(g, min(previous, v), max(previous, v))
|
||||
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, lo, hi, p, design, state, **extra) -> dict:
|
||||
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(lo)), 4),
|
||||
"ci_high": round(float(np.exp(hi)), 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.to_dict(), **state},
|
||||
"state": {"design": design.state(), **state},
|
||||
}
|
||||
|
||||
|
||||
def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
|
||||
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
|
||||
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 data or no variation"}
|
||||
design = Design.of(d, predictor, adjust)
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)
|
||||
b, pl = _fit_firth(X, y)
|
||||
_, info = _score(b, X, y)
|
||||
se = float(np.sqrt(np.linalg.inv(info)[1, 1]))
|
||||
profile = lambda v: _profile_firth(v, 1, X, y, b) # noqa: E731
|
||||
lo, hi = _interval(profile, b[1], pl, max(se, 0.05))
|
||||
p = float(stats.chi2.sf(max(2 * (pl - profile(0.0)), 0.0), 1))
|
||||
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:]
|
||||
flic = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
return _summary(
|
||||
"firth",
|
||||
len(d),
|
||||
b[1],
|
||||
lo,
|
||||
hi,
|
||||
p,
|
||||
design,
|
||||
{"beta": [float(v) for v in b[1:]], "intercept": float(flic)},
|
||||
events=int(y.sum()),
|
||||
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 firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
|
||||
X = Design.from_dict(state["design"]).matrix(t)
|
||||
return expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"]))
|
||||
|
||||
|
||||
def firth_reference(state: dict) -> float:
|
||||
return float(expit(state["intercept"]))
|
||||
|
||||
|
||||
def _nll_ordinal(par, X, yk, K):
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
eta = X @ par[K - 1 :]
|
||||
n = len(yk)
|
||||
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
|
||||
pr = cdf[np.arange(n), yk + 1] - cdf[np.arange(n), yk]
|
||||
return -float(np.sum(np.log(np.clip(pr, 1e-300, None))))
|
||||
|
||||
|
||||
def _fit_ordinal(X, yk, K, fixed=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: _nll_ordinal(q, X, yk, K), start, method="BFGS")
|
||||
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
||||
return r.x, float(r.fun)
|
||||
j, value = fixed
|
||||
idx = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
free = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
|
||||
def f(q):
|
||||
def nll(q):
|
||||
par = np.empty(len(start))
|
||||
par[idx], par[K - 1 + j] = q, value
|
||||
return _nll_ordinal(par, X, yk, K)
|
||||
par[free], par[K - 1 + j] = q, value
|
||||
return _ordinal_nll(par, X, y, K)
|
||||
|
||||
return None, float(optimize.minimize(f, start[idx], method="BFGS").fun)
|
||||
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
|
||||
|
||||
|
||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
|
||||
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
|
||||
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 data or no variation"}
|
||||
design = Design.of(d, predictor, adjust)
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)[:, 1:]
|
||||
K = len(levels)
|
||||
yk = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
y = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
par, nll = _fit_ordinal(X, yk, K)
|
||||
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: -_fit_ordinal(X, yk, K, fixed=(0, v))[1] # noqa: E731
|
||||
lo, hi = _interval(profile, beta[0], -nll, 0.1)
|
||||
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))
|
||||
return _summary(
|
||||
"ordinal",
|
||||
len(d),
|
||||
beta[0],
|
||||
lo,
|
||||
hi,
|
||||
p,
|
||||
design,
|
||||
{
|
||||
"beta": [float(v) for v in beta],
|
||||
"threshold": float(theta[k - 1]) if 0 < k < K else None,
|
||||
"always": None if 0 < k < K else float(k == 0),
|
||||
},
|
||||
levels=K,
|
||||
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 ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
|
||||
X = Design.from_dict(state["design"]).matrix(t)[:, 1:]
|
||||
if state["threshold"] is None:
|
||||
return np.where(np.isnan(X).any(axis=1), np.nan, state["always"])
|
||||
return 1 - expit(state["threshold"] - X @ np.asarray(state["beta"]))
|
||||
|
||||
|
||||
def ordinal_reference(state: dict) -> float:
|
||||
return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"]))
|
||||
|
||||
|
||||
def bh(p) -> np.ndarray:
|
||||
p = np.asarray(p, dtype=float)
|
||||
q = np.full(len(p), np.nan)
|
||||
ok = np.isfinite(p)
|
||||
if ok.any():
|
||||
v = p[ok]
|
||||
o = np.argsort(v)
|
||||
r = v[o] * len(v) / np.arange(1, len(v) + 1)
|
||||
r = np.minimum.accumulate(r[::-1])[::-1]
|
||||
q[np.flatnonzero(ok)[o]] = np.minimum(r, 1)
|
||||
return q
|
||||
|
||||
|
||||
def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
|
||||
if pair["kind"] == "item":
|
||||
score = item_scores(cohort, pair["outcome"])
|
||||
return (score >= ALTERED).astype(float).where(score.notna()), score
|
||||
css = pd.to_numeric(cohort.get("css", pd.Series(np.nan, index=cohort.index)), errors="coerce")
|
||||
return (css >= CSS_HIGH).astype(float).where(css.notna()), css
|
||||
|
||||
|
||||
def _guarded(fit, model: str, *args, **kwargs) -> dict:
|
||||
def _guarded(fit, *args) -> dict:
|
||||
try:
|
||||
return fit(*args, **kwargs)
|
||||
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 _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
|
||||
p = pair["predictor"]
|
||||
fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731
|
||||
if pair["kind"] == "item":
|
||||
return fit_firth(), _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=ALTERED)
|
||||
return _guarded(ordinal, "ordinal", d, "_level", p, ADJUST, high=CSS_HIGH), fit_firth()
|
||||
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 _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||
if fit["model"] == "firth":
|
||||
return firth_probability(fit["state"], t), firth_reference(fit["state"])
|
||||
return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"])
|
||||
def outcome_code(row: dict) -> str:
|
||||
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
|
||||
|
||||
|
||||
class Ados2Association:
|
||||
name = "ados2_association"
|
||||
version = "0.1.0"
|
||||
impl = "modern"
|
||||
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 __init__(self, level: str = "auto", fitted: dict | None = None):
|
||||
if level not in ("auto", "item", "domain"):
|
||||
raise ValueError(f"level must be auto, item or domain, not {level!r}")
|
||||
self.level = level
|
||||
self.fitted = fitted
|
||||
|
||||
def fit(self, cohort: pd.DataFrame) -> Ados2Association:
|
||||
level = self.level if self.level != "auto" else ("item" if has_items(cohort) else "domain")
|
||||
rows = []
|
||||
for pair in 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)
|
||||
d["_yes"], d["_level"] = _outcome(cohort, pair)
|
||||
principal, sensitivity = _models(d, pair)
|
||||
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
|
||||
q = np.full(len(rows), np.nan)
|
||||
biomarkers = np.array([r["biomarker"] for r in rows])
|
||||
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
|
||||
for b in dict.fromkeys(biomarkers):
|
||||
q[biomarkers == b] = bh(p[biomarkers == b]).round(5)
|
||||
for r, v in zip(rows, q, strict=True):
|
||||
r["q"] = None if np.isnan(v) else float(v)
|
||||
self.fitted = {"level": level, "n": len(cohort), "rows": rows}
|
||||
return self
|
||||
|
||||
def _rows(self) -> list[dict]:
|
||||
if self.fitted is None:
|
||||
raise ValueError(f"{self.name}: fit() before associations() or score()")
|
||||
return self.fitted["rows"]
|
||||
|
||||
def associations(self) -> pd.DataFrame:
|
||||
out = []
|
||||
for r in self._rows():
|
||||
f, s = r["principal"], r["sensitivity"]
|
||||
kind = r["kind"]
|
||||
ors, sens = f.get("odds_ratio"), s.get("odds_ratio")
|
||||
out.append(
|
||||
{
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"kind": kind,
|
||||
"outcome": r["outcome"],
|
||||
"outcome_code": item_code(r["outcome"]) if kind == "item" else CSS,
|
||||
"event": f">={ALTERED if kind == 'item' else CSS_HIGH}",
|
||||
"model": f["model"],
|
||||
"n": f["n"],
|
||||
"odds_ratio": ors,
|
||||
"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": sens,
|
||||
"same_direction": (
|
||||
None
|
||||
if ors is None or sens is None
|
||||
else bool(np.sign(ors - 1) == np.sign(sens - 1))
|
||||
),
|
||||
"reason": f.get("reason", ""),
|
||||
}
|
||||
)
|
||||
return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS))
|
||||
|
||||
def score(self, cohort: pd.DataFrame) -> pd.DataFrame:
|
||||
parts = []
|
||||
for r in self._rows():
|
||||
f = r["principal"]
|
||||
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
|
||||
continue
|
||||
t = cohort
|
||||
if r["kind"] == "item":
|
||||
modules = set(ITEMS[r["outcome"]][2])
|
||||
t = cohort[cohort["ados_module"].isin(modules)]
|
||||
t = t[t[r["predictor"]].notna()]
|
||||
if not len(t):
|
||||
continue
|
||||
prob, ref = _probability(f, t)
|
||||
kept = np.isfinite(prob)
|
||||
parts.append(
|
||||
pd.DataFrame(
|
||||
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": t["key"].to_numpy()[kept],
|
||||
"key": key,
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"outcome_code": item_code(r["outcome"]) if r["kind"] == "item" else CSS,
|
||||
"z": t[r["predictor"]].to_numpy(float)[kept],
|
||||
"probability": prob[kept].round(4),
|
||||
"reference_probability": round(ref, 4),
|
||||
"outcome_code": outcome_code(r),
|
||||
"z": float(z),
|
||||
"probability": round(float(p), 4),
|
||||
"reference_probability": round(reference, 4),
|
||||
}
|
||||
)
|
||||
)
|
||||
if not parts:
|
||||
return pd.DataFrame(columns=list(SCORE_COLUMNS))
|
||||
return pd.concat(parts, ignore_index=True)[list(SCORE_COLUMNS)]
|
||||
|
||||
def save(self, path) -> None:
|
||||
Path(path, "association.json").write_text(
|
||||
json.dumps({"level": self.level, "fitted": self.fitted}, default=float)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def load(cls, path) -> Ados2Association:
|
||||
d = json.loads(Path(path, "association.json").read_text())
|
||||
return cls(d["level"], d["fitted"])
|
||||
|
||||
|
||||
MODULE = Ados2Association()
|
||||
|
||||
|
||||
class Model(mlflow.pyfunc.PythonModel):
|
||||
def __init__(self, fitted: dict):
|
||||
self.fitted = json.loads(json.dumps(fitted, default=float))
|
||||
|
||||
def predict(self, context, cohort_df):
|
||||
return Ados2Association(fitted=self.fitted).score(cohort_df)
|
||||
return out
|
||||
|
||||
@@ -119,22 +119,15 @@ def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def centiles(baseline_feature: dict, age_months: float) -> dict:
|
||||
curve = pd.DataFrame(baseline_feature["curve"]).astype(float).dropna()
|
||||
names = [name for name in QUANTILES if name in curve or name in ("p5", "median", "p95")]
|
||||
if curve.empty or not age_months > 0:
|
||||
return dict.fromkeys(names)
|
||||
log_ages = np.log(curve["age_months"].to_numpy())
|
||||
at = float(np.log(np.array([age_months]))[0])
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return dict.fromkeys(names)
|
||||
return {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in names}
|
||||
|
||||
|
||||
def _score_curve(baseline: dict, value: float, age: float) -> dict:
|
||||
q = centiles(baseline, age)
|
||||
if q["median"] is None:
|
||||
return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
curve = pd.DataFrame(baseline["curve"]).astype(float).dropna()
|
||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
if not len(curve) or not age > 0:
|
||||
return out
|
||||
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0])
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return out
|
||||
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES}
|
||||
side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"]
|
||||
z = (value - q["median"]) / (side / 1.645) if side > 0 else None
|
||||
outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0
|
||||
|
||||
+6
-84
@@ -13,7 +13,6 @@ import io
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from struct import Struct
|
||||
|
||||
import edfio
|
||||
import mne
|
||||
@@ -76,91 +75,14 @@ class Recording:
|
||||
return [name for name in self.names if kind(name) in kinds]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Header:
|
||||
patient_code: str | None
|
||||
sex: str | None
|
||||
birthdate: date | None
|
||||
start_date: date | None
|
||||
record_code: str | None
|
||||
duration_s: float | None
|
||||
channels: int
|
||||
|
||||
|
||||
_FIXED = Struct("8s80s80s8s8s8s44s8s8s4s")
|
||||
|
||||
|
||||
def _check_length(data: bytes) -> None:
|
||||
if len(data) < _FIXED.size:
|
||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||
|
||||
|
||||
def _fixed_header(data: bytes) -> dict:
|
||||
_check_length(data)
|
||||
try:
|
||||
(
|
||||
version,
|
||||
patient,
|
||||
recording,
|
||||
startdate,
|
||||
starttime,
|
||||
size,
|
||||
reserved,
|
||||
records,
|
||||
duration,
|
||||
signals,
|
||||
) = (field.decode("ascii").strip() for field in _FIXED.unpack_from(data))
|
||||
size, records, duration, signals = int(size), int(records), float(duration), int(signals)
|
||||
if version != "0" or size != 256 * (1 + signals) or signals < 0:
|
||||
raise ValueError
|
||||
except ValueError as exc:
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
return dict(
|
||||
version=version, patient=patient, recording=recording, startdate=startdate,
|
||||
starttime=starttime, size=size, reserved=reserved, records=records,
|
||||
duration=duration, signals=signals,
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _date(value: str, fmt: str) -> date | None:
|
||||
try:
|
||||
return datetime.strptime(value, fmt).date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def header(edf: bytes) -> Header:
|
||||
fixed = _fixed_header(edf)
|
||||
patient = fixed["patient"].split(maxsplit=3) + [""] * 3
|
||||
recording = fixed["recording"].split(maxsplit=3) + [""] * 3
|
||||
start = _date(recording[1], "%d-%b-%Y") if recording[0] == "Startdate" else None
|
||||
return Header(
|
||||
patient_code=None if patient[0] in ("", "X") else patient[0],
|
||||
sex=patient[1] if patient[1] in ("F", "M") else None,
|
||||
birthdate=_date(patient[2], "%d-%b-%Y"),
|
||||
start_date=None if start == UNKNOWN_START else start,
|
||||
record_code=None if recording[2] in ("", "X") else recording[2],
|
||||
duration_s=None if fixed["records"] == -1 else fixed["records"] * fixed["duration"],
|
||||
channels=fixed["signals"],
|
||||
)
|
||||
|
||||
|
||||
def _open(edf: bytes) -> edfio.Edf:
|
||||
_check_length(edf)
|
||||
try:
|
||||
opened = edfio.read_edf(edf, lazy_load_data=True)
|
||||
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
declared_records = int(edf[236:244])
|
||||
if declared_records > opened.num_data_records:
|
||||
raise FileNotValid("the EDF signal data is truncated")
|
||||
return opened
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
|
||||
signals = _open(edf).signals
|
||||
if len(edf) < 256:
|
||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||
try:
|
||||
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
||||
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
if not signals:
|
||||
raise FileNotValid("the EDF declares zero signals")
|
||||
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
|
||||
|
||||
@@ -12,7 +12,7 @@ from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models import execution
|
||||
from models import cluster
|
||||
from models.tea.eeg.analysis import analyze
|
||||
from models.tea.eeg.curves import SCENARIOS
|
||||
|
||||
@@ -33,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)]
|
||||
|
||||
|
||||
def _one(study: tuple[str, Path, float, float]) -> dict:
|
||||
key, path, age, mains_hz = study
|
||||
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz)
|
||||
def _one(key: str, edf: bytes, age: float) -> dict:
|
||||
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ)
|
||||
return {
|
||||
"key": key,
|
||||
"age_months": age,
|
||||
@@ -45,10 +44,11 @@ def _one(study: tuple[str, Path, float, float]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def measure(studies, workers: int | None = None, mains_hz: float = MAINS_HZ) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order."""
|
||||
items = [(k, p, a, mains_hz) for k, p, a in studies]
|
||||
return execution.map(_one, items, phase="measuring_reference", workers=workers)
|
||||
def measure(studies) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order, each a task on the cluster
|
||||
(models.cluster)."""
|
||||
# each task carries its recording: workers see no local folder
|
||||
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]:
|
||||
|
||||
+148
-224
@@ -1,40 +1,28 @@
|
||||
"""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
|
||||
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
|
||||
|
||||
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
|
||||
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."""
|
||||
(models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the
|
||||
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
|
||||
cohort by models/tests/test_eeg.py."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
|
||||
from core.measures import as_day
|
||||
from core.tea import ADOS2_ITEMS, ASSOCIATION_BIOMARKERS, ados2
|
||||
from core.tea.fhir import eeg_study_id
|
||||
from models import execution
|
||||
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
|
||||
from models.tea.eeg import reference as cohort_reference
|
||||
from persistance import cluster, eeg, registry, silver
|
||||
from models.tea.eeg import analysis, curves, reference
|
||||
from persistance import eeg, registry, silver
|
||||
|
||||
ASSOCIATION = "ados2_association"
|
||||
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_SELECT = [
|
||||
"tea_eeg_analyses+",
|
||||
"tea_eeg_metrics+",
|
||||
"tea_associations",
|
||||
"tea_association_scores",
|
||||
]
|
||||
|
||||
|
||||
class Baseline(mlflow.pyfunc.PythonModel):
|
||||
@@ -44,12 +32,6 @@ class Baseline(mlflow.pyfunc.PythonModel):
|
||||
def __init__(self, scenario: str, baseline: dict):
|
||||
self.scenario, self.baseline = scenario, baseline
|
||||
|
||||
def curve(self, feature: str, ages) -> list[dict]:
|
||||
baseline = self.baseline[feature]
|
||||
if baseline["kind"] == "count_rate":
|
||||
raise LookupError("no centiles by age for a count-rate feature")
|
||||
return [{"age_months": age, **curves.centiles(baseline, age)} for age in ages]
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||
feature = (params or {}).get("feature", "value")
|
||||
rows = model_input.to_dict("records")
|
||||
@@ -58,52 +40,18 @@ class Baseline(mlflow.pyfunc.PythonModel):
|
||||
for r in rows]) # fmt: skip
|
||||
|
||||
|
||||
def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
|
||||
edf, birth, signal = item
|
||||
return edf, analysis.analyze(signal, birth)
|
||||
|
||||
|
||||
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
|
||||
rows = eeg.select(scope or eeg.Scope())
|
||||
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows)
|
||||
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
|
||||
def analyze() -> int:
|
||||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
||||
pending = eeg.pending()
|
||||
done = cluster.run(
|
||||
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
|
||||
) # one task per EEG
|
||||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||||
eeg.save_analyses(found)
|
||||
if rebuild_gold:
|
||||
silver.build(GOLD_SELECT)
|
||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||
return len(found)
|
||||
|
||||
|
||||
def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
|
||||
if reference is None:
|
||||
folder = Path(os.environ["TEA_REFERENCE_DIR"])
|
||||
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
|
||||
name, line_hz = cohort_reference.NAME, 50
|
||||
else:
|
||||
folder = cluster.reference_dir(reference.name)
|
||||
ages = folder / "edades.csv"
|
||||
if not ages.is_file():
|
||||
raise ValueError(f"reference cohort {reference.name!r} has no edades.csv")
|
||||
name, line_hz = reference.name, reference.line_hz
|
||||
|
||||
studies = cohort_reference.listing(folder, ages)
|
||||
if reference is not None and not studies:
|
||||
raise ValueError(f"reference cohort {name!r} has no EDF with an age from 16 to 36 months")
|
||||
content = "\n".join(f"{p.name}|{a}" for _, p, a in studies)
|
||||
if line_hz != 50:
|
||||
content += f"|line_hz={line_hz}"
|
||||
digest = hashlib.sha256(content.encode()).hexdigest()
|
||||
cache = os.environ.get("TEA_REFERENCE_CACHE")
|
||||
path = Path(cache) / f"{name}-{digest[:16]}.json" if cache else None
|
||||
if path and path.exists():
|
||||
return digest, json.loads(path.read_text()), name, line_hz
|
||||
measured = cohort_reference.measure(studies, mains_hz=float(line_hz))
|
||||
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, name, line_hz
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Jobs:
|
||||
"""The domain's model jobs (models.definitions): every curve is routine."""
|
||||
@@ -111,6 +59,9 @@ class Jobs:
|
||||
def routine(self) -> list[str]:
|
||||
return list(MODELS)
|
||||
|
||||
def scored(self) -> list[str]:
|
||||
return list(MODELS) # the curves, then the association on their scores
|
||||
|
||||
|
||||
JOBS = Jobs()
|
||||
|
||||
@@ -119,168 +70,44 @@ def registered(name: str) -> str:
|
||||
return f"tea.{name}"
|
||||
|
||||
|
||||
def train(
|
||||
name: str, as_of: date | None = None, reference: cluster.Reference | None = None
|
||||
) -> int | None:
|
||||
"""A new version of one age curve, trained on the reference cohort's valid studies,
|
||||
with its two reports: the cohort it learned from, and its centile curves."""
|
||||
def train(name: str, as_of: date | None = None) -> int:
|
||||
if name == ASSOCIATION:
|
||||
return train_association(as_of)
|
||||
digest, measured, cohort, hz = _reference(reference)
|
||||
table = cohort_reference.tables(measured)[name]
|
||||
return _train_association(as_of)
|
||||
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]
|
||||
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 = {
|
||||
"model": name, "method": "age curves (weighted centiles on log age)",
|
||||
"cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured),
|
||||
"valid_studies": len(valid),
|
||||
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
|
||||
"features": sorted(baseline),
|
||||
"cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day),
|
||||
"studies": len(measured), "valid_studies": len(measured),
|
||||
"ages_months": [min(ages), max(ages)], "features": sorted(baseline),
|
||||
} # fmt: skip
|
||||
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
||||
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
|
||||
params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)}
|
||||
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
|
||||
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
|
||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
|
||||
|
||||
|
||||
def score_curves() -> dict[str, int | None]:
|
||||
return {name: score(name) for name in MODELS}
|
||||
|
||||
|
||||
def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
columns = [
|
||||
"key",
|
||||
"person_id",
|
||||
"study_date",
|
||||
"edf",
|
||||
"age_months",
|
||||
"ados_module",
|
||||
"css",
|
||||
*ADOS2_ITEMS,
|
||||
]
|
||||
biomarker = {metric: name for name, metric in ASSOCIATION_BIOMARKERS.items()}
|
||||
studies, scores = eeg.association_cohort_rows()
|
||||
records = []
|
||||
for row in studies:
|
||||
row["evaluation_date"] = as_day(row["evaluation_date"]) if row["evaluation_date"] else None
|
||||
birth = as_day(row["birth_date"]) if row["evaluation_date"] and row["birth_date"] else None
|
||||
records.append(
|
||||
{
|
||||
**row,
|
||||
"key": eeg_study_id(row["person_id"], row["study_date"]),
|
||||
"ados_module": row["module"],
|
||||
"css": ados2.score(row, birth)[0],
|
||||
}
|
||||
)
|
||||
values = {}
|
||||
edfs = {row["edf"] for row in records}
|
||||
for row in scores:
|
||||
if row["edf"] not in edfs:
|
||||
continue
|
||||
name = biomarker[row["metric"]]
|
||||
if name in ("spikes", "spindles"):
|
||||
if row["part"] != "zones":
|
||||
continue
|
||||
predictor = f"z_{name}_{row['site']}"
|
||||
else:
|
||||
if row["part"] != "value":
|
||||
continue
|
||||
predictor = f"z_{name}"
|
||||
values.setdefault(row["edf"], {})[predictor] = row["z"]
|
||||
scored = pd.DataFrame(records, columns=columns)
|
||||
if values:
|
||||
scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="edf")
|
||||
scored = scored.sort_values(["person_id", "study_date", "key"], na_position="last").reset_index(
|
||||
drop=True
|
||||
)
|
||||
predictors = [c for c in scored.columns if c.startswith("z_")]
|
||||
fit = (
|
||||
scored[scored[predictors].notna().any(axis=1)]
|
||||
.drop_duplicates("person_id")
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
drop = ["person_id", "study_date", "edf"]
|
||||
return fit.drop(columns=drop), scored.drop(columns=drop)
|
||||
|
||||
|
||||
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
|
||||
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
|
||||
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
|
||||
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
|
||||
return hashlib.sha256(text.encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
def _records(frame: pd.DataFrame) -> list[dict]:
|
||||
clean = frame.replace([float("inf"), -float("inf")], None).astype(object)
|
||||
return clean.where(clean.notna(), None).to_dict("records")
|
||||
|
||||
|
||||
def train_association(as_of: date | None = None) -> int | None:
|
||||
fit, scored = cohort()
|
||||
if fit.empty:
|
||||
raise EmptyCohort(ASSOCIATION)
|
||||
estimator = association.Ados2Association(level="auto")
|
||||
mark = fingerprint(
|
||||
fit, scored, f"{estimator.name}/{estimator.version}/{estimator.impl}/{estimator.level}"
|
||||
)
|
||||
name = registered(ASSOCIATION)
|
||||
versions = registry.versions(name)
|
||||
if versions and versions[-1]["params"].get("fingerprint") == mark:
|
||||
return versions[-1]["version"]
|
||||
|
||||
estimator.fit(fit)
|
||||
pairs = estimator.associations()
|
||||
level = estimator.fitted["level"]
|
||||
forest = ["biomarker", "zone", "outcome_code", "odds_ratio", "ci_low", "ci_high", "q"]
|
||||
reports = {
|
||||
"technical_validation": {
|
||||
"model": ASSOCIATION,
|
||||
"method": "Firth / ordinal logistic, profile CI, BH within biomarker",
|
||||
"level": level,
|
||||
"cohort": len(fit),
|
||||
"scored": len(scored),
|
||||
"fingerprint": mark,
|
||||
"pairs": _records(pairs),
|
||||
},
|
||||
"interpretability": {"kind": "forest", "rows": _records(pairs[forest])},
|
||||
}
|
||||
params = {"fingerprint": mark, "level": level}
|
||||
metrics = {"n_reference": len(fit), "pairs": int(pairs["odds_ratio"].notna().sum())}
|
||||
return registry.register(name, association.Model(estimator.fitted), params, metrics, reports)
|
||||
|
||||
|
||||
def relate() -> int | None:
|
||||
found = registry.champion(registered(ASSOCIATION))
|
||||
if found is None:
|
||||
return None
|
||||
version, model = found
|
||||
estimator = association.Ados2Association(fitted=model.unwrap_python_model().fitted)
|
||||
_, scored = cohort()
|
||||
rows = []
|
||||
for row in _records(estimator.associations()):
|
||||
if row["odds_ratio"] is None or row["odds_ratio"] <= 0:
|
||||
continue
|
||||
row["key"] = f"{row['biomarker']}|{row['zone']}|{row['outcome_code']}"
|
||||
row["method"] = row.pop("model")
|
||||
row.pop("outcome")
|
||||
row["level"] = estimator.fitted["level"]
|
||||
row["n_cohort"] = estimator.fitted["n"]
|
||||
row["reason"] = row["reason"] or None
|
||||
rows.append(row)
|
||||
keys = {row["key"] for row in rows}
|
||||
scores = []
|
||||
for row in model.predict(scored).to_dict("records"):
|
||||
pair = "|".join(row.pop(field) for field in ("biomarker", "zone", "outcome_code"))
|
||||
if pair in keys:
|
||||
eeg_id = row["key"]
|
||||
scores.append({**row, "eeg_id": eeg_id, "pair": pair, "key": f"{eeg_id}|{pair}"})
|
||||
eeg.save_associations(version, rows)
|
||||
eeg.save_association_scores(version, scores)
|
||||
return version
|
||||
|
||||
|
||||
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
|
||||
electrode and zone it measures; None without a champion."""
|
||||
found = registry.champion(registered(name))
|
||||
@@ -288,7 +115,7 @@ def score(name: str) -> int | None:
|
||||
return None
|
||||
version, model = found
|
||||
baseline = model.unwrap_python_model().baseline
|
||||
scenario, label = MODELS[name], f"{registered(name)}/{version}"
|
||||
scenario, label = CURVES[name], f"{registered(name)}/{version}"
|
||||
rows = []
|
||||
for one in eeg.analysed():
|
||||
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
|
||||
@@ -310,3 +137,100 @@ def score(name: str) -> int | None:
|
||||
"part": part, "site": site or None, **s}) # fmt: skip
|
||||
eeg.save_scores(name, rows)
|
||||
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
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
import math
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from core import concept_map, tea
|
||||
from core.pipeline import apply_patterns
|
||||
from core.tea import ados2 as scoring
|
||||
from core.tea import ados2_items
|
||||
from models import graph
|
||||
from models.tea.eeg import analysis, curves, read
|
||||
from models.tea.jobs import MODELS
|
||||
from persistance import config_log, registry
|
||||
from persistance.previews import PreviewAdos2, PreviewEeg, PreviewMetric, PreviewResult, Site
|
||||
|
||||
|
||||
def _deviations(models: dict, study: analysis.Analysis) -> dict:
|
||||
metrics = {metric.code: metric for metric in study.metrics}
|
||||
missing_values = set()
|
||||
for name, baseline in models.items():
|
||||
scenario = curves.SCENARIOS[name]
|
||||
if scenario.metric not in metrics:
|
||||
continue
|
||||
metric = metrics[scenario.metric]
|
||||
changes = {
|
||||
part: {
|
||||
site: value
|
||||
for site, value in getattr(metric, part).items()
|
||||
if curves.PREFIX[part] + site in baseline
|
||||
}
|
||||
for part in scenario.parts
|
||||
if part != "value"
|
||||
}
|
||||
if "value" in scenario.parts and "value" not in baseline:
|
||||
models[name] = baseline | {"value": {}}
|
||||
changes["value"] = None
|
||||
missing_values.add(metric.code)
|
||||
metrics[metric.code] = replace(metric, **changes)
|
||||
|
||||
features = {name: study.features.get(name, {}) for name in models}
|
||||
found = curves.deviations(
|
||||
models, replace(study, metrics=list(metrics.values()), features=features)
|
||||
)
|
||||
for code in missing_values:
|
||||
found.get(code, {}).pop("value", None)
|
||||
return found
|
||||
|
||||
|
||||
def _sites(values: dict, scores: dict) -> dict[str, Site]:
|
||||
return {key: Site(value=value, score=scores.get(key)) for key, value in values.items()}
|
||||
|
||||
|
||||
def _metrics(study: analysis.Analysis, warnings: list[str]) -> list[PreviewMetric]:
|
||||
models, versions = {}, {}
|
||||
found = {}
|
||||
if study.valid:
|
||||
for name in curves.SCENARIOS:
|
||||
champion = registry.champion(f"tea.{name}")
|
||||
if champion is not None:
|
||||
versions[name], model = champion
|
||||
models[name] = model.unwrap_python_model().baseline
|
||||
if not models:
|
||||
warnings.append("there are no champion age curves: no z is shown")
|
||||
else:
|
||||
codes = {metric.code for metric in study.metrics}
|
||||
warnings.extend(
|
||||
f"no champion for {name}: its z is not shown"
|
||||
for name, scenario in curves.SCENARIOS.items()
|
||||
if name not in models and scenario.metric in codes
|
||||
)
|
||||
found = _deviations(models, study)
|
||||
|
||||
labels = {
|
||||
MODELS[name].metric: f"tea.{name}/{version}"
|
||||
for name, version in versions.items()
|
||||
if "value" in MODELS[name].parts
|
||||
}
|
||||
metrics = []
|
||||
for metric in study.metrics:
|
||||
parts = found.get(metric.code, {})
|
||||
metrics.append(
|
||||
PreviewMetric(
|
||||
code=metric.code,
|
||||
value=metric.value,
|
||||
score=parts.get("value"),
|
||||
model=labels.get(metric.code) if "value" in parts else None,
|
||||
electrodes=_sites(metric.electrodes, parts.get("electrodes", {})),
|
||||
zones=_sites(metric.zones, parts.get("zones", {})),
|
||||
)
|
||||
)
|
||||
return metrics
|
||||
|
||||
|
||||
def _parse(field, value, kind, warnings):
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if kind == "date":
|
||||
return value if isinstance(value, date) else date.fromisoformat(value)
|
||||
number = float(value)
|
||||
if math.isfinite(number):
|
||||
return number
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
warnings.append(f"{field}: could not read {value!r} as a {kind}")
|
||||
return None
|
||||
|
||||
|
||||
def _report(
|
||||
content: bytes,
|
||||
pipeline: str,
|
||||
recorded_on: date | None,
|
||||
birth: date | None,
|
||||
warnings: list[str],
|
||||
) -> PreviewAdos2 | None:
|
||||
if not content.startswith(b"%PDF"):
|
||||
warnings.append("the ADOS-2 file is not a PDF")
|
||||
return None
|
||||
text = graph.read_file(content)
|
||||
if error := text["error"]:
|
||||
warnings.append(f"the ADOS-2 report could not be read: {error}")
|
||||
return None
|
||||
|
||||
try:
|
||||
saved = config_log.get(pipeline)
|
||||
except (LookupError, SQLAlchemyError, ValueError):
|
||||
saved = None
|
||||
if saved is None:
|
||||
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
|
||||
return None
|
||||
_, definition = saved
|
||||
node = next((n for n in definition.nodes if n.kind == "extract" and n.entity == "ados2"), None)
|
||||
if node is None:
|
||||
warnings.append(f"pipeline {pipeline} has no ados2 extract node")
|
||||
return None
|
||||
|
||||
codes = {}
|
||||
if node.concept_map:
|
||||
mapping = config_log.concept_map(node.concept_map)
|
||||
codes = {field: concept_map.table([mapping], field) for field in node.patterns}
|
||||
found = apply_patterns(node, text["text"], codes)
|
||||
if not found:
|
||||
warnings.append("no ADOS-2 field was found in the report")
|
||||
return None
|
||||
|
||||
row = dict(found[0][0])
|
||||
fields = sorted(row)
|
||||
evaluation_date = _parse("evaluation_date", row.get("evaluation_date"), "date", warnings)
|
||||
if "evaluation_date" not in row:
|
||||
evaluation_date = recorded_on
|
||||
module = row.get("module")
|
||||
titles = {i.field: f"{i.code} {i.title}" for i in ados2_items.ITEMS.get(module, ())}
|
||||
order = [*titles, *(item for item in tea.ADOS2_ITEMS if item not in titles)]
|
||||
items = {item: _parse(item, row.get(item), "number", warnings) for item in order}
|
||||
css, classification = None, None
|
||||
if evaluation_date is None:
|
||||
warnings.append("ADOS-2 not scored: no evaluation date")
|
||||
else:
|
||||
try:
|
||||
css, classification = scoring.score(
|
||||
row | items | {"evaluation_date": evaluation_date}, birth
|
||||
)
|
||||
except (ValueError, TypeError) as exc:
|
||||
warnings.append(f"ADOS-2 not scored: {exc}")
|
||||
else:
|
||||
if css is None and classification is None:
|
||||
warnings.append(
|
||||
"the ADOS-2 score could not be calculated: "
|
||||
"the report lacks the module or the item scores"
|
||||
)
|
||||
return PreviewAdos2(
|
||||
module=module,
|
||||
evaluation_date=evaluation_date,
|
||||
items=items,
|
||||
titles=titles,
|
||||
css=css,
|
||||
classification=classification,
|
||||
read=fields,
|
||||
)
|
||||
|
||||
|
||||
def preview(
|
||||
edf: bytes,
|
||||
ados2: bytes | None = None,
|
||||
birth_date: date | None = None,
|
||||
pipeline: str = "tea",
|
||||
) -> PreviewResult:
|
||||
study = analysis.analyze(edf, birth_date)
|
||||
try:
|
||||
header = read.header(edf)
|
||||
except read.FileNotValid:
|
||||
header = None
|
||||
recorded_on = header.start_date if header else None
|
||||
warnings = []
|
||||
if study.error:
|
||||
warnings.append(f"the EEG analysis ended with an error: {study.error}")
|
||||
eeg = PreviewEeg(
|
||||
valid=study.valid,
|
||||
level=study.level,
|
||||
recorded_on=recorded_on,
|
||||
age_months=study.age_months,
|
||||
clean_fraction=study.clean_fraction,
|
||||
bad_channels=study.bad_channels,
|
||||
channels=study.channels,
|
||||
duration_min=study.duration_min,
|
||||
line_noise_db=study.line_noise_db,
|
||||
sleep=study.sleep,
|
||||
checks=study.checks,
|
||||
metrics=_metrics(study, warnings),
|
||||
error=study.error,
|
||||
)
|
||||
report = None
|
||||
if ados2 is not None:
|
||||
birth = birth_date or (header.birthdate if header else None)
|
||||
report = _report(ados2, pipeline, recorded_on, birth, warnings)
|
||||
return PreviewResult(eeg=eeg, ados2=report, warnings=warnings)
|
||||
@@ -24,8 +24,13 @@ dependencies = [
|
||||
"edfio>=0.4.18",
|
||||
"statsmodels>=0.15.0",
|
||||
"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
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import edfio
|
||||
import numpy as np
|
||||
|
||||
|
||||
def small_edf(
|
||||
path: Path,
|
||||
*,
|
||||
patient_code="N1001",
|
||||
sex="F",
|
||||
birthdate=date(2025, 1, 5),
|
||||
startdate=date(2026, 3, 2),
|
||||
record_code="LAB-1",
|
||||
seconds=20,
|
||||
channels=("Fp1", "Fp2", "Cz"),
|
||||
) -> bytes:
|
||||
edf = edfio.Edf(
|
||||
[
|
||||
edfio.EdfSignal(
|
||||
np.random.default_rng(1).normal(0, 20, 100 * seconds),
|
||||
sampling_frequency=100,
|
||||
label=name,
|
||||
)
|
||||
for name in channels
|
||||
],
|
||||
patient=edfio.Patient(code=patient_code, sex=sex, birthdate=birthdate),
|
||||
recording=edfio.Recording(startdate=startdate, hospital_administration_code=record_code),
|
||||
)
|
||||
edf.write(path)
|
||||
return path.read_bytes()
|
||||
@@ -1,220 +0,0 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import bundle, config, registry
|
||||
|
||||
DOMAIN = Domain.TEA
|
||||
NAME = "tea.curve_x"
|
||||
|
||||
|
||||
class Model(mlflow.pyfunc.PythonModel):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None):
|
||||
return model_input.assign(score=self.value)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stores(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
|
||||
def use(name):
|
||||
path = tmp_path / name
|
||||
path.mkdir(exist_ok=True)
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{path}/a.db")
|
||||
monkeypatch.chdir(path)
|
||||
|
||||
use("a")
|
||||
return use
|
||||
|
||||
|
||||
def _register(value=1, clinical=True):
|
||||
version = registry.register(
|
||||
NAME,
|
||||
Model(value),
|
||||
{"scenario": "curve"},
|
||||
{"n_reference": 10},
|
||||
{"technical_validation": {"a": 1}, "interpretability": {"b": 2}},
|
||||
tags={"source": "test", "bundle.source_version": "stale"},
|
||||
)
|
||||
if clinical:
|
||||
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
|
||||
return version
|
||||
|
||||
|
||||
def _trust(data):
|
||||
sha = hashlib.sha256(data).hexdigest()
|
||||
with bundle.trusted_file().open("a") as file:
|
||||
file.write(f"\n {sha.upper()} \n")
|
||||
return sha
|
||||
|
||||
|
||||
def _entries(data):
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
return {name: archive.read(name) for name in archive.namelist()}
|
||||
|
||||
|
||||
def _zip(entries):
|
||||
stream = io.BytesIO()
|
||||
with zipfile.ZipFile(stream, "w") as archive:
|
||||
for name, data in entries.items():
|
||||
archive.writestr(name, data)
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def test_export_is_deterministic(stores):
|
||||
registry.promote(NAME, _register())
|
||||
first, second = bundle.export(DOMAIN), bundle.export(DOMAIN)
|
||||
assert first.data == second.data
|
||||
assert first.sha256 == second.sha256 == hashlib.sha256(first.data).hexdigest()
|
||||
with zipfile.ZipFile(io.BytesIO(first.data)) as archive:
|
||||
assert archive.namelist() == sorted(archive.namelist())
|
||||
for info in archive.infolist():
|
||||
assert info.date_time == bundle.EPOCH
|
||||
assert info.compress_type == zipfile.ZIP_DEFLATED
|
||||
assert info.external_attr == 0o644 << 16
|
||||
assert info.create_system == 3
|
||||
|
||||
|
||||
def test_layout_and_manifest_hold_every_file_hash(stores):
|
||||
_register()
|
||||
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
||||
manifest = json.loads(entries.pop("manifest.json"))
|
||||
assert (manifest["format"], manifest["domain"]) == (1, "tea")
|
||||
(item,) = manifest["versions"]
|
||||
assert (item["name"], item["version"]) == (NAME, 1)
|
||||
prefix = "models/tea.curve_x/v1/"
|
||||
assert prefix + "meta.json" in entries
|
||||
assert prefix + "model/MLmodel" in entries
|
||||
assert prefix + "reports/clinical_validation.txt" in entries
|
||||
assert item["files"] == {key: hashlib.sha256(data).hexdigest() for key, data in entries.items()}
|
||||
meta = json.loads(entries.pop(prefix + "meta.json"))
|
||||
content = {key.removeprefix(prefix): data for key, data in entries.items()}
|
||||
assert meta["content_sha256"] == item["content_sha256"] == bundle.content_sha256(content)
|
||||
|
||||
|
||||
def test_selection_champion_latest_all(stores):
|
||||
for value in (1, 2, 3):
|
||||
_register(value)
|
||||
with pytest.raises(bundle.Empty, match="nothing to export"):
|
||||
bundle.export(DOMAIN)
|
||||
registry.promote(NAME, 2)
|
||||
assert bundle.export(DOMAIN).versions == [(NAME, 2)]
|
||||
assert bundle.export(DOMAIN, ["curve_x"], "latest").versions == [(NAME, 3)]
|
||||
assert bundle.export(DOMAIN, versions="all").versions == [(NAME, 1), (NAME, 2), (NAME, 3)]
|
||||
with pytest.raises(bundle.BundleError, match="no tea model missing"):
|
||||
bundle.export(DOMAIN, ["missing"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("clinical", [True, False])
|
||||
def test_roundtrip_registers_candidates_with_lineage(stores, clinical):
|
||||
_register()
|
||||
source_version = _register(2, clinical=clinical)
|
||||
source = registry.snapshot(NAME, source_version)
|
||||
inputs = pd.DataFrame({"value": [0]})
|
||||
prediction = mlflow.pyfunc.load_model(f"models:/{NAME}/{source_version}").predict(inputs)
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
stores("b")
|
||||
_trust(exported.data)
|
||||
assert bundle.import_(DOMAIN, exported.data) == bundle.Imported(
|
||||
exported.sha256, [(NAME, 1)], []
|
||||
)
|
||||
target = registry.snapshot(NAME, 1)
|
||||
pd.testing.assert_frame_equal(
|
||||
mlflow.pyfunc.load_model(f"models:/{NAME}/1").predict(inputs),
|
||||
prediction,
|
||||
)
|
||||
assert target.params == source.params
|
||||
assert target.metrics == source.metrics
|
||||
assert target.reports == source.reports
|
||||
assert target.tags == {
|
||||
"source": "test",
|
||||
"bundle.sha256": exported.sha256,
|
||||
"bundle.source_name": NAME,
|
||||
"bundle.source_version": "2",
|
||||
"bundle.content_sha256": json.loads(_entries(exported.data)["manifest.json"])["versions"][
|
||||
0
|
||||
]["content_sha256"],
|
||||
}
|
||||
assert registry.champion_version(NAME) is None
|
||||
if clinical:
|
||||
registry.promote(NAME, 1)
|
||||
assert registry.champion_version(NAME) == 1
|
||||
else:
|
||||
with pytest.raises(registry.MissingReports, match="clinical_validation"):
|
||||
registry.promote(NAME, 1)
|
||||
|
||||
|
||||
def test_importing_twice_is_a_conflict_and_partial_imports_skip(stores):
|
||||
_register()
|
||||
single = bundle.export(DOMAIN, versions="latest")
|
||||
_register(2)
|
||||
both = bundle.export(DOMAIN, versions="all")
|
||||
stores("b")
|
||||
_trust(single.data)
|
||||
_trust(both.data)
|
||||
assert bundle.import_(DOMAIN, single.data).imported == [(NAME, 1)]
|
||||
with pytest.raises(bundle.Conflict, match="every version is already registered"):
|
||||
bundle.import_(DOMAIN, single.data)
|
||||
result = bundle.import_(DOMAIN, both.data)
|
||||
assert result.imported == [(NAME, 2)]
|
||||
assert result.skipped == [(NAME, 1)]
|
||||
|
||||
|
||||
def test_tampered_bundles_are_refused(stores):
|
||||
_register()
|
||||
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
||||
path = "models/tea.curve_x/v1/model/MLmodel"
|
||||
manifest = json.loads(entries["manifest.json"])
|
||||
|
||||
def with_manifest(**fields):
|
||||
return entries | {"manifest.json": json.dumps(manifest | fields).encode()}
|
||||
|
||||
cases = [
|
||||
(_zip(entries | {path: entries[path][:-1] + b"!"}), "content does not match the manifest"),
|
||||
(_zip(entries | {"extra": b""}), "files in the bundle do not match the manifest"),
|
||||
(_zip({k: v for k, v in entries.items() if k != path}), "files in the bundle do not match"),
|
||||
(_zip(entries | {"../x": b""}), r"unsafe bundle path: \.\./x"),
|
||||
(_zip(with_manifest(format=2)), "bundle format 2, this platform reads 1"),
|
||||
(_zip(with_manifest(domain="cacu")), "bundle is for cacu, not tea"),
|
||||
(b"hello", "not a bundle"),
|
||||
]
|
||||
for data, message in cases:
|
||||
_trust(data)
|
||||
with pytest.raises(bundle.BundleError, match=message):
|
||||
bundle.import_(DOMAIN, data)
|
||||
|
||||
|
||||
def test_import_refuses_an_untrusted_digest(stores):
|
||||
_register()
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"):
|
||||
bundle.import_(DOMAIN, exported.data)
|
||||
|
||||
|
||||
def test_version_lifecycle(stores):
|
||||
first = _register(clinical=False)
|
||||
second = _register(clinical=True)
|
||||
assert registry.status(NAME, first) == "candidate"
|
||||
with pytest.raises(registry.MissingReports, match="clinical_validation"):
|
||||
registry.promote(NAME, first)
|
||||
registry.add_report(NAME, first, "clinical_validation", "review.txt", b"approved")
|
||||
registry.promote(NAME, first)
|
||||
assert registry.status(NAME, first) == "champion"
|
||||
with pytest.raises(ValueError, match="the champion cannot be retired"):
|
||||
registry.retire(NAME, first)
|
||||
registry.promote(NAME, second)
|
||||
assert registry.status(NAME, first) == "candidate"
|
||||
registry.retire(NAME, first)
|
||||
assert registry.status(NAME, first) == "retired"
|
||||
with pytest.raises(ValueError, match="is retired"):
|
||||
registry.promote(NAME, first)
|
||||
assert registry.champion_version(NAME) == second
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu import reports
|
||||
|
||||
|
||||
def test_a_candidate_with_two_reasons_is_excluded_once():
|
||||
"""Pins the totals, the pending rule, the people without a candidate and the as-of cut."""
|
||||
rows = pd.DataFrame(
|
||||
[
|
||||
("eligible", "2025-01-01", None, None),
|
||||
("two", "2025-01-01", None, "hysterectomy"),
|
||||
("two", "2025-01-01", None, "under_18"),
|
||||
("waiting", "2025-01-01", None, "no_index_result"),
|
||||
("waiting_and_out", "2025-01-01", None, "no_index_result"),
|
||||
("waiting_and_out", "2025-01-01", None, "prior_outcome"),
|
||||
("after", "2025-07-01", None, "hysterectomy"),
|
||||
],
|
||||
columns=["person_id", "index_date", "index_sample_id", "criterion"],
|
||||
)
|
||||
|
||||
found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30))
|
||||
|
||||
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
|
||||
assert (found["pending"], found["without_candidate"]) == (1, 6)
|
||||
assert found["by_reason"] == {
|
||||
"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1,
|
||||
} # fmt: skip
|
||||
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
|
||||
assert found["stage_by_reason"]["no_index_result"] == "index"
|
||||
assert found["stage_counts_overlap"] is True
|
||||
@@ -0,0 +1,142 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
from scipy.stats import norm
|
||||
|
||||
from models.cacu.bayes_development import prevalence_gibbs as PG
|
||||
|
||||
|
||||
def test_normal_posterior_is_least_squares_under_a_flat_prior():
|
||||
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no\
|
||||
information."""
|
||||
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)
|
||||
|
||||
def pr(shift):
|
||||
return np.where(r == 1, norm.cdf(shift), norm.sf(shift))
|
||||
|
||||
py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0)
|
||||
py0 = np.where((r == 1) & (y == 1), 0.0, 1.0)
|
||||
direct = np.log(
|
||||
p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0
|
||||
).sum()
|
||||
assert np.isclose(got, direct)
|
||||
@@ -0,0 +1,94 @@
|
||||
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.0, 1.0, np.nan, 1.0], "copy": [0.0, 1.0, np.nan, 1.0], "absent": [np.nan] * 4}
|
||||
)
|
||||
assert _candidates(train, 0.7, 5) == ["a"]
|
||||
a, b = _matrix(train, pd.DataFrame({"a": [np.nan]}), ["a"])
|
||||
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
|
||||
|
||||
|
||||
def test_nested_cv_and_loocv_record_every_attempt():
|
||||
X = pd.DataFrame({"a": [0, 0, 1, 1, 0, 1, 0, 1], "b": [0, 1, 0, 1, 1, 0, 0, 1]})
|
||||
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
|
||||
report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2)
|
||||
assert report["development_only"] and report["max_subsets"] == 4
|
||||
assert set(report["validation"]) == {"cv", "loocv"}
|
||||
assert {a["method"] for a in report["attempts"]} == set(METHODS)
|
||||
assert all("variables" in a and "error" in a for a in report["attempts"])
|
||||
assert all(len(report["validation"]["loocv"][m]["selected"]) == len(X) for m in METHODS)
|
||||
|
||||
|
||||
def test_budget_rejects_large_loocv_before_fitting():
|
||||
X = pd.DataFrame({"a": [0, 1] * 10})
|
||||
with pytest.raises(ValueError, match="exceeds configured limit"):
|
||||
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
|
||||
|
||||
|
||||
def test_development_job_is_not_a_production_score():
|
||||
from core.models import DEVELOPMENT
|
||||
from models.definitions import defs
|
||||
|
||||
assert "cacu.cin2_firth_development" in DEVELOPMENT
|
||||
job = defs.get_job_def("cacu_development_evaluation")
|
||||
assert job.name == "cacu_development_evaluation"
|
||||
|
||||
|
||||
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
|
||||
import dagster as dg
|
||||
import mlflow
|
||||
from mlflow.tracking._tracking_service import utils as tracking_utils
|
||||
|
||||
from models.cacu import development_selection, encoders, features
|
||||
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
|
||||
from persistance import gold
|
||||
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", (tmp_path / "mlruns").as_uri())
|
||||
monkeypatch.setenv("MLFLOW_ALLOW_FILE_STORE", "true")
|
||||
monkeypatch.setattr(tracking_utils, "_tracking_uri", tracking_utils._tracking_uri)
|
||||
mlflow.set_tracking_uri((tmp_path / "mlruns").as_uri())
|
||||
patients = [str(i) for i in range(8)]
|
||||
events = pd.DataFrame(
|
||||
{"person_id": patients, "date": ["2025-01-01"] * 8, "index_date": ["2025-01-01"] * 8}
|
||||
)
|
||||
encoded = pd.DataFrame(
|
||||
{
|
||||
"person_id": patients,
|
||||
"index_date": ["2025-01-01"] * 8,
|
||||
"factor": [0, 0, 1, 1, 0, 1, 0, 1],
|
||||
}
|
||||
)
|
||||
outcomes = pd.DataFrame(
|
||||
{"person_id": patients, "known": [True] * 8, "y": [0, 1, 0, 1, 0, 1, 1, 0]}
|
||||
)
|
||||
monkeypatch.setattr(gold, "evidence_timelines", lambda *a: events)
|
||||
monkeypatch.setattr(gold, "cervical_forms", lambda *a: pd.DataFrame())
|
||||
monkeypatch.setattr(encoders, "encode", lambda *a: encoded)
|
||||
monkeypatch.setattr(features, "windowed_outcome", lambda *a: outcomes)
|
||||
real = development_selection.evaluate
|
||||
monkeypatch.setattr(
|
||||
development_selection,
|
||||
"evaluate",
|
||||
lambda X, y, **kw: real(
|
||||
X, y, candidate_limit=1, subset_limit=1, outer_folds=2, inner_folds=2, **kw
|
||||
),
|
||||
)
|
||||
with dg.build_op_context() as context:
|
||||
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of="2026-01-01"))
|
||||
artifacts = mlflow.MlflowClient().list_artifacts(run_id, "reports")
|
||||
assert [a.path for a in artifacts] == ["reports/development_evaluation.json"]
|
||||
@@ -0,0 +1,129 @@
|
||||
"""The binary encoders read only what was available at the index, and never turn an
|
||||
absent value into 0."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.encoders import FINDINGS, encode
|
||||
|
||||
INDEX = "2025-06-10"
|
||||
|
||||
|
||||
def event(day, kind, code=None, person="p1", table="cervical_cytology", sample=None,
|
||||
clinical=None, available=None): # fmt: skip
|
||||
return {
|
||||
"person_id": person, "index_date": INDEX, "date": day, "type": kind,
|
||||
"value_code": code, "value_num": np.nan, "source_table": table,
|
||||
"source_id": sample or day, "evidence_date": clinical, "source_available_at": available,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def form(sample, report, person="p1", **fields):
|
||||
empty = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
|
||||
return {"person_id": person, "sample_date": sample, "report_date": report} | empty | fields
|
||||
|
||||
|
||||
def row(events, forms=None, person="p1"):
|
||||
found = encode(pd.DataFrame(events), None if forms is None else pd.DataFrame(forms))
|
||||
return found.set_index("person_id").loc[person].drop("index_date").astype(float)
|
||||
|
||||
|
||||
def test_nothing_known_is_all_missing():
|
||||
found = row([event(INDEX, "cytology", "satisfactory")])
|
||||
assert found.isna().all()
|
||||
|
||||
|
||||
def test_values_and_missing():
|
||||
found = row([
|
||||
event("1980-06-11", "birth", table="person"),
|
||||
event("2025-01-15", "bethesda", "LSIL", sample="2025-01-10"),
|
||||
event("2025-01-15", "hpv", "positive", sample="2025-01-10"),
|
||||
event("2025-01-15", "hpv_16", "negative", sample="2025-01-10"),
|
||||
event(INDEX, "cervix_appearance", "lesion"),
|
||||
event(INDEX, "presenting_symptom", "not-a-code"),
|
||||
]) # fmt: skip
|
||||
assert found["age__35-44"] == 1 and found["age__45-54"] == 0
|
||||
assert found["bethesda__LSIL"] == 1 and found["bethesda__HSIL"] == 0
|
||||
assert found["cytology_ascus_plus"] == 1 and found["cytology_hsil_plus"] == 0
|
||||
assert found["hpv_positive"] == 1 and found["hpv_16_positive"] == 0
|
||||
assert np.isnan(found["hpv_18_positive"])
|
||||
# one genotype negative and the other unreported is unknown, not negative
|
||||
assert np.isnan(found["hpv_16_or_18_positive"])
|
||||
assert found["cervix_appearance__lesion"] == 1 and found["cervix_appearance__healthy"] == 0
|
||||
assert found.filter(like="presenting_symptom").isna().all() # ambiguous value
|
||||
assert found.filter(like="prior_").isna().all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("positive, other, expected", [
|
||||
("positive", None, 1.0), ("negative", "negative", 0.0), ("negative", "positive", 1.0),
|
||||
]) # fmt: skip
|
||||
def test_genotypes_combined(positive, other, expected):
|
||||
events = [event("2025-01-15", "hpv_16", positive)]
|
||||
if other:
|
||||
events.append(event("2025-01-15", "hpv_18", other))
|
||||
assert row(events)["hpv_16_or_18_positive"] == expected
|
||||
|
||||
|
||||
def test_nothing_later_than_the_index_is_read():
|
||||
base = [event(INDEX, "cytology", "satisfactory")]
|
||||
later = [
|
||||
event("2025-06-20", "bethesda", "HSIL", sample=INDEX), # the index sample's report
|
||||
event("2025-06-20", "hpv", "positive", sample=INDEX),
|
||||
event("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
|
||||
event("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
|
||||
# procedures of the index day may be the outcome
|
||||
event(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
|
||||
event(INDEX, "colposcopy", table="clinical_note"),
|
||||
event(INDEX, "treatment", table="clinical_note"),
|
||||
event("2025-08-01", "history", table="clinical_note"),
|
||||
# standalone evidence without an availability date: its onset says nothing of it
|
||||
event("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence"),
|
||||
] # fmt: skip
|
||||
forms = [form(INDEX, "2025-06-20", adequacy="unsatisfactory", finding_atrophy=True)]
|
||||
pd.testing.assert_series_equal(row(base + later, forms), row(base))
|
||||
|
||||
|
||||
def test_available_by_the_index_day_is_read():
|
||||
found = row([
|
||||
event("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
|
||||
event("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence", available="2024-01-01"),
|
||||
]) # fmt: skip
|
||||
assert found["cytology_hsil_plus"] == 1 and found["history_hysterectomy"] == 1
|
||||
|
||||
|
||||
def test_prior_procedures_and_referral():
|
||||
found = row([
|
||||
event("2025-01-15", "bethesda", "HSIL", sample="2025-01-10"),
|
||||
event("2025-03-01", "colposcopy", table="clinical_note"),
|
||||
event("2025-03-01", "biopsy_order", table="cervical_biopsy"),
|
||||
event("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
|
||||
]) # fmt: skip
|
||||
assert found["prior_colposcopy"] == 1 and found["prior_biopsy_order"] == 1
|
||||
assert found["prior_biopsy_lsil_plus"] == 1 and found["prior_biopsy_hsil_plus"] == 0
|
||||
assert found["referral_high_grade"] == 1
|
||||
assert np.isnan(found["prior_treatment"])
|
||||
|
||||
|
||||
def test_form_fields_come_from_the_latest_report():
|
||||
forms = [
|
||||
form("2024-01-10", "2024-01-20", screening_history="never", finding_atrophy=True),
|
||||
form("2025-01-10", "2025-01-20", adequacy="satisfactory", finding_candida=1),
|
||||
]
|
||||
found = row([event(INDEX, "cytology")], forms)
|
||||
assert found["screening_history__never"] == 1
|
||||
assert found["sample_unsatisfactory"] == 0 and found["finding_candida"] == 1
|
||||
assert np.isnan(found["finding_atrophy"])
|
||||
|
||||
|
||||
def test_members_are_kept_apart():
|
||||
events = [event("2025-01-15", "hpv", "positive"), event(INDEX, "cytology", person="p2")]
|
||||
assert np.isnan(row(events, person="p2")["hpv_positive"])
|
||||
|
||||
|
||||
def test_a_timeline_without_availability_is_refused():
|
||||
events = pd.DataFrame([event(INDEX, "cytology")]).drop(columns="source_available_at")
|
||||
with pytest.raises(ValueError, match="source_available_at"):
|
||||
encode(events)
|
||||
@@ -0,0 +1,16 @@
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import features as f
|
||||
|
||||
|
||||
def test_without_an_hpv_result_she_is_not_evaluated():
|
||||
day = pd.Timestamp("2025-01-01")
|
||||
rows = [(p, day, day, "bethesda", "NILM") for p in ("negative", "positive", "none")]
|
||||
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
|
||||
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
|
||||
found = f.index_results(events, cacu.KPNC)
|
||||
assert dict(zip(found["person_id"], found["hpv_positive"], strict=False)) == {
|
||||
"negative": 0.0,
|
||||
"positive": 1.0,
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
"""The CaCu models compute what the current ones compute: fed the timelines the current
|
||||
platform built for its cohorts (the reference fixtures, in its codes), each rewritten model
|
||||
gives the current model's predictions.
|
||||
|
||||
Fixed on purpose, so left out of the comparison:
|
||||
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
|
||||
(1970-01-01 for everyone); the rewrite returns the index sample's date.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from joblib import parallel_config
|
||||
|
||||
from core import cacu
|
||||
from models import curves, survival
|
||||
from models.cacu import reports
|
||||
from models.cacu.features import days, prepared
|
||||
from models.cacu.specs import MODELS
|
||||
|
||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
||||
RTOL = 1e-6 # as captured (models.json)
|
||||
# The current platform's cohort cutoff, where the logistic model's follow-up ends.
|
||||
REFERENCE_CUTOFF = "2026-11-23"
|
||||
|
||||
TYPES = {
|
||||
"citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv",
|
||||
"vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy",
|
||||
"orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history",
|
||||
"diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth",
|
||||
"defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order",
|
||||
} # fmt: skip
|
||||
CODES = {
|
||||
"bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"},
|
||||
"biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"},
|
||||
"hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"},
|
||||
"cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"},
|
||||
}
|
||||
COHORTS = {
|
||||
"cacu_cohort_surveillance": "cohorte_vigilancia",
|
||||
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
|
||||
}
|
||||
|
||||
|
||||
def timelines(cohort: str) -> pd.DataFrame:
|
||||
"""A reference cohort's timelines in the platform's names and codes."""
|
||||
found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet")
|
||||
found = found.rename(columns={
|
||||
"pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type",
|
||||
"valor_codigo": "value_code", "valor_numerico": "value_num",
|
||||
"fuente_tabla": "source_table", "fuente_id": "source_id",
|
||||
}) # fmt: skip
|
||||
found["type"] = found["type"].map(TYPES)
|
||||
for kind, codes in CODES.items():
|
||||
rows = found["type"] == kind
|
||||
found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes)
|
||||
return found
|
||||
|
||||
|
||||
def hpv_missing_as_the_current_platform_read_it(events: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Changed on purpose: the rewrite does not evaluate a patient without an HPV result at the
|
||||
index; the current platform read it as negative. Standing in a result that is not positive
|
||||
here keeps the rest of the computation compared."""
|
||||
index = events.groupby("person_id", as_index=False).first()
|
||||
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
|
||||
has = events[(events["type"] == "hpv") & near]
|
||||
missing = index[~index["person_id"].isin(has["person_id"])]
|
||||
assumed = missing.assign(
|
||||
date=missing["index_date"], type="hpv", value_code="assumed"
|
||||
) # not positive, and not a negative visit
|
||||
return pd.concat([events, assumed[events.columns]], ignore_index=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
|
||||
"cin2_logistic"]) # fmt: skip
|
||||
def test_predictions_match_the_current_models(name):
|
||||
spec = MODELS[name]
|
||||
events = timelines(COHORTS[spec.cohort])
|
||||
if spec.method != "logistic regression":
|
||||
events = hpv_missing_as_the_current_platform_read_it(events)
|
||||
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
|
||||
model, metrics, _ = spec.train(events, *args)
|
||||
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
||||
current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"]
|
||||
assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"]
|
||||
|
||||
found = spec.predict(model, events)
|
||||
both = found.merge(
|
||||
reference,
|
||||
left_on=["person_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"],
|
||||
how="outer",
|
||||
indicator=True,
|
||||
)
|
||||
assert (both["_merge"] == "both").all(), "the same patients and horizons are scored"
|
||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
if theirs in both:
|
||||
# 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":
|
||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||
|
||||
|
||||
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
|
||||
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."""
|
||||
spec = MODELS["survival"]
|
||||
events = timelines("cohorte_total").drop(columns="index_date")
|
||||
events["date"] = pd.to_datetime(events["date"])
|
||||
events["record_number"] = "CACU" + events["person_id"].astype(str).str.zfill(4)
|
||||
cases = events[(events["type"] == "biopsy") & events["value_code"].isin(["CIS", "carcinoma"])]
|
||||
index = cases.groupby("person_id")["date"].min().rename("index_date")
|
||||
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
|
||||
born = set(events.loc[events["type"] == "birth", "person_id"])
|
||||
died = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
||||
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
|
||||
events = events.merge(index, left_on="person_id", right_index=True)
|
||||
|
||||
model, metrics, data = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
||||
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",
|
||||
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
|
||||
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
|
||||
found = spec.predict(model, events)
|
||||
assert all(set(json.loads(value)) == set(spec.features) for value in found["input_values"])
|
||||
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
||||
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
||||
assert len(both) == len(reference) == len(found)
|
||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
|
||||
|
||||
monkeypatch.setattr(survival, "BOOTSTRAP", 3)
|
||||
monkeypatch.setattr(curves, "fit_fractional", lambda d, c, k, lam: (1.0, 1.0, lam))
|
||||
with parallel_config(backend="sequential"):
|
||||
report = reports.interpretability(spec, model, data)
|
||||
combined = report["km_combinaciones"]
|
||||
assert sum(c["n"] for c in combined) == len(pd.concat([data["train"], data["test"]]))
|
||||
for c in combined:
|
||||
assert set(c["valores"]) == set(spec.features)
|
||||
assert ("km" in c) == (c["fallecidos"] >= survival.MIN_SCENARIO_EVENTS)
|
||||
if "km" in c:
|
||||
assert {"weibull", "weibull_fractional", "points"} <= set(c)
|
||||
point = c["points"]["COMB"]
|
||||
assert len(point["S"]) == len(c["horizons_months"]) == len(spec.borders) - 1
|
||||
(scenario,) = report["escenarios"]
|
||||
name = scenario["escenario"]
|
||||
assert name == "Citología · HSIL+"
|
||||
assert scenario["horizons_months"] == [12, 36, 60]
|
||||
km = scenario["km"]
|
||||
assert km["months"] and len(km["months"]) == len(km["low"]) == len(km["high"])
|
||||
scored = found.drop_duplicates("person_id")
|
||||
assert scored["scenarios"].str.contains(name, regex=False, na=False).sum() == scenario["n"]
|
||||
assert "VPH negativo" in {row["escenario"] for row in report["escenarios_sin_curvas"]}
|
||||
|
||||
|
||||
def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch):
|
||||
"""A site with no colposcopies has nobody in the post-colposcopy cohort: training that
|
||||
model says so (and the train job goes on with the others) instead of failing inside it."""
|
||||
from models import jobs
|
||||
from models.cacu.jobs import JOBS
|
||||
|
||||
monkeypatch.setattr(jobs.gold, "timelines", lambda *a: pd.DataFrame())
|
||||
with pytest.raises(jobs.EmptyCohort, match="cacu_cohort_post_colposcopy"):
|
||||
JOBS.train("cin2_pim_post_colposcopy")
|
||||
@@ -0,0 +1,22 @@
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.specs import _rows
|
||||
|
||||
|
||||
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
|
||||
members = pd.DataFrame(
|
||||
[
|
||||
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
||||
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
||||
]
|
||||
)
|
||||
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5), ("cytology", "hpv"))
|
||||
assert [json.loads(v) for v in result.input_values] == [
|
||||
{"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "HSIL", "hpv": 1},
|
||||
{"cytology": "HSIL", "hpv": 1},
|
||||
]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""CaMa's models give the current platform's predictions on its own cohort (the reference
|
||||
fixtures), read in the platform's timeline shape."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.specs import MODELS
|
||||
|
||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama"
|
||||
TRAINED_ON = "2026-11-24" # the day the reference was trained: its follow-up ends there
|
||||
TYPES = {"nacimiento": "birth", "defuncion": "death", "biopsia": "biopsy"}
|
||||
CODES = {"CARCINOMA_INVASOR": "invasive", "CARCINOMA_IN_SITU": "in_situ", "BENIGNO": "benign"}
|
||||
|
||||
|
||||
def _timelines() -> pd.DataFrame:
|
||||
"""The reference cohort's members (first invasive biopsy report in the window) with their
|
||||
events, as gold.cama_events gives them."""
|
||||
old = pd.read_parquet(REFERENCE / "cohorts" / "cama" / "cohorte_total" / "dbt" / "1.parquet")
|
||||
old = old[old["tipo"].isin(TYPES)]
|
||||
events = pd.DataFrame({
|
||||
"person_id": old["pac_id"].astype(str), "date": pd.to_datetime(old["fecha"]),
|
||||
"type": old["tipo"].map(TYPES), "value_code": old["valor_codigo"].map(CODES),
|
||||
"value_num": old["valor_numerico"], "source_table": old["fuente_tabla"],
|
||||
"source_id": old["fuente_id"],
|
||||
"record_number": "CAMA" + old["pac_id"].astype(str).str.zfill(4),
|
||||
}) # fmt: skip
|
||||
invasive = events[(events["type"] == "biopsy") & (events["value_code"] == "invasive")]
|
||||
index = invasive.groupby("person_id")["date"].min().rename("index_date")
|
||||
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
|
||||
return events.merge(index, left_on="person_id", right_index=True)
|
||||
|
||||
|
||||
def test_survival_matches_the_current_model():
|
||||
spec = MODELS["survival"]
|
||||
events = _timelines()
|
||||
model, metrics, _ = spec.train(events, pd.Timestamp(TRAINED_ON).date())
|
||||
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
||||
for name in ("n_train", "n_test", "stack_w_lr_6m", "stack_w_lr_12m", "stack_w_lr_18m"):
|
||||
assert metrics[name] == current["metrics"][name], name
|
||||
ours = spec.predict(model, events)
|
||||
ref = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
||||
ref = ref.assign(person_id=ref["pac_id"].astype(str), horizon_years=ref["horizonte_anios"])
|
||||
both = ours.merge(ref, on=["person_id", "horizon_years"], validate="1:1")
|
||||
assert len(both) == len(ref) == len(ours)
|
||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||
np.testing.assert_allclose(both["probability"], both["probabilidad"], rtol=1e-6)
|
||||
@@ -1,24 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from models.tea.eeg import curves
|
||||
|
||||
|
||||
def test_centile_interpolation_preserves_scoring():
|
||||
baseline = {
|
||||
"kind": "curves",
|
||||
"curve": {
|
||||
"age_months": [16, 36],
|
||||
"p5": [1, 3],
|
||||
"p25": [2, 4],
|
||||
"median": [3, 5],
|
||||
"p75": [5, 7],
|
||||
"p95": [7, 9],
|
||||
},
|
||||
}
|
||||
assert curves.centiles(baseline, 24) == pytest.approx(
|
||||
{"p5": 2, "p25": 3, "median": 4, "p75": 6, "p95": 8}
|
||||
)
|
||||
for value, z, outside in ((0, -3.29, -1), (3, -0.8225, 0), (6, 0.8225, 0), (10, 2.4675, 1)):
|
||||
assert curves.score(baseline, value, 24) == pytest.approx(
|
||||
{"z": z, "outside": outside, "p5": 2, "median": 4, "p95": 8}, rel=1e-9
|
||||
)
|
||||
@@ -1,50 +0,0 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from edf_files import small_edf
|
||||
|
||||
from models.tea.eeg.read import FileNotValid, Header, _kept, header
|
||||
|
||||
|
||||
def test_header_reads_the_facts(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
assert header(data) == Header(
|
||||
"N1001", "F", date(2025, 1, 5), date(2026, 3, 2), "LAB-1", 20.0, 3
|
||||
)
|
||||
|
||||
|
||||
def test_placeholders_are_none(tmp_path):
|
||||
data = small_edf(
|
||||
tmp_path / "a.edf", patient_code="X", sex="X", birthdate=None,
|
||||
startdate=date(1985, 1, 1), record_code="X",
|
||||
) # fmt: skip
|
||||
assert header(data) == Header(None, None, None, None, None, 20.0, 3)
|
||||
|
||||
|
||||
def test_header_does_not_read_the_signal(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
truncated = data[: int(data[184:192])]
|
||||
assert header(truncated) == header(data)
|
||||
assert header(truncated).duration_s == 20.0
|
||||
with pytest.warns(UserWarning, match="Updating header"):
|
||||
with pytest.raises(FileNotValid, match="truncated"):
|
||||
_kept(truncated)
|
||||
|
||||
|
||||
def test_zero_signal_header_is_valid(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
zero = data[:184] + b"256 " + data[192:252] + b"0 "
|
||||
assert header(zero).channels == 0
|
||||
with pytest.raises(FileNotValid, match="ZeroDivisionError"):
|
||||
_kept(zero)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [b"", b"x" * 100, b"x" * 300])
|
||||
def test_not_an_edf_is_not_valid(data):
|
||||
with pytest.raises(FileNotValid):
|
||||
header(data)
|
||||
|
||||
|
||||
def test_kept_channels_are_unchanged(tmp_path):
|
||||
data = small_edf(tmp_path / "a.edf")
|
||||
assert _kept(data) == [("Fp1", "Fp1"), ("Fp2", "Fp2"), ("Cz", "Cz")]
|
||||
+331
-17
@@ -1,28 +1,342 @@
|
||||
import numpy as np
|
||||
"""The rewritten TEA EEG analysis computes what the current one computes: for every hospital
|
||||
EEG with an EDF, the same verdict, checks, metric values and per-electrode / per-zone values
|
||||
(the reference tables, in the current platform's codes); and age baselines trained on our own
|
||||
features of the HK1K reference cohort score each EEG as the current registered baselines did
|
||||
(z, outside, p5, median, p95 of each metric, z of each electrode and zone).
|
||||
|
||||
Tolerance: RTOL = 1e-9 relative (absolute below 1). Values are compared after the reference's
|
||||
own storage (floats as captured); counts, texts, flags and levels exactly. The report at the
|
||||
end of each test says how many compared fields are bit-identical.
|
||||
|
||||
Needs the hospital database (`~/isssteleon-data/hospital_tea.db`), and for the curves the
|
||||
Helsinki EDFs (`/mnt/drive/eeg-helsinki`) unless their features are cached
|
||||
(`~/isssteleon-data/cache/eeg_hk1k_features.json`; `EEG_REBUILD_REFERENCE=1` measures the 223
|
||||
studies again: 10-20 min on 4 workers). The 78 hospital EEGs take about 40 s on 4 workers.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.tea.eeg import curves, signals
|
||||
pytest.importorskip("mne")
|
||||
pytest.importorskip("edfio")
|
||||
|
||||
from models.tea.eeg import curves, reference # noqa: E402
|
||||
from models.tea.eeg.analysis import analyze # noqa: E402
|
||||
|
||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "tea"
|
||||
DATA = Path.home() / "isssteleon-data"
|
||||
HOSPITAL = DATA / "hospital_tea.db"
|
||||
HELSINKI = Path("/mnt/drive/eeg-helsinki")
|
||||
CACHE = DATA / "cache" / "eeg_hk1k_features.json"
|
||||
OLD_FEATURES = DATA / "specs" / "eeg" / "hk1k_features.json" # only to check our own features
|
||||
RTOL = 1e-9
|
||||
WORKERS = 4
|
||||
|
||||
pytestmark = pytest.mark.skipif(not HOSPITAL.exists(), reason="no hospital database")
|
||||
|
||||
CODES = {
|
||||
"RITMO_POSTERIOR": "posterior_rhythm",
|
||||
"HUSOS_SUENO_N2": "spindles_n2",
|
||||
"HUSOS_SUENO_N3": "spindles_n3",
|
||||
"PICOS_PAROXISTICOS": "paroxysmal_spikes",
|
||||
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient",
|
||||
}
|
||||
LEVELS = {
|
||||
"completo": "complete",
|
||||
"sin_referencia_auricular": "no_ear_reference",
|
||||
"parcial": "partial",
|
||||
"no_analizable": "not_analyzable",
|
||||
}
|
||||
ZONES = {
|
||||
"frontal_izq": "frontal_left",
|
||||
"frontal_der": "frontal_right",
|
||||
"frontal_media": "frontal_midline",
|
||||
"temporal_izq": "temporal_left",
|
||||
"temporal_der": "temporal_right",
|
||||
}
|
||||
# The current platform's features of the HK1K studies, by our scenario's feature names.
|
||||
OLD_SCENARIOS = {
|
||||
"eeg-posterior-rhythm": ("posterior_rhythm|", {"value": "posterior_rhythm_hz"}),
|
||||
"eeg-gradient": ("gradient|", {"value": "gradient_delta_sueno"}),
|
||||
"eeg-spikes": (
|
||||
"spikes|",
|
||||
{
|
||||
"value": "spike_rate_nrem",
|
||||
"minutes": "spike_minutes_nrem",
|
||||
"electrode_": "spike_density_nrem_",
|
||||
"zone_": "spike_zone_rate_nrem_",
|
||||
},
|
||||
),
|
||||
**{
|
||||
f"eeg-spindles-{s}": (
|
||||
f"spindles|{s.upper()}",
|
||||
{"value": "spindle_density_per_min_channel", "zone_": "spindle_zone_"},
|
||||
)
|
||||
for s in ("n2", "n3")
|
||||
},
|
||||
**{
|
||||
f"eeg-spindle-topography-{s}": (
|
||||
f"spindle_topography|{s.upper()}",
|
||||
{"electrode_": "topo_enh_"},
|
||||
)
|
||||
for s in ("n2", "n3")
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class Tally:
|
||||
"""Compared fields: bit-identical, within RTOL, and the mismatches."""
|
||||
|
||||
def __init__(self):
|
||||
self.exact, self.close, self.wrong = 0, 0, []
|
||||
|
||||
def __call__(self, where, ours, theirs):
|
||||
if isinstance(ours, bool):
|
||||
ours = int(ours)
|
||||
if ours is None or theirs is None or isinstance(ours, str) or isinstance(theirs, str):
|
||||
ok = ours == theirs
|
||||
self.exact += ok
|
||||
else:
|
||||
a, b = float(ours), float(theirs)
|
||||
ok = a == b or abs(a - b) <= RTOL * max(1.0, abs(a), abs(b))
|
||||
self.exact += a == b
|
||||
self.close += ok and a != b
|
||||
if not ok:
|
||||
self.wrong.append((where, ours, theirs))
|
||||
|
||||
def report(self, name):
|
||||
total = self.exact + self.close + len(self.wrong)
|
||||
print(
|
||||
f"{name}: {total} fields, {self.exact} identical, {self.close} within {RTOL:g}, "
|
||||
f"{len(self.wrong)} different"
|
||||
)
|
||||
|
||||
|
||||
def _table(name):
|
||||
return json.loads((FIXTURES / "tables" / f"{name}.json").read_text())
|
||||
|
||||
|
||||
def _edfs():
|
||||
with sqlite3.connect(f"file:{HOSPITAL}?mode=ro", uri=True) as con:
|
||||
rows = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
|
||||
return {key: bytes(edf) for key, edf in rows}
|
||||
|
||||
|
||||
def _analysed(key_edf):
|
||||
key, edf = key_edf
|
||||
return key, analyze(edf)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def analyses():
|
||||
edfs = _edfs()
|
||||
with ProcessPoolExecutor(WORKERS, mp_context=get_context("spawn")) as pool:
|
||||
return dict(pool.map(_analysed, [(k, edfs[k]) for k in sorted(edfs)]))
|
||||
|
||||
|
||||
def test_verdicts_and_checks(analyses):
|
||||
eeg = {r["eeg_id"]: r for r in _table("eeg")}
|
||||
criteria = _table("eeg_criterio")
|
||||
tally = Tally()
|
||||
for key, a in analyses.items():
|
||||
ref = eeg[key]
|
||||
assert a.error is None, (key, a.error)
|
||||
pairs = {
|
||||
"eeg_valido": a.valid,
|
||||
"eeg_nivel": a.level,
|
||||
"eeg_edad_meses": a.age_months,
|
||||
"eeg_fraccion_limpia": a.clean_fraction,
|
||||
"eeg_canales_malos": a.bad_channels,
|
||||
"eeg_canales": a.channels,
|
||||
"eeg_duracion_min": a.duration_min,
|
||||
"eeg_ruido_linea_db": a.line_noise_db,
|
||||
"eeg_con_sueno": a.sleep,
|
||||
"eeg_error": a.error,
|
||||
}
|
||||
for field, ours in pairs.items():
|
||||
theirs = LEVELS[ref[field]] if field == "eeg_nivel" else ref[field]
|
||||
tally((key, field), ours, theirs)
|
||||
theirs = sorted(
|
||||
(
|
||||
(
|
||||
r["cri_codigo"],
|
||||
r["cri_electrodo"] or "",
|
||||
r["cri_valor"],
|
||||
LEVELS.get(r["cri_valor_texto"], r["cri_valor_texto"]),
|
||||
r["cri_unidad"],
|
||||
r["cri_bajo"],
|
||||
r["cri_alto"],
|
||||
r["cri_decisivo"],
|
||||
r["cri_anormal"],
|
||||
)
|
||||
for r in criteria
|
||||
if r["cri_eeg_id"] == key
|
||||
),
|
||||
key=lambda t: (t[0], t[1], str(t[3])),
|
||||
)
|
||||
ours = sorted(
|
||||
(
|
||||
(
|
||||
c["code"],
|
||||
c["electrode"] or "",
|
||||
c["value"],
|
||||
c["text"],
|
||||
c["unit"],
|
||||
c["low"],
|
||||
c["high"],
|
||||
c["decisive"],
|
||||
c["abnormal"],
|
||||
)
|
||||
for c in a.checks
|
||||
),
|
||||
key=lambda t: (t[0], t[1], str(t[3])),
|
||||
)
|
||||
tally((key, "checks"), len(ours), len(theirs))
|
||||
for o, t in zip(ours, theirs, strict=False):
|
||||
for name, x, y in zip(
|
||||
(
|
||||
"code",
|
||||
"electrode",
|
||||
"value",
|
||||
"text",
|
||||
"unit",
|
||||
"low",
|
||||
"high",
|
||||
"decisive",
|
||||
"abnormal",
|
||||
),
|
||||
o,
|
||||
t,
|
||||
strict=True,
|
||||
):
|
||||
tally((key, o[0], o[1], name), x, y)
|
||||
tally.report("eeg + eeg_criterio")
|
||||
assert not tally.wrong, tally.wrong[:20]
|
||||
|
||||
|
||||
def _reference_metrics():
|
||||
"""(eeg, our code) -> (metric row, {electrode: row}, {our zone: row})."""
|
||||
electrodes, zones = {}, {}
|
||||
for r in _table("eeg_metrica_electrodo"):
|
||||
electrodes.setdefault(r["mel_met_id"], {})[r["mel_electrodo"]] = r
|
||||
for r in _table("eeg_metrica_zona"):
|
||||
zones.setdefault(r["mez_met_id"], {})[ZONES.get(r["mez_zona"], r["mez_zona"])] = r
|
||||
return {
|
||||
(r["met_eeg_id"], CODES[r["met_codigo"]]): (
|
||||
r,
|
||||
electrodes.get(r["met_id"], {}),
|
||||
zones.get(r["met_id"], {}),
|
||||
)
|
||||
for r in _table("eeg_metrica")
|
||||
}
|
||||
|
||||
|
||||
def test_metric_values(analyses):
|
||||
reference_rows = _reference_metrics()
|
||||
tally = Tally()
|
||||
for key, a in analyses.items():
|
||||
expected = sorted(code for k, code in reference_rows if k == key)
|
||||
tally((key, "metrics"), ",".join(sorted(m.code for m in a.metrics)), ",".join(expected))
|
||||
for m in a.metrics:
|
||||
row, electrodes, zones = reference_rows[key, m.code]
|
||||
tally((key, m.code), m.value, row["met_valor"])
|
||||
tally(
|
||||
(key, m.code, "electrodes"),
|
||||
",".join(sorted(m.electrodes)),
|
||||
",".join(sorted(electrodes)),
|
||||
)
|
||||
tally((key, m.code, "zones"), ",".join(sorted(m.zones)), ",".join(sorted(zones)))
|
||||
for e, v in m.electrodes.items():
|
||||
tally((key, m.code, e), v, electrodes[e]["mel_valor"])
|
||||
for z, v in m.zones.items():
|
||||
tally((key, m.code, z), v, zones[z]["mez_valor"])
|
||||
tally.report("eeg_metrica + electrodes + zones, values")
|
||||
assert not tally.wrong, tally.wrong[:20]
|
||||
|
||||
|
||||
def _measure_reference():
|
||||
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
|
||||
measured = reference.measure(studies)
|
||||
CACHE.parent.mkdir(parents=True, exist_ok=True)
|
||||
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
|
||||
return measured
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def hk1k():
|
||||
if CACHE.exists() and os.environ.get("EEG_REBUILD_REFERENCE") != "1":
|
||||
return json.loads(CACHE.read_text())["studies"]
|
||||
if not HELSINKI.exists():
|
||||
pytest.skip("no cached HK1K features and no Helsinki EDFs")
|
||||
return _measure_reference()
|
||||
|
||||
|
||||
def _old_feature(feature: str, names: dict[str, str]) -> str:
|
||||
"""`electrode_Fp1` -> `topo_enh_Fp1`, `zone_frontal_left` -> `spindle_zone_frontal_izq`."""
|
||||
if feature in names:
|
||||
return names[feature]
|
||||
prefix, rest = feature.split("_", 1)
|
||||
return names[prefix + "_"] + {ours: old for old, ours in ZONES.items()}.get(rest, rest)
|
||||
|
||||
|
||||
def test_reference_features(hk1k):
|
||||
"""Our HK1K features are the current platform's (as it measured them for its baselines)."""
|
||||
if not OLD_FEATURES.exists():
|
||||
pytest.skip("no captured HK1K features")
|
||||
old = {s["key"]: s for s in json.loads(OLD_FEATURES.read_text())["studies"]}
|
||||
tally = Tally()
|
||||
assert len(hk1k) == len(old) == 223
|
||||
for study in hk1k:
|
||||
theirs = old[study["key"]]
|
||||
tally((study["key"], "age"), study["age_months"], theirs["age_months"])
|
||||
tally((study["key"], "valid"), study["valid"], theirs["valid"])
|
||||
for scenario, (old_name, names) in OLD_SCENARIOS.items():
|
||||
for feature, v in study["features"][scenario].items():
|
||||
old_feature = _old_feature(feature, names)
|
||||
tally((study["key"], feature), v, theirs["features"][old_name][old_feature])
|
||||
tally.report("HK1K features")
|
||||
assert not tally.wrong, tally.wrong[:20]
|
||||
|
||||
|
||||
def test_curves(analyses, hk1k):
|
||||
"""Baselines trained on our HK1K features score each EEG as the registered ones did."""
|
||||
tables = reference.tables(hk1k)
|
||||
assert all(len(t) == 223 for t in tables.values())
|
||||
models = {name: curves.train(table, name) for name, table in tables.items()}
|
||||
json.dumps(models, allow_nan=False) # plain JSON, as MLflow logs it
|
||||
reference_rows = _reference_metrics()
|
||||
tally = Tally()
|
||||
for key, a in analyses.items():
|
||||
for code, scored in curves.deviations(models, a).items():
|
||||
row, electrodes, zones = reference_rows[key, code]
|
||||
value = scored["value"]
|
||||
for ours, theirs in (
|
||||
("z", "met_z"),
|
||||
("outside", "met_fuera"),
|
||||
("p5", "met_p5"),
|
||||
("median", "met_mediana"),
|
||||
("p95", "met_p95"),
|
||||
):
|
||||
tally((key, code, ours), value[ours], row[theirs])
|
||||
for e, s in scored.get("electrodes", {}).items():
|
||||
tally((key, code, e, "z"), s["z"], electrodes[e]["mel_z"])
|
||||
for z, s in scored.get("zones", {}).items():
|
||||
tally((key, code, z, "z"), s["z"], zones[z]["mez_z"])
|
||||
tally.report("eeg_metrica z/outside/p5/median/p95 + electrode and zone z")
|
||||
assert not tally.wrong, tally.wrong[:20]
|
||||
|
||||
|
||||
def test_score_without_value_or_coverage():
|
||||
"""No value, or an age the curve doesn't cover (too few studies anywhere): all None."""
|
||||
table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]})
|
||||
baseline = curves.train(table, "eeg-gradient")["value"]
|
||||
empty = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
assert curves.score(baseline, None, 25.0) == empty
|
||||
assert curves.score(baseline, 2.0, 25.0) == empty
|
||||
|
||||
|
||||
def test_dominant_peak_recovers_a_posterior_rhythm_above_background():
|
||||
frequencies = np.arange(1.0, 46.0, 0.5)
|
||||
background = 1 / frequencies
|
||||
power = background.copy()
|
||||
power[frequencies == 8] *= 10
|
||||
assert signals.dominant_peak(frequencies, power) == (8.0, pytest.approx(10), True)
|
||||
assert not signals.dominant_peak(frequencies, background)[2]
|
||||
|
||||
|
||||
def test_band_power_excludes_line_noise_and_rescales_clean_bins():
|
||||
frequencies = np.arange(7.0, 14.0)
|
||||
power = np.array([100.0, 2.0, 30.0, 40.0, 30.0, 4.0, 100.0])
|
||||
assert signals.band_power(frequencies, power, 8, 13, lines=(10,)) == 15
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from models import execution
|
||||
from models.execution import Execution, ExecutionError
|
||||
from persistance import cluster
|
||||
|
||||
|
||||
def square(x):
|
||||
return int(x) ** 2
|
||||
|
||||
|
||||
def fail_on_three(x):
|
||||
if x == 3:
|
||||
raise RuntimeError("three")
|
||||
return x
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def env(monkeypatch):
|
||||
for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
def test_resolve_defaults_and_allow_list(monkeypatch):
|
||||
assert execution.resolve().mode == "local"
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
assert execution.resolve().mode == "sync"
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.resolve(Execution(mode="remote"))
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786")
|
||||
assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786"
|
||||
assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == (
|
||||
"tcp://b:8786"
|
||||
)
|
||||
assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"]
|
||||
|
||||
|
||||
def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786")
|
||||
with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"):
|
||||
execution.resolve(Execution(mode="remote", scheduler="c:8786"))
|
||||
with pytest.raises(ExecutionError, match="only goes with remote"):
|
||||
execution.resolve(Execution(mode="local", scheduler="a:8786"))
|
||||
with pytest.raises(ExecutionError, match="not host:port"):
|
||||
cluster.normalize("http://a:1")
|
||||
|
||||
|
||||
def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
lines = []
|
||||
assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16]
|
||||
assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5"
|
||||
|
||||
|
||||
def test_map_on_error_converts_a_failed_item(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None)
|
||||
assert out == [0, 1, 2, -3, 4, 5]
|
||||
|
||||
|
||||
def test_map_raises_without_on_error(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
with pytest.raises(RuntimeError, match="three"):
|
||||
execution.map(fail_on_three, range(6), log=lambda s: None)
|
||||
|
||||
|
||||
def test_eta_smoothing_and_threshold():
|
||||
eta = execution.Eta(alpha=0.3, min_done=3)
|
||||
eta.update(0.0, 0)
|
||||
eta.update(1.0, 2)
|
||||
assert eta.eta_s(10) is None
|
||||
eta.update(2.0, 4)
|
||||
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
|
||||
eta.update(3.0, 8)
|
||||
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
|
||||
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
|
||||
the rules point at is read into text (scanned ones through OCR). The site: the synthetic
|
||||
hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs)."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
|
||||
|
||||
|
||||
def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict:
|
||||
"""What an operator would draw for this site: one Source per table, and a Read on each
|
||||
column that holds documents."""
|
||||
|
||||
def table(node_id, credentials, name, **args):
|
||||
args = {"credentials": credentials, "table": name, **args}
|
||||
return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args}
|
||||
|
||||
nodes = [
|
||||
table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t)
|
||||
for name, tables in hospital_tables.items()
|
||||
for t in tables
|
||||
]
|
||||
return {
|
||||
"nodes": nodes
|
||||
+ [
|
||||
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
|
||||
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
SQL_TABLE = "dlt.sources.sql_database:sql_table"
|
||||
|
||||
|
||||
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path):
|
||||
count, query = platform.count, platform.query
|
||||
tables = {}
|
||||
for name in ("cacu", "cama"):
|
||||
shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db")
|
||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||
found = con.execute("select name from sqlite_master where type = 'table'")
|
||||
tables[name] = [t for (t,) in found]
|
||||
truth = site.truth
|
||||
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url)))
|
||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||
|
||||
by_place = {}
|
||||
for r in truth:
|
||||
by_place.setdefault(r["where"].split(":")[0], []).append(r)
|
||||
documents = len(truth)
|
||||
expected = {"resultados": documents, "text": documents}
|
||||
for name, names in tables.items():
|
||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||
for t in names:
|
||||
expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0]
|
||||
|
||||
def counts():
|
||||
return {node: count(f"bronze.n__site__{node}") for node in expected}
|
||||
|
||||
for _ in range(2): # loading the same site again changes nothing
|
||||
platform.ingest()
|
||||
assert counts() == expected
|
||||
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
|
||||
assert len(read_once) == documents # each file read once
|
||||
|
||||
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
|
||||
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
|
||||
platform.ingest()
|
||||
assert counts() == expected
|
||||
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
|
||||
assert query(corrected) == [("64000",)]
|
||||
|
||||
space = re.compile(r"\s+")
|
||||
for table in ("ResultadoSubrogado",):
|
||||
read = query("select id, text, ocr, error from bronze.n__site__text")
|
||||
assert [error for *_, error in read if error is not None] == []
|
||||
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
||||
for r in by_place[table]:
|
||||
txt, ocr = by_id[int(r["where"].split(":")[1])]
|
||||
assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans
|
||||
if "record_number" in r["identity"]: # even scanned, the number reads back exactly
|
||||
assert r["identity"]["record_number"] in txt, (r["where"], txt)
|
||||
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
|
||||
read_once
|
||||
) # reruns never read a file again
|
||||
@@ -0,0 +1,51 @@
|
||||
"""A reviewer's "they are different people" is about the persons: it holds when more records
|
||||
join one of them, whichever record the person is known by afterwards."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
PEOPLE = [("1001", "ANA LOPEZ RUIZ", "1980-01-01"), ("2002", "BEATRIZ MORA DIAZ", "1980-01-01")]
|
||||
PEOPLE += [(f"9{k:03d}", f"PERSONA {k} DE RELLENO", f"19{50 + k}-0{1 + k % 9}-11")
|
||||
for k in range(30)] # fmt: skip
|
||||
|
||||
|
||||
def graph(db) -> dict:
|
||||
fields = {"record_number": "num", "full_name": "nombre", "birth_date": "nac", "nss": "nss"}
|
||||
return {"nodes": [
|
||||
{"id": "people", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
|
||||
"args": {"credentials": f"sqlite:///{db}", "table": "people"}},
|
||||
{"id": "identity", "kind": "map", "inputs": ["people"], "fields": fields},
|
||||
{"id": "persons", "kind": "link", "inputs": ["identity"], "fields": list(fields)},
|
||||
]} # fmt: skip
|
||||
|
||||
|
||||
def insert(db, rows) -> None:
|
||||
with sqlite3.connect(db) as con:
|
||||
con.execute(
|
||||
"create table if not exists people "
|
||||
"(id integer primary key, num text, nombre text, nac text, nss text)"
|
||||
)
|
||||
con.executemany("insert into people (num, nombre, nac, nss) values (?, ?, ?, ?)", rows)
|
||||
|
||||
|
||||
def test_an_answer_outlives_the_record_a_person_was_known_by(platform, tmp_path):
|
||||
db, drawn = tmp_path / "people.db", tmp_path / "pipeline.json"
|
||||
insert(db, [(*p, None) for p in PEOPLE])
|
||||
drawn.write_text(json.dumps(graph(db)))
|
||||
platform.save("pipelines", "site", drawn)
|
||||
platform.ingest()
|
||||
queue = "select person, candidate from bronze.n__site__persons__review"
|
||||
((a, b),) = platform.query(queue)
|
||||
platform.run("python", "-c", "from persistance import nodes; "
|
||||
f"nodes.decide_persons({a!r}, {b!r}, False, 'reviewer')") # fmt: skip
|
||||
platform.ingest()
|
||||
assert platform.query(queue) == []
|
||||
|
||||
# Forty more documents of each woman: whichever of her records her person was known by,
|
||||
# one of these is (almost surely) it now.
|
||||
insert(db, [(num, None, None, f"{num}{k:07d}") for num in ("1001", "2002") for k in range(40)])
|
||||
platform.ingest()
|
||||
lowest = "select min(_record) from bronze.n__site__persons where record_number = '{}'"
|
||||
known = {platform.query(lowest.format(n))[0][0] for n in ("1001", "2002")}
|
||||
assert known != {a, b}
|
||||
assert platform.query(queue) == []
|
||||
@@ -0,0 +1,15 @@
|
||||
"""A stratum in which no row is at a level the fit saw gives no value, not an error."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.pim import Mixture
|
||||
|
||||
|
||||
def test_rows_only_at_unseen_levels_are_left_without_a_risk():
|
||||
X = pd.DataFrame({"cytology": ["NILM", "NILM", "ASC-US", "ASC-US"] * 10})
|
||||
y = pd.DataFrame({"c": [0, 1] * 20, "l": [1.0, 0.0] * 20, "r": [np.inf, 0.0] * 20})
|
||||
y.loc[::5, ["c", "l", "r"]] = [-999, 0.5, 2.0]
|
||||
mixture = Mixture((1, 5), ["cytology"], (), {"cytology": ["NILM", "ASC-US", "High Grade"]})
|
||||
mixture.fit(X, y)
|
||||
assert np.isnan(mixture.predict(pd.DataFrame({"cytology": ["High Grade"]}))).all()
|
||||
@@ -0,0 +1,43 @@
|
||||
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"
|
||||
+252
-19
@@ -1,13 +1,236 @@
|
||||
"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two
|
||||
published datasets, loaded by the platform's `cama_reference` pipeline (the files are in
|
||||
`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia).
|
||||
|
||||
Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's
|
||||
constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes
|
||||
and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal
|
||||
cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull
|
||||
curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value
|
||||
on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence;
|
||||
v1 stopped its fit on a 60-second wall clock, short of it, so its curve is v1's within
|
||||
FRACTIONAL_TOLERANCE, not equal. The fractional curve itself is a solver's, within
|
||||
SOLVER_TOLERANCE of the exact series.
|
||||
|
||||
The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to
|
||||
convergence, a few minutes each) are marked `slow` and run only with RECURRENCE_SLOW=1
|
||||
(about an hour); the default set takes about two minutes.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
import recurrence_reference as reference
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
from scipy.special import gammaln
|
||||
|
||||
from models import curves, survival
|
||||
from conftest import _platform
|
||||
from models import curves
|
||||
from models.cama import recurrence
|
||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||
|
||||
SOLVER_TOLERANCE = 1e-6
|
||||
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
|
||||
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1"
|
||||
# Max |S| difference to v1's fractional Weibull curve: v1 stopped its fit on a 60 s clock,
|
||||
# short of the optimum this fit converges to (largest gap measured: 0.053).
|
||||
FRACTIONAL_TOLERANCE = 0.06
|
||||
SOLVER_TOLERANCE = 1e-6 # max |S| error of the fractional Weibull's solver (~1e-7 measured)
|
||||
FACTOR_TOLERANCE = 1.01e-4
|
||||
|
||||
FILES = ("brca_metabric_clinical_data.tsv", "scanb_clinical_metadata.txt")
|
||||
PIPELINE = Path(__file__).parents[2] / "tests" / "fixtures" / "pipelines" / "cama_reference.json"
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not all((RAW / f).exists() for f in FILES), reason="no reference raw files"
|
||||
)
|
||||
slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset")
|
||||
|
||||
|
||||
def _json(path: str):
|
||||
return json.loads((V1 / path).read_text())
|
||||
|
||||
|
||||
VERSION = _json("version.json") if V1.exists() else {}
|
||||
DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exists() else {}
|
||||
FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else []
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
|
||||
"""Both datasets as the platform loads them: the `cama_reference` pipeline into a fresh
|
||||
platform, read back from its tables."""
|
||||
folder = tmp_path_factory.mktemp("platform")
|
||||
platform = _platform("sqlite", folder)
|
||||
drawn = folder / "pipeline.json"
|
||||
drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW)))
|
||||
platform.save("pipelines", "cama_reference", drawn)
|
||||
platform.ingest("cama_reference")
|
||||
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
||||
out = folder / "datasets.pkl"
|
||||
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
||||
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)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def prepared(raws):
|
||||
return {s: reference.prepare(s, raw) for s, raw in raws.items()}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fits(prepared):
|
||||
found = modeling.fit(prepared, {})
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
return found
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- comparisons
|
||||
|
||||
|
||||
# v1 read SCAN-B's clinical stage as a number, so its categories print as 0.0, 1.0...; the
|
||||
# platform keeps the dataset's text (0, 1...). Same categories, in the same order.
|
||||
STAGES = {f"{n}.0": str(n) for n in range(5)}
|
||||
|
||||
|
||||
def _stages(table: dict) -> dict:
|
||||
"""v1's summary with the stages as the dataset writes them."""
|
||||
text = re.sub(r"Estadio_clinico=(\d)\.0", r"Estadio_clinico=\1", json.dumps(table))
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0):
|
||||
ref = [{**r, **{k: STAGES.get(r[k], r[k]) for k in ("categoria", "referencia") if k in r}}
|
||||
if r.get("variable") == "Estadio_clinico" else r for r in ref] # fmt: skip
|
||||
assert len(mine) == len(ref)
|
||||
for i, (a, b) in enumerate(zip(mine, ref, strict=True)):
|
||||
assert a.keys() == b.keys(), i
|
||||
for c, z in b.items():
|
||||
x = a[c]
|
||||
if isinstance(z, float) and not isinstance(z, bool) and x is not None:
|
||||
assert abs(x - z) <= tolerance, (i, c, x, z)
|
||||
else:
|
||||
assert x == z, (i, c, x, z)
|
||||
|
||||
|
||||
def _auc_rows(rows: list[dict], with_bootstrap: bool) -> list[dict]:
|
||||
keep = slice(None) if with_bootstrap else slice(0, 6)
|
||||
return [dict(list(r.items())[keep]) for r in rows]
|
||||
|
||||
|
||||
def _reference_selection(source: str) -> dict:
|
||||
"""v1's bootstrap selection shares, as its risk-factor table published them."""
|
||||
found = {}
|
||||
for r in DEVELOPMENT["factores_riesgo"]["filas"]:
|
||||
if r["cohorte"] == source and r["tipo"] == "factor de riesgo":
|
||||
found.setdefault(r["horizonte_meses"], {})[r["variable"]] = r[
|
||||
"freq_seleccion_bootstrap"
|
||||
]
|
||||
return found
|
||||
|
||||
|
||||
def _check_figures(records: list[dict], fractional_tolerance: float):
|
||||
assert [(r["cohorte"], r["escenario"]) for r in records] == [
|
||||
(r["cohorte"], r["escenario"]) for r in FIGURES
|
||||
]
|
||||
for mine, ref in zip(records, FIGURES, strict=True):
|
||||
fixed = ("condiciones", "n", "recaidas", "observado_hasta", "months_max", "cohorte_nombre")
|
||||
assert {k: mine[k] for k in fixed} == {k: ref[k] for k in fixed}
|
||||
assert mine["bootstrap_replicas"] == ref["bootstrap_replicas"]
|
||||
assert mine["km"]["months"] == ref["km"]["months"]
|
||||
for part in ("S", "low", "high"):
|
||||
np.testing.assert_allclose(mine["km"][part], ref["km"][part], rtol=0, atol=1e-12)
|
||||
got, want = mine["points"]["COMB"][part], ref["points"]["COMB"][part]
|
||||
np.testing.assert_allclose(got, want, rtol=0, atol=1e-12)
|
||||
np.testing.assert_allclose(mine["weibull"]["t"], ref["weibull"]["t"], rtol=0, atol=0)
|
||||
np.testing.assert_allclose(mine["weibull"]["S"], ref["weibull"]["S"], rtol=0, atol=1e-12)
|
||||
gap = np.nanmax(np.abs(np.subtract(mine["weibull_fractional"]["S"],
|
||||
ref["weibull_fractional"]["S"]))) # fmt: skip
|
||||
assert gap <= fractional_tolerance, (mine["escenario"], gap)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- fast
|
||||
|
||||
|
||||
def test_cohorts(prepared):
|
||||
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
|
||||
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
|
||||
for source, c in prepared.items():
|
||||
assert len(c.frame) == sampling[source]["pacientes"]
|
||||
assert int(c.frame["evento"].sum()) == sampling[source]["recaidas"]
|
||||
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
||||
assert c.covariates == list(missing[source])
|
||||
assert cohorts.unknown_shares(c) == missing[source]
|
||||
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
||||
|
||||
|
||||
def test_routines(prepared):
|
||||
found = reports.routines(prepared, reference.N_BOOTSTRAP)
|
||||
for name, record in found.items():
|
||||
assert record == _json(f"rutinas/{name}.json"), name
|
||||
|
||||
|
||||
def test_c_index_and_internal_auc(fits):
|
||||
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)
|
||||
metrics = reports.metrics(rows)
|
||||
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
||||
|
||||
|
||||
def test_saved_model(fits):
|
||||
"""METABRIC's terms (in order of entry), parents, and their whole-cohort refits."""
|
||||
tables = modeling.tables(fits["metabric"])
|
||||
for h, mine in tables.items():
|
||||
ref = VERSION["model"]["tables"][str(h)]
|
||||
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
|
||||
assert {**mine, "hbn_cpt": cpt} == ref, h
|
||||
frame, covariates = fits["metabric"].cohort.frame, fits["metabric"].cohort.covariates
|
||||
model = recurrence.Recurrence("metabric", recurrence.HORIZONS, covariates, tables)
|
||||
found = model.predict(frame.iloc[:5])
|
||||
assert list(found.columns) == ["recurrence_12m", "recurrence_36m", "recurrence_60m"]
|
||||
t = tables[36]
|
||||
row = frame.iloc[0]
|
||||
x = np.array([float(f"{v}_{row[v]}" == term) for term in t["lr_terms"]
|
||||
for v in [modeling.variable_of(term, model.covariates)]]) # fmt: skip
|
||||
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + x @ np.array(t["lr_coefficients"]))))
|
||||
p_hbn = t["hbn_cpt"][tuple(row[p] for p in t["hbn_parents"])]
|
||||
assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@slow
|
||||
def test_calculator(fits):
|
||||
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
||||
records, rows = [], []
|
||||
for source in reference.SOURCES:
|
||||
found = calculator.calculator(fits[source])
|
||||
records += found[0]
|
||||
rows += found[1]
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
table = reports.table(pd.DataFrame(rows).round(4))
|
||||
assert table["columnas"] == DEVELOPMENT["calculadora"]["columnas"]
|
||||
_same_rows(table["filas"], DEVELOPMENT["calculadora"]["filas"])
|
||||
_check_figures(records, FRACTIONAL_TOLERANCE)
|
||||
|
||||
|
||||
def test_risk_factors(fits):
|
||||
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
||||
table = pd.concat(
|
||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in reference.SOURCES],
|
||||
ignore_index=True,
|
||||
)
|
||||
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
||||
FACTOR_TOLERANCE) # fmt: skip
|
||||
summary = [r for s in reference.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
||||
|
||||
|
||||
def test_fractional_weibull_reproduces_the_classic_one():
|
||||
"""With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's."""
|
||||
t = np.linspace(0, 300, 61)
|
||||
for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)):
|
||||
found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam)
|
||||
@@ -15,6 +238,7 @@ def test_fractional_weibull_reproduces_the_classic_one():
|
||||
|
||||
|
||||
def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741
|
||||
"""E_{rho,m,l}(z) by its defining series, in floats: exact where |z| is small."""
|
||||
j = np.arange(terms - 1)
|
||||
log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1)
|
||||
- gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip
|
||||
@@ -22,6 +246,7 @@ def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) ->
|
||||
|
||||
|
||||
def test_fractional_weibull_solver_matches_the_series():
|
||||
"""Where the series is exact in floats (|z| < 2), the solver gives it within its error."""
|
||||
t = np.linspace(0, 72, 289)
|
||||
for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)):
|
||||
s = k + a - 2
|
||||
@@ -31,20 +256,28 @@ def test_fractional_weibull_solver_matches_the_series():
|
||||
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
|
||||
|
||||
|
||||
def test_survival_censors_deaths_after_follow_up_or_horizon():
|
||||
index = pd.Series(["2020-01-01"] * 4)
|
||||
death = pd.Series(["2020-03-05", "2020-05-15", "2020-08-01", None])
|
||||
result = survival.outcomes(index, death, "2020-06-01", cap_months=3)
|
||||
assert list(result.itertuples(index=False, name=None)) == [
|
||||
(2, True),
|
||||
(3, False),
|
||||
(3, False),
|
||||
(3, False),
|
||||
]
|
||||
uncapped = survival.outcomes(index, death, "2020-06-01", cap_months=0)
|
||||
assert list(uncapped.itertuples(index=False, name=None)) == [
|
||||
(2, True),
|
||||
(4, True),
|
||||
(4, False),
|
||||
(4, False),
|
||||
]
|
||||
# ---------------------------------------------------------------- slow: the whole v1 run
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@slow
|
||||
def test_train_reproduces_v1(raws):
|
||||
model, metrics, found = reference.train(raws, bootstrap=True)
|
||||
assert metrics == VERSION["metrics"]
|
||||
for h in recurrence.HORIZONS:
|
||||
mine = model.tables[h]
|
||||
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
|
||||
assert {**mine, "hbn_cpt": cpt} == VERSION["model"]["tables"][str(h)]
|
||||
technical = found["technical_validation"]
|
||||
for name, record in technical["rutinas"].items():
|
||||
assert record == _json(f"rutinas/{name}.json"), name
|
||||
tables = technical["recurrencia_desarrollo"]["tablas"]
|
||||
_same_rows(tables["auc"]["filas"], DEVELOPMENT["auc"]["filas"])
|
||||
_same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"])
|
||||
_same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
||||
FACTOR_TOLERANCE) # fmt: skip
|
||||
assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"])
|
||||
figures = found["interpretability"]["recurrencia"]
|
||||
assert figures["horizons_months"] == [12, 36, 60]
|
||||
_check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE)
|
||||
json.dumps(found, allow_nan=False) # JSON-able as it is
|
||||
|
||||
+174
-15
@@ -1,19 +1,178 @@
|
||||
from persistance.nodes import stable_persons
|
||||
"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst
|
||||
can trust, and everything the platform can't decide alone is put in front of a reviewer.
|
||||
|
||||
The source hides its answers the way the real one does (synthetic.site): one PDF per study in
|
||||
one SQL Server table, the institute's forms beside what outsourced labs send back; an HPV result
|
||||
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
|
||||
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, neurology's), death notes and TEA's
|
||||
M-CHAT, ADOS-2 and EEG reports are the institute's forms.
|
||||
"""
|
||||
|
||||
import json
|
||||
from collections import Counter
|
||||
from datetime import date
|
||||
|
||||
from core import catalog
|
||||
|
||||
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
|
||||
FIELDS = {
|
||||
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
||||
"hpv_18"),
|
||||
"cervical_biopsy": ("request_date", "report_date", "histology"),
|
||||
"mammography": ("exam_date", "report_date", "adequacy", "birads"),
|
||||
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
|
||||
"er", "pr", "her2", "ki67_pct", "size_mm", "positive_nodes", "stage"),
|
||||
"breast_treatment": ("start_date", "kind"),
|
||||
"breast_recurrence": ("diagnosis_date", "site"),
|
||||
"clinical_note": ("note_date", "specialty", "icd10"),
|
||||
"death": ("death_date",),
|
||||
"mchat": ("screening_date", "score"),
|
||||
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
||||
"eeg": ("study_date", "lab_record_id", "edf"),
|
||||
} # fmt: skip
|
||||
BOOLS = {f for s in catalog.studies().values() for f, d in s.fields.items() if d.type == "boolean"}
|
||||
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
||||
|
||||
|
||||
def test_person_ids_survive_a_review_merge_and_split(fresh_platform):
|
||||
older = stable_persons({"one": ["a"]})["one"]
|
||||
newer = stable_persons({"two": ["b", "c"]})["two"]
|
||||
assert older != newer
|
||||
def value(field, v):
|
||||
if v is None:
|
||||
return None
|
||||
if field in BOOLS:
|
||||
return bool(v) if not isinstance(v, str) else v == "true"
|
||||
if field in NUMBERS:
|
||||
return float(v)
|
||||
return v.isoformat() if isinstance(v, date) else str(v)
|
||||
|
||||
assert stable_persons({"merged": ["a", "b", "c"]}) == {"merged": older}
|
||||
with fresh_platform.connect() as connection:
|
||||
assert connection.exec_driver_sql(
|
||||
"select person_id, replaced_by from bronze.person_link"
|
||||
).all() == [(newer, older)]
|
||||
|
||||
split = {"small": ["a"], "large": ["b", "c"]}
|
||||
assigned = stable_persons(split)
|
||||
assert assigned["large"] == older
|
||||
assert assigned["small"] not in {older, newer}
|
||||
assert stable_persons(split) == assigned
|
||||
def said(record: dict, entity: str) -> dict | None:
|
||||
"""What a document says of one study (an oncology note: its treatment and the note)."""
|
||||
if entity == "clinical_note":
|
||||
return record.get("clinical_note")
|
||||
return record["values"] if record["entity"] == entity else None
|
||||
|
||||
|
||||
def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path):
|
||||
truth = site.truth
|
||||
(tmp_path / "pipeline.json").write_text(site.drawn)
|
||||
platform.save("concept_maps", "erick_site", site.concept_map)
|
||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||
platform.ingest()
|
||||
q = platform.query
|
||||
of = site.patients(q)
|
||||
|
||||
# Persons: nobody is merged with somebody else, except the two women of one name, joined
|
||||
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
|
||||
# whose report it is.
|
||||
# A person nothing names (a scan whose name line wasn't read) is held as well: there is
|
||||
# nobody to join her to.
|
||||
members: dict[str, set] = {}
|
||||
held, nameless, named, person_of = set(), set(), set(), {}
|
||||
for record, person, why, *identifiers in q(
|
||||
"select _record, person_id, _held, full_name, birth_date, record_number "
|
||||
"from bronze.n__site__persons"
|
||||
):
|
||||
members.setdefault(person, set()).add(of[record])
|
||||
person_of[record] = person
|
||||
if any(identifiers):
|
||||
named.add(person)
|
||||
if why and "no name" in why:
|
||||
nameless.add(person)
|
||||
elif why:
|
||||
held.add(person)
|
||||
assert nameless == set(members) - named, nameless
|
||||
torn = {p for p, who in members.items() if len(who) > 1}
|
||||
assert len(torn) == 1 and torn == held, (torn, held)
|
||||
assert members[next(iter(torn))] == set(site.meta["namesakes"])
|
||||
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless}
|
||||
|
||||
# Every woman split into several persons (a misspelled form, say) is in the review
|
||||
# queue, joined by candidates.
|
||||
parts: dict[str, set] = {}
|
||||
for p, x in patient.items():
|
||||
parts.setdefault(x, set()).add(p)
|
||||
queued = {
|
||||
frozenset(person_of[r] for r in pair)
|
||||
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
||||
}
|
||||
split = {x: persons for x, persons in parts.items() if len(persons) > 1}
|
||||
assert split # the misspelled forms, at least
|
||||
for x, persons in split.items():
|
||||
reached, frontier = set(), {next(iter(persons))}
|
||||
while frontier:
|
||||
reached |= frontier
|
||||
frontier = {b for a in frontier for pair in queued if a in pair for b in pair}
|
||||
frontier -= reached
|
||||
assert persons <= reached, (x, persons)
|
||||
|
||||
# Every value accepted from a typed document is what the document says; and most of what
|
||||
# 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
|
||||
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
|
||||
# values (one, on a site too small for a rate), each listed.
|
||||
at = {r["where"]: r for r in truth}
|
||||
place = {r: f"ResultadoSubrogado:{i}"
|
||||
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
|
||||
record_of = {w: r for r, w in place.items()}
|
||||
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
|
||||
for entity in FIELDS:
|
||||
mine = accepted[entity] = {}
|
||||
for record, field, *values in q(
|
||||
"select _record, field, value_text, value_num, value_bool, value_date "
|
||||
f"from bronze.staged__observation where study = '{entity}'"
|
||||
):
|
||||
got = next((v for v in values if v is not None), None)
|
||||
mine.setdefault(record, {})[field] = value(field, got)
|
||||
assert mine or not any(said(r, entity) for r in truth), entity
|
||||
stated = read = scanned = 0
|
||||
missed: Counter = Counter()
|
||||
wrong = []
|
||||
for record, got in mine.items():
|
||||
t = at[place[record]]
|
||||
if not t.get("flipped"):
|
||||
truly = {f: v for f, v in said(t, entity).items() if v is not None}
|
||||
differ = {f: (v, value(f, truly.get(f))) for f, v in got.items()
|
||||
if v != value(f, truly.get(f))} # fmt: skip
|
||||
assert t.get("scanned") or not differ, (t["where"], differ)
|
||||
wrong += [(t["where"], differ)] if differ else []
|
||||
scanned += len(got) if t.get("scanned") else 0
|
||||
stated, read = stated + len(truly), read + len(got)
|
||||
missed.update(set(truly) - set(got))
|
||||
assert read >= 0.95 * stated, (entity, read, stated, missed)
|
||||
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:
|
||||
# never loaded, and a reviewer sees it.
|
||||
misread = set()
|
||||
for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"):
|
||||
if record in place and person_of.get(record) not in torn | nameless:
|
||||
t, got = at[place[record]], json.loads(raw)
|
||||
truly = said(t, entity)
|
||||
assert {f: value(f, got.get(f)) for f in truly} != {
|
||||
f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip
|
||||
misread.add(record)
|
||||
|
||||
# Silver: each person's studies, the records of one study key merged (a cytology form and
|
||||
# its HPV report are one cytology), but for the torn person's, the misreads, and a study
|
||||
# whose reports contradict each other (until review says which is right).
|
||||
for entity, fields in FIELDS.items():
|
||||
key = catalog.studies()[entity].key
|
||||
merged: dict[tuple, dict] = {}
|
||||
disputed = set()
|
||||
for r in truth:
|
||||
record = record_of[r["where"]]
|
||||
got = accepted[entity].get(record)
|
||||
if got is None or person_of[record] in torn | nameless or record in misread:
|
||||
continue
|
||||
at_key = (person_of[record], *(got.get(k) for k in key))
|
||||
merged.setdefault(at_key, {}).update(got)
|
||||
if r.get("conflict"):
|
||||
disputed.add(at_key)
|
||||
expected = {(k[0], *(row.get(f) for f in fields))
|
||||
for k, row in merged.items() if k not in disputed} # fmt: skip
|
||||
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
||||
got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True)))
|
||||
for p, *values in rows if p not in torn | nameless} # fmt: skip
|
||||
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
|
||||
sorted(expected - got, key=str)[:4]) # fmt: skip
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
"""CaMa survival measured against the SEER-trained original (Luis's pipeline,
|
||||
`05_curvas_supervivencia.py`): the same model, trained on the same SEER patients, gives each
|
||||
clinical scenario the same patients and deaths, the same observed curves (Kaplan-Meier,
|
||||
Weibull, fractional Weibull), and model points close to the original's.
|
||||
|
||||
SEER is real registry data under NCI's use agreement: it is read from outside git
|
||||
(SEER_FILE) and nothing of it is kept. The original's outputs are read from where it ran
|
||||
(LUIS_RUN: its `subgrupos_*.csv`). Both missing: the test is skipped.
|
||||
|
||||
Each SEER case becomes a timeline: a first invasive biopsy at diagnosis with its report's
|
||||
results, its first course of treatment a month later, and its death or last contact placed so
|
||||
the platform's whole months of follow-up are SEER's survival months.
|
||||
|
||||
The model points are not the original's: it trains on every case, the platform on the
|
||||
earliest 70% by index date (and validates on the rest), and SEER's latest diagnoses carry few
|
||||
recorded deaths yet. They are checked against the survival of the cases the model learned
|
||||
from; their distance to the original's is printed. Slow (a quarter of an hour): SEER_SLOW=1."""
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models import curves, survival
|
||||
from models.cama.specs import MODELS
|
||||
from models.survival import DAYS_PER_MONTH, DAYS_PER_YEAR, TRAIN_FRACTION, scenario_masks
|
||||
|
||||
SEER = Path(
|
||||
os.environ.get("SEER_FILE", Path.home() / "camaSupervivencia" / "dataframe_recodificado.csv")
|
||||
)
|
||||
RUN = Path(os.environ.get("LUIS_RUN", Path.home() / "isssteleon-data" / "luis-run"))
|
||||
AS_OF = pd.Timestamp("2023-12-31") # SEER's follow-up cutoff: survivors are followed to it
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.skipif(
|
||||
not (SEER.exists() and (RUN / "subgrupos_KM_Weibull_fraccional.csv").exists()),
|
||||
reason="SEER and the original's outputs are outside git",
|
||||
),
|
||||
pytest.mark.skipif(not os.environ.get("SEER_SLOW"), reason="slow: SEER_SLOW=1"),
|
||||
]
|
||||
CURVE = 1e-3 # the fits' agreement (maximum distance to Kaplan-Meier, shape k relative)
|
||||
CALIBRATION = 0.01 # the model's mean survival against its training cases' Kaplan-Meier
|
||||
|
||||
STAGE = {"0 (in situ)": "0", "I": "I", "II": "II", "III": "III", "IV": "IV"}
|
||||
GRADE = {"G1": "1", "G2": "2", "G3": "3"}
|
||||
RECEPTOR = {"Positivo": "positive", "Negativo": "negative"}
|
||||
SURGERY = {"Conservadora": "breast_conserving_surgery", "Mastectomía": "mastectomy"}
|
||||
|
||||
|
||||
def _her2(subtype: str) -> str | None:
|
||||
return "positive" if "HER2+" in subtype else "negative" if "HER2-" in subtype else None
|
||||
|
||||
|
||||
def _age(recode: str) -> float:
|
||||
"""The age band's lower bound, as the original reads it ("65-69 years": 65)."""
|
||||
found = re.search(r"\d+", str(recode))
|
||||
return float(found.group()) if found else np.nan
|
||||
|
||||
|
||||
def seer_events(frame: pd.DataFrame) -> pd.DataFrame:
|
||||
"""SEER cases as CaMa timelines (gold `cama_events` shape, indexed at diagnosis)."""
|
||||
months = pd.to_numeric(frame["Survival_months"], errors="coerce")
|
||||
frame, months = frame[months.notna()], months[months.notna()]
|
||||
dead = frame["Vital_status_recode_study_cutoff_used"].str.lower().str.contains("dead")
|
||||
person = frame["Patient_ID"].to_numpy()
|
||||
# Whole months from the index are SEER's. A survivor's index is months + 1/2 before the
|
||||
# cutoff; a death's is in its year of diagnosis (spread over the year by its id, never so
|
||||
# late that the death would pass the cutoff), and she dies months + 1/4 after it. So the
|
||||
# index dates keep SEER's calendar, which the model's split by index date reads.
|
||||
latest = AS_OF - pd.to_timedelta((months + 0.5) * DAYS_PER_MONTH, "D")
|
||||
year = pd.to_datetime(frame["Year_of_diagnosis"] + "-01-01")
|
||||
spread = pd.to_timedelta(frame["Patient_ID"].astype(int) % 365, "D")
|
||||
index = latest.where(~dead, (year + spread).where(year + spread < latest, latest))
|
||||
death = index + pd.to_timedelta((months + 0.25) * DAYS_PER_MONTH, "D")
|
||||
birth = index - pd.to_timedelta((frame["Age_recode_with_1_year_olds_and_90"].map(_age) + 0.5)
|
||||
* DAYS_PER_YEAR, "D") # fmt: skip
|
||||
base = pd.DataFrame({"person_id": person, "index_date": index.to_numpy(),
|
||||
"record_number": person}) # fmt: skip
|
||||
rows = [base.assign(date=birth.to_numpy(), type="birth", value_code=None)]
|
||||
rows.append(base[dead.to_numpy()].assign(date=death[dead].to_numpy(), type="death",
|
||||
value_code=None)) # fmt: skip
|
||||
hr_negative = frame["Subtipo_molecular_cat"].str.startswith("HR-")
|
||||
hr_positive = frame["Subtipo_molecular_cat"].str.startswith("HR+")
|
||||
er = frame["Receptor_estrogeno_cat"].map(RECEPTOR)
|
||||
pr = frame["Receptor_progesterona_cat"].map(RECEPTOR)
|
||||
both_negative = er.eq("negative") & pr.eq("negative")
|
||||
results = {
|
||||
"biopsy": pd.Series("invasive", index=frame.index),
|
||||
"stage": frame["Estadio_cat"].map(STAGE),
|
||||
"grade": frame["Grado_histologico_cat"].map(GRADE),
|
||||
# Hormone receptors as SEER's subtype states them, which the original's scenarios read:
|
||||
# SEER's own columns disagree in a few cases (HR+ with both recodes negative, likely
|
||||
# borderline results): HR- makes both negative; HR+ with both negative leaves ER unknown.
|
||||
"er": er.mask(hr_negative, "negative").mask(hr_positive & both_negative, None),
|
||||
"pr": pr.mask(hr_negative, "negative"),
|
||||
"her2": frame["Subtipo_molecular_cat"].map(_her2),
|
||||
"histologic_type": frame["Histologic_Type_ICD_O_3"].astype(str) + "/3",
|
||||
}
|
||||
for kind, values in results.items():
|
||||
rows.append(base.assign(date=index.to_numpy(), type=kind, value_code=values.to_numpy()))
|
||||
size = pd.to_numeric(frame["Tumor_Size_Over_Time_Recode_1988"], errors="coerce")
|
||||
rows.append(base.assign(date=index.to_numpy(), type="size_mm", value_code=None,
|
||||
value_num=size.where(size < 990).to_numpy())) # fmt: skip
|
||||
course = {
|
||||
"surgery": frame["Tratamiento_quirurgico_cat"].map(SURGERY),
|
||||
"chemotherapy": frame["Quimioterapia_cat"].map({"Sí": "chemotherapy"}),
|
||||
"radiotherapy": frame["Radioterapia_cat"].map({"Sí": "radiotherapy"}),
|
||||
}
|
||||
month_later = index + pd.Timedelta(days=30)
|
||||
for values in course.values():
|
||||
rows.append(base.assign(date=month_later.to_numpy(), type="treatment",
|
||||
value_code=values.to_numpy())) # fmt: skip
|
||||
events = pd.concat(rows, ignore_index=True)
|
||||
events = events[events["type"].isin(["birth", "death"]) | events["value_code"].notna()
|
||||
| events.get("value_num", pd.Series(np.nan)).notna()] # fmt: skip
|
||||
events["value_num"] = events.get("value_num")
|
||||
events["source_table"], events["source_id"] = "seer", events["person_id"]
|
||||
return events.reset_index(drop=True)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def trained():
|
||||
events = seer_events(pd.read_csv(SEER, dtype=str))
|
||||
spec = MODELS["survival"]
|
||||
model, metrics, data = spec.train(events, AS_OF)
|
||||
return spec, model, metrics, data
|
||||
|
||||
|
||||
def _original(name: str) -> pd.DataFrame:
|
||||
return pd.read_csv(RUN / name)
|
||||
|
||||
|
||||
def test_each_scenario_takes_the_originals_patients_and_deaths(trained):
|
||||
spec, _, _, data = trained
|
||||
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
|
||||
masks = scenario_masks(members, spec.scenarios)
|
||||
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
|
||||
for name, row in theirs.iterrows():
|
||||
mask = masks[name]
|
||||
assert (int(mask.sum()), int(members["event"][mask].sum())) == (
|
||||
row["n"],
|
||||
row["fallecidos"],
|
||||
), name
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def report(trained):
|
||||
spec, model, _, data = trained
|
||||
return survival.interpretability(spec, model, data)
|
||||
|
||||
|
||||
def test_each_scenarios_observed_curves_are_the_originals(report):
|
||||
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
|
||||
assert {e["escenario"] for e in report["escenarios"]} == set(theirs.index)
|
||||
for e in report["escenarios"]:
|
||||
row, km = theirs.loc[e["escenario"]], np.array(e["km"]["S"])
|
||||
months = np.arange(len(km))
|
||||
weibull = np.interp(months, e["weibull"]["t"], e["weibull"]["S"])
|
||||
fractional = np.interp(months, e["weibull_fractional"]["t"], e["weibull_fractional"]["S"])
|
||||
assert e["weibull"]["k"] == pytest.approx(row["k Weibull"], rel=CURVE), e["escenario"]
|
||||
assert np.abs(weibull - km).max() == pytest.approx(row["máx|KM−Weibull|"], abs=CURVE)
|
||||
assert np.abs(fractional - km).max() <= row["máx|KM−fracc.|"] + CURVE, e["escenario"]
|
||||
|
||||
|
||||
def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained, report):
|
||||
spec, _, _, data = trained
|
||||
train = data["train"].reset_index(drop=True)
|
||||
masks = scenario_masks(train, spec.scenarios)
|
||||
theirs = _original("subgrupos_puntos_LR_HBN.csv")
|
||||
horizons = list(spec.borders[1:])
|
||||
for e in report["escenarios"]:
|
||||
mask = masks[e["escenario"]]
|
||||
months, event = train["months"][mask].to_numpy(), train["event"][mask].to_numpy(bool)
|
||||
km, _, _ = curves.kaplan_meier(months, event, horizons[-1])
|
||||
ours = np.array(e["points"]["COMB"]["S"])
|
||||
assert ours == pytest.approx(km[horizons], abs=CALIBRATION), e["escenario"]
|
||||
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
|
||||
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}")
|
||||
|
||||
|
||||
# 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
|
||||
@@ -1,41 +0,0 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core.tea import ADOS2_ITEMS
|
||||
from models.tea import association as a
|
||||
|
||||
|
||||
def test_firth_on_separation():
|
||||
frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6})
|
||||
fit = a.firth(frame, "event", "z", ())
|
||||
assert np.isfinite(fit["odds_ratio"])
|
||||
assert fit["ci_low"] < fit["odds_ratio"] < fit["ci_high"]
|
||||
|
||||
|
||||
def test_bh():
|
||||
np.testing.assert_allclose(a.bh([0.04, 0.01, np.nan, 0.03]), [0.04, 0.03, np.nan, 0.04])
|
||||
|
||||
|
||||
def test_ordinal_on_monotone_trend():
|
||||
frame = pd.DataFrame({"z": np.arange(12), "level": [0, 0, 1, 0, 1, 1, 2, 0, 2, 1, 2, 2]})
|
||||
assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1
|
||||
|
||||
|
||||
def test_pairs_and_item_availability():
|
||||
assert len(a.pairs("item")) == 41
|
||||
assert len(a.pairs("domain")) == 15
|
||||
assert ADOS2_ITEMS == [
|
||||
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact",
|
||||
"facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name",
|
||||
"ignoring", "requesting", "showing", "joint_attention_initiation",
|
||||
"joint_attention_response", "social_overtures_quality", "social_overtures_caregiver",
|
||||
"reciprocal_communication", "rapport_quality", "intonation", "stereotyped_language",
|
||||
"unusual_sensory_interest", "hand_finger_mannerisms", "repetitive_interests",
|
||||
] # fmt: skip
|
||||
frame = pd.DataFrame(
|
||||
{
|
||||
"ados_module": ["toddler", "module_1", "module_2", "module_3"],
|
||||
"vocalization_directed": [3, 7, 1, 1],
|
||||
}
|
||||
)
|
||||
np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan])
|
||||
@@ -1,77 +0,0 @@
|
||||
from datetime import date
|
||||
|
||||
import dagster as dg
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from models.definitions import ScopeConfig, after_ingest
|
||||
from persistance import eeg
|
||||
|
||||
|
||||
def test_scope_validation():
|
||||
assert eeg.Scope().mode == "pending"
|
||||
assert eeg.Scope(mode="first_n", n=3).n == 3
|
||||
good = "p1|2024-05-06"
|
||||
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
|
||||
bad = [
|
||||
{"mode": "first_n"},
|
||||
{"mode": "first_n", "n": 0},
|
||||
{"mode": "first_n", "n": 2, "ids": [good]},
|
||||
{"mode": "ids"},
|
||||
{"mode": "ids", "ids": [good], "n": 1},
|
||||
{"mode": "ids", "ids": ["nobar"]},
|
||||
{"mode": "ids", "ids": ["p|2024-5-6"]},
|
||||
{"mode": "ids", "ids": ["|2024-05-06"]},
|
||||
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
|
||||
{"mode": "pending", "n": 1},
|
||||
{"mode": "pending", "ids": [good]},
|
||||
{"mode": "other"},
|
||||
{"extra": 1},
|
||||
]
|
||||
for kwargs in bad:
|
||||
with pytest.raises(ValidationError):
|
||||
eeg.Scope(**kwargs)
|
||||
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
|
||||
with pytest.raises(ValidationError, match="first_n needs n"):
|
||||
ScopeConfig(mode="first_n").model()
|
||||
|
||||
|
||||
def test_after_ingest_requests_a_run_only_with_pending_eegs():
|
||||
skip = after_ingest("r1", lambda: False)
|
||||
assert isinstance(skip, dg.SkipReason)
|
||||
request = after_ingest("r1", lambda: True)
|
||||
assert isinstance(request, dg.RunRequest)
|
||||
assert request.run_key == "after-ingest-r1"
|
||||
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
|
||||
assert scope == {"mode": "pending"}
|
||||
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
|
||||
|
||||
|
||||
def test_tea_eeg_first_n_selects_exactly_n_pending_studies(fresh_platform):
|
||||
with fresh_platform.begin() as con:
|
||||
con.exec_driver_sql("create table silver.person (person_id text, birth_date text)")
|
||||
con.exec_driver_sql("insert into silver.person values ('p1', '2023-01-01')")
|
||||
con.exec_driver_sql("create table silver.eeg (person_id text, study_date text, edf text)")
|
||||
con.exec_driver_sql(
|
||||
"insert into silver.eeg values (?, ?, ?)",
|
||||
[
|
||||
("p1", "2025-01-01", "c"),
|
||||
("p1", "2025-02-01", "b"),
|
||||
("p1", "2025-03-01", "a"),
|
||||
("p1", "2025-04-01", "d"),
|
||||
("p1", "2025-05-01", None),
|
||||
],
|
||||
)
|
||||
con.exec_driver_sql("create table bronze.eeg_analysis (edf text)")
|
||||
con.exec_driver_sql("insert into bronze.eeg_analysis values ('b')")
|
||||
|
||||
birth = date(2023, 1, 1)
|
||||
assert eeg.select(eeg.Scope(mode="first_n", n=2)) == [
|
||||
{"edf": "a", "birth_date": birth},
|
||||
{"edf": "c", "birth_date": birth},
|
||||
]
|
||||
assert eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-02-01"])) == [
|
||||
{"edf": "b", "birth_date": birth}
|
||||
]
|
||||
with pytest.raises(LookupError, match="has no signal"):
|
||||
eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-05-01"]))
|
||||
@@ -1,61 +0,0 @@
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from dagster import build_op_context
|
||||
|
||||
from models.definitions import Preview, preview_study
|
||||
from models.tea import preview as study
|
||||
from persistance import config, previews
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def preview_area(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
return previews.area()
|
||||
|
||||
|
||||
def test_previews_area(preview_area):
|
||||
key = previews.put(b"file")
|
||||
assert key == hashlib.sha256(b"file").hexdigest()
|
||||
os.utime(preview_area / key, (1, 1))
|
||||
assert previews.put(b"file") == key
|
||||
assert (preview_area / key).stat().st_mtime == 1
|
||||
assert previews.get(key) == b"file"
|
||||
for invalid in ("../x", "abc"):
|
||||
with pytest.raises(ValueError):
|
||||
previews.get(invalid)
|
||||
with pytest.raises(LookupError, match=f"no preview file {'0' * 64}"):
|
||||
previews.get("0" * 64)
|
||||
previews.discard([key, None, "0" * 64])
|
||||
assert not (preview_area / key).exists()
|
||||
|
||||
old = previews.put(b"old")
|
||||
recent = previews.put(b"recent")
|
||||
os.utime(preview_area / old, (1, 1))
|
||||
assert previews.sweep() == 1
|
||||
assert {path.name for path in preview_area.iterdir()} == {recent}
|
||||
|
||||
|
||||
def test_an_unreadable_file_is_a_result_not_a_crash():
|
||||
result = study.preview(b"nope")
|
||||
assert result.eeg.valid is False
|
||||
assert result.eeg.checks
|
||||
assert result.ados2 is None
|
||||
assert result.eeg.recorded_on is None
|
||||
|
||||
|
||||
def test_the_job_deletes_its_files_and_returns_the_result_as_output(preview_area):
|
||||
edf = previews.put(b"not an EDF")
|
||||
report = previews.put(b"not a PDF")
|
||||
with build_op_context() as context:
|
||||
result = preview_study(context, Preview(edf=edf, ados2=report))
|
||||
assert result == {"valid": False, "warnings": 1}
|
||||
assert list(preview_area.iterdir()) == []
|
||||
|
||||
|
||||
def test_the_job_deletes_its_files_when_the_study_fails(preview_area):
|
||||
report = previews.put(b"%PDF")
|
||||
with build_op_context() as context, pytest.raises(LookupError, match="no preview file"):
|
||||
preview_study(context, Preview(edf="0" * 64, ados2=report))
|
||||
assert list(preview_area.iterdir()) == []
|
||||
@@ -1,42 +0,0 @@
|
||||
import pytest
|
||||
from edf_files import small_edf
|
||||
from pydantic import ValidationError
|
||||
|
||||
from models.tea import jobs
|
||||
from persistance.cluster import Reference
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False)
|
||||
folder = tmp_path / "hel"
|
||||
folder.mkdir()
|
||||
for i in range(3):
|
||||
small_edf(folder / f"{i}.edf")
|
||||
ages = folder / "edades.csv"
|
||||
ages.write_text("name,age\n0.edf,1.5\n1.edf,2.0\n2.edf,2.5\n")
|
||||
return folder, ages
|
||||
|
||||
|
||||
def test_bad_references_fail_with_a_reason(cohort):
|
||||
folder, ages = cohort
|
||||
for name in ("..", ".", "nope"):
|
||||
with pytest.raises(ValueError) as exc:
|
||||
jobs._reference(Reference(name=name))
|
||||
assert str(exc.value) == f"no reference cohort {name!r}"
|
||||
|
||||
ages.write_text("name,age\n0.edf,1\n1.edf,4\n2.edf,5\n")
|
||||
with pytest.raises(
|
||||
ValueError, match="reference cohort 'hel' has no EDF with an age from 16 to 36 months"
|
||||
):
|
||||
jobs._reference(Reference(name="hel"))
|
||||
|
||||
ages.unlink()
|
||||
with pytest.raises(ValueError, match=r"reference cohort 'hel' has no edades\.csv"):
|
||||
jobs._reference(Reference(name="hel"))
|
||||
|
||||
with pytest.raises(ValidationError, match="name"):
|
||||
Reference(name="../x")
|
||||
with pytest.raises(ValidationError, match="line_hz"):
|
||||
Reference(name="hel", line_hz=55)
|
||||
Reference in New Issue
Block a user