Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| daff410b46 | |||
| 04c9b3124b | |||
| f99cca5176 | |||
| aca4c9d58a | |||
| a1e2e07e0c | |||
| 17a60ff68d | |||
| efa2c2793e | |||
| 3a033efc1b | |||
| d27b585560 | |||
| 1feedad79a | |||
| da14e4ea8e | |||
| fe1f284e00 | |||
| d392cc02a5 | |||
| 8a860c698f | |||
| 6e6c5bb81b | |||
| d27319ad1f | |||
| b5480e8bbb | |||
| dbbea0b16e | |||
| 76e88d0779 | |||
| 8548eb8d9e |
@@ -0,0 +1,20 @@
|
||||
# Fundamento bayesiano en desarrollo
|
||||
|
||||
`prevalence_gibbs.py` y sus pruebas proceden de `edgar/bayes-pim`, commit
|
||||
`1cef69be90a7a9ea30378118cd2a2c9fa312943e`. Solo se cambió el import de las
|
||||
pruebas. El módulo incluye Gibbs de prevalencia transversal y funciones NUTS
|
||||
con importación diferida de PyMC; no está conectado a producción ni a Dagster.
|
||||
|
||||
Esto **no implementa todavía** el modelo longitudinal: faltan los módulos de
|
||||
Markov y Klausch, el adaptador de visitas gold con fecha de disponibilidad,
|
||||
la ejecución NUTS, y el artefacto de diagnóstico y comparación. El original
|
||||
usa CIN3+ y categorías de biopsia que esta plataforma no puede identificar
|
||||
por separado; no se deben transformar HSIL o CIN2+ en CIN3+. Su fitting
|
||||
además importa `models.cacu.cin2_pim.likelihood`, que no existe aquí: hay que
|
||||
verificar matemáticamente la equivalencia con el PIM actual antes de conectar
|
||||
las verosimilitudes. La disponibilidad temporal y la definición del desenlace
|
||||
se deben resolver antes de entrenar con datos reales.
|
||||
|
||||
No se añadieron PyMC ni otras dependencias al entorno de producción. El modelo
|
||||
se mantiene únicamente como código de investigación, sin registro, promoción,
|
||||
servicio de predicciones ni entrenamiento con datos de pacientes.
|
||||
@@ -0,0 +1,190 @@
|
||||
"""The prevalence part of Klausch's BayesPIM as a conjugate Gibbs sampler, for cross-sectional screening data.
|
||||
|
||||
Klausch, Lissenberg-Witte and Coupé (2026), Stat Med 45(8-9):e70433, doi:10.1002/sim.70433. Their R package needs
|
||||
follow-up times to initialise the incidence part, so it cannot fit a sample with one test per woman (2026 sample of
|
||||
Modelo-cacu, issue 0120). With no follow-up only the prevalence part is informed, and it is this:
|
||||
|
||||
z_i ~ N(x_i beta, 1), g_i = 1[z_i > 0] true state at the test (probit, Albert and Chib 1993)
|
||||
y_i | g_i, r_i = 1 ~ Bernoulli(kappa g_i) the test: specificity 1, sensitivity kappa
|
||||
r_i = 0 no test (or no result): g_i is only augmented
|
||||
|
||||
Every full conditional is a standard distribution, so each step is an exact draw:
|
||||
g (Bernoulli, z integrated out), z (truncated normal), beta (normal), kappa (beta).
|
||||
|
||||
The extension proposed in chapter 19 (selection of who gets the test, the arc g -> r) adds a second probit,
|
||||
|
||||
w_i ~ N(u_i gamma + gamma_g arc_i g_i, 1), r_i = 1[w_i > 0]
|
||||
|
||||
with arc_i = 1 where the hospital protocol does not refer the woman's cell (referral there is clinical suspicion or
|
||||
persistence). It keeps conjugacy: w is another truncated normal, (gamma, gamma_g) another normal regression with the
|
||||
augmented g as a column, and g gains the factor P(r_i | g = 1) / P(r_i | g = 0). With one test per woman gamma_g is
|
||||
weakly identified and needs an informative prior.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
from scipy.stats import norm, truncnorm
|
||||
|
||||
|
||||
def normal_posterior(X: np.ndarray, z: np.ndarray, b0: np.ndarray, B0inv: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""beta | z for a regression with unit-variance errors and prior N(b0, B0): N(m, V) with
|
||||
V = (X'X + B0^-1)^-1 and m = V (X'z + B0^-1 b0). Returns m and the Cholesky factor of V."""
|
||||
V = np.linalg.inv(X.T @ X + B0inv)
|
||||
m = V @ (X.T @ z + B0inv @ b0)
|
||||
return m, np.linalg.cholesky(V)
|
||||
|
||||
|
||||
def draw_latent(mean: np.ndarray, positive: np.ndarray, rng: np.random.Generator) -> np.ndarray:
|
||||
"""Albert-Chib step: z ~ N(mean, 1) truncated to z > 0 where `positive`, to z <= 0 elsewhere."""
|
||||
lo = np.where(positive, -mean, -np.inf)
|
||||
hi = np.where(positive, np.inf, -mean)
|
||||
return mean + truncnorm.rvs(lo, hi, random_state=rng)
|
||||
|
||||
|
||||
def prob_g(p: np.ndarray, r: np.ndarray, y: np.ndarray, kappa: float, odds_r=1.0) -> np.ndarray:
|
||||
"""P(g_i = 1 | beta, kappa, data) with z_i integrated out: prior odds p / (1 - p) times the likelihood ratio of
|
||||
what was observed of woman i, P(data | g = 1) / P(data | g = 0):
|
||||
|
||||
* tested positive: infinite (specificity 1: only a diseased woman tests positive), so g = 1;
|
||||
* tested negative: (1 - kappa) / 1 (a diseased woman is missed with probability 1 - kappa);
|
||||
* untested: 1 (nothing observed).
|
||||
|
||||
`odds_r` is the extra ratio P(r_i | g = 1) / P(r_i | g = 0) of the referral arc; 1 without it."""
|
||||
lr = np.where(r == 1, np.where(y == 1, np.inf, 1.0 - kappa), 1.0) * odds_r
|
||||
odds = p / (1.0 - p) * lr
|
||||
with np.errstate(invalid="ignore"): # inf / inf in the branch that np.where drops
|
||||
return np.where(np.isinf(odds), 1.0, odds / (1.0 + odds))
|
||||
|
||||
|
||||
def draw_kappa(g: np.ndarray, r: np.ndarray, y: np.ndarray, a: float, b: float, rng: np.random.Generator) -> float:
|
||||
"""kappa | g, y ~ Beta(a + detected, b + missed), counting only tested women whose (augmented) g is 1."""
|
||||
diseased = (r == 1) & (g == 1)
|
||||
detected = int((y[diseased] == 1).sum())
|
||||
return rng.beta(a + detected, b + int(diseased.sum()) - detected)
|
||||
|
||||
|
||||
def referral_odds(eta_r: np.ndarray, gamma_g: float, arc: np.ndarray, r: np.ndarray) -> np.ndarray:
|
||||
"""The arc g -> r: P(r_i | g_i = 1) / P(r_i | g_i = 0) when r_i = 1[w_i > 0], w_i ~ N(eta_r_i + gamma_g arc_i g_i, 1).
|
||||
For a tested woman it is Phi(eta + gamma_g) / Phi(eta); for an untested one, the same with the survival
|
||||
function. Where arc_i = 0 (the protocol refers her cell) both are equal and the ratio is 1. Logs for stability."""
|
||||
shifted = eta_r + gamma_g * arc
|
||||
log1 = np.where(r == 1, norm.logcdf(shifted), norm.logsf(shifted))
|
||||
log0 = np.where(r == 1, norm.logcdf(eta_r), norm.logsf(eta_r))
|
||||
return np.exp(log1 - log0)
|
||||
|
||||
|
||||
def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None,
|
||||
iterations: int = 4000, warmup: int = 2000, seed: int = 0) -> dict:
|
||||
"""One chain. X carries the intercept column; r = 1 if the test was done with a result, y its result (ignored
|
||||
where r = 0). Prior beta ~ N(b0, B0), kappa ~ Beta(kappa_ab). Returns the kept draws of beta and kappa.
|
||||
|
||||
With `U` (the referral design, with its intercept), the arc g -> r is added: w_i ~ N(U_i gamma + gamma_g arc_i g_i,
|
||||
1), r_i = 1[w_i > 0], with `arc` = 1 where the protocol does not refer the woman's cell (the arc acts) and
|
||||
delta = (gamma, gamma_g) ~ N(d0, D0), gamma_g last. Its draws are returned as "delta"."""
|
||||
rng = np.random.default_rng(seed)
|
||||
r, y = np.asarray(r, int), np.asarray(y, float)
|
||||
b0, B0inv = np.asarray(b0, float), np.linalg.inv(np.asarray(B0, float))
|
||||
beta, kappa = b0.copy(), kappa_ab[0] / sum(kappa_ab)
|
||||
with_arc = U is not None
|
||||
if with_arc:
|
||||
arc, d0 = np.asarray(arc, float), np.asarray(d0, float)
|
||||
D0inv, delta = np.linalg.inv(np.asarray(D0, float)), np.asarray(d0, float).copy()
|
||||
kept = {"beta": [], "kappa": [], "delta": []}
|
||||
for it in range(iterations):
|
||||
eta = X @ beta
|
||||
p = np.clip(norm.cdf(eta), 1e-12, 1 - 1e-12)
|
||||
odds_r = referral_odds(U @ delta[:-1], delta[-1], arc, r) if with_arc else 1.0
|
||||
g = rng.random(len(r)) < prob_g(p, r, y, kappa, odds_r) # 1. g | beta, delta, kappa, data
|
||||
z = draw_latent(eta, g, rng) # 2. z | g, beta
|
||||
m, L = normal_posterior(X, z, b0, B0inv) # 3. beta | z
|
||||
beta = m + L @ rng.standard_normal(len(m))
|
||||
if with_arc:
|
||||
D = np.column_stack([U, g * arc]) # 4. the referral design, with g as a column
|
||||
w = draw_latent(D @ delta, r == 1, rng) # w | r, g, delta
|
||||
m, L = normal_posterior(D, w, d0, D0inv) # delta | w, g
|
||||
delta = m + L @ rng.standard_normal(len(m))
|
||||
kappa = draw_kappa(g, r, y, *kappa_ab, rng) # 5. kappa | g, y
|
||||
if it >= warmup:
|
||||
kept["beta"].append(beta)
|
||||
kept["kappa"].append(kappa)
|
||||
if with_arc:
|
||||
kept["delta"].append(delta)
|
||||
return {k: np.array(v) for k, v in kept.items() if v}
|
||||
|
||||
|
||||
def split_rhat(draws: np.ndarray) -> float:
|
||||
"""Split R-hat of one scalar (Gelman et al., BDA3, section 11.4): `draws` has shape (chains, iterations). Each
|
||||
chain is cut in half, and the spread between the halves' means is compared with the spread within them."""
|
||||
half = draws.shape[1] // 2
|
||||
parts = np.concatenate([draws[:, :half], draws[:, half:2 * half]])
|
||||
within = parts.var(axis=1, ddof=1).mean()
|
||||
between = half * parts.mean(axis=1).var(ddof=1)
|
||||
return float(np.sqrt(((half - 1) / half * within + between / half) / within))
|
||||
|
||||
|
||||
def patterns(X, r, y, U=None, arc=None) -> dict:
|
||||
"""Women with the same covariates and the same observation share their likelihood term: the distinct rows and
|
||||
how many women each one stands for (y = -1 marks an untested row)."""
|
||||
cols = [X, r[:, None], np.nan_to_num(y, nan=-1.0)[:, None]]
|
||||
if U is not None:
|
||||
cols += [U, np.asarray(arc, float)[:, None]]
|
||||
rows, counts = np.unique(np.column_stack(cols), axis=0, return_counts=True)
|
||||
p = X.shape[1]
|
||||
out = {"X": rows[:, :p], "r": rows[:, p].astype(int), "y": rows[:, p + 1], "n": counts.astype(float)}
|
||||
if U is not None:
|
||||
out["U"], out["arc"] = rows[:, p + 2:-1], rows[:, -1]
|
||||
return out
|
||||
|
||||
|
||||
def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None):
|
||||
"""The same model with g summed out of the likelihood, so that NUTS samples only continuous parameters:
|
||||
|
||||
P(data_i) = P(g=1) P(r_i | g=1) P(y_i | g=1) + P(g=0) P(r_i | g=0) P(y_i | g=0)
|
||||
|
||||
with P(y=1 | g=0) = 0 (specificity 1), so a tested positive keeps only the first term. Without `U` the test is
|
||||
taken as done at random given x, and P(r | g) drops out, as in the Gibbs."""
|
||||
import pymc as pm
|
||||
import pytensor.tensor as pt
|
||||
|
||||
d = patterns(np.asarray(X, float), np.asarray(r, int), np.asarray(y, float), U, arc)
|
||||
positive = (d["r"] == 1) & (d["y"] == 1)
|
||||
negative = (d["r"] == 1) & (d["y"] == 0)
|
||||
log_phi = lambda v: pm.logcdf(pm.Normal.dist(0.0, 1.0), v) # log Phi(v), stable in the tails
|
||||
with pm.Model() as model:
|
||||
beta = pm.MvNormal("beta", mu=np.asarray(b0, float), cov=np.asarray(B0, float))
|
||||
kappa = pm.Beta("kappa", *kappa_ab)
|
||||
eta = pt.as_tensor(d["X"]) @ beta
|
||||
log_g1, log_g0 = log_phi(eta), log_phi(-eta) # log P(g=1), log P(g=0)
|
||||
log_r1 = log_r0 = 0.0
|
||||
if U is not None:
|
||||
delta = pm.MvNormal("delta", mu=np.asarray(d0, float), cov=np.asarray(D0, float))
|
||||
eta_r = pt.as_tensor(d["U"]) @ delta[:-1]
|
||||
sign = np.where(d["r"] == 1, 1.0, -1.0) # P(r=1) = Phi(.), P(r=0) = Phi(-.)
|
||||
log_r1, log_r0 = log_phi(sign * (eta_r + delta[-1] * d["arc"])), log_phi(sign * eta_r)
|
||||
log_y1 = pt.switch(negative, pt.log1p(-kappa), 0.0) # a diseased woman missed: 1 - kappa
|
||||
diseased = log_g1 + log_r1 + log_y1
|
||||
healthy = log_g0 + log_r0
|
||||
loglik = pt.switch(positive, diseased + pt.log(kappa), pt.logaddexp(diseased, healthy))
|
||||
pm.Potential("loglik", pt.sum(d["n"] * loglik))
|
||||
return model
|
||||
|
||||
|
||||
def nuts(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None, draws: int = 1000,
|
||||
tune: int = 1000, chains: int = 4, seed: int = 0, cores: int | None = None) -> dict:
|
||||
"""NUTS on `pymc_model`. Returns the draws with the chains stacked (as in `gibbs`), the max split R-hat over the
|
||||
parameters and the number of divergent transitions. `cores` defaults to one per chain."""
|
||||
import pymc as pm
|
||||
|
||||
with pymc_model(X, r, y, b0, B0, kappa_ab, U, arc, d0, D0):
|
||||
idata = pm.sample(draws=draws, tune=tune, chains=chains, cores=cores or chains, random_seed=seed, progressbar=False,
|
||||
compute_convergence_checks=False)
|
||||
post = idata.posterior
|
||||
out, rhats = {}, []
|
||||
for name in ("beta", "kappa", "delta"):
|
||||
if name in post:
|
||||
v = post[name].values.reshape(chains, draws, -1) # (chains, draws, parameters)
|
||||
rhats += [split_rhat(v[:, :, j]) for j in range(v.shape[2])]
|
||||
out[name] = v.reshape(chains * draws, -1).squeeze() if name == "kappa" else v.reshape(chains * draws, -1)
|
||||
out["rhat"] = max(rhats)
|
||||
out["divergences"] = int(idata.sample_stats["diverging"].values.sum())
|
||||
return out
|
||||
@@ -1,161 +0,0 @@
|
||||
"""Development only (an opt-in Dagster job; nothing registered, promoted or scored): which of
|
||||
the binary encoders (models.cacu.encoders) predict CIN2+ at one year, by Firth's logistic
|
||||
regression and its FLIC and FLAC corrections, chosen and judged by nested stratified
|
||||
cross-validation and nested leave-one-out. Selection, coverage, rank checks and imputation
|
||||
see training partitions only."""
|
||||
|
||||
import itertools
|
||||
import math
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from firthmodels import FirthLogisticRegression
|
||||
from scipy.optimize import brentq
|
||||
from scipy.special import expit, logit
|
||||
from sklearn.base import BaseEstimator, ClassifierMixin, clone
|
||||
from sklearn.impute import SimpleImputer
|
||||
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, cross_val_predict
|
||||
from sklearn.pipeline import make_pipeline
|
||||
|
||||
METHODS = ("firth", "flic", "flac")
|
||||
FAILED = (ValueError, np.linalg.LinAlgError, RuntimeError)
|
||||
|
||||
|
||||
def firth(X, y, weights=None, penalty=0.5):
|
||||
"""A converged Firth fit (penalty 0: maximum likelihood) and its leverages."""
|
||||
model = FirthLogisticRegression(penalty_weight=penalty, max_iter=200, gtol=1e-6, xtol=1e-6)
|
||||
model.fit(X, y, sample_weight=weights)
|
||||
if not model.converged_:
|
||||
raise RuntimeError("the Firth fit did not converge")
|
||||
design = np.column_stack([np.ones(len(y)), X])
|
||||
p = expit(model.intercept_ + X @ model.coef_)
|
||||
w = (np.ones(len(y)) if weights is None else weights) * p * (1 - p)
|
||||
information = design.T @ (w[:, None] * design)
|
||||
return model, w * np.einsum("ij,ji->i", design, np.linalg.solve(information, design.T))
|
||||
|
||||
|
||||
class Firth(ClassifierMixin, BaseEstimator):
|
||||
"""Firth; FLIC (its intercept refit so the mean prediction is the outcome's); FLAC
|
||||
(refit by maximum likelihood with pseudo-observations weighted by half the leverage)."""
|
||||
|
||||
def __init__(self, method: str = "firth"):
|
||||
self.method = method
|
||||
|
||||
def fit(self, X, y):
|
||||
X, y = np.asarray(X, float), np.asarray(y, int)
|
||||
if np.linalg.matrix_rank(np.column_stack([np.ones(len(X)), X])) < X.shape[1] + 1:
|
||||
raise ValueError("collinear predictors in the training partition")
|
||||
model, h = firth(X, y)
|
||||
self.classes_, self.coef_, self.intercept_ = np.array([0, 1]), model.coef_, model.intercept_
|
||||
if self.method == "flic":
|
||||
eta = X @ self.coef_
|
||||
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
elif self.method == "flac":
|
||||
augmented = np.column_stack([np.tile(X, (3, 1)), np.repeat([0, 1, 1], len(y))])
|
||||
plain, _ = firth(augmented, np.r_[y, y, 1 - y], np.r_[np.ones(len(y)), h / 2, h / 2],
|
||||
penalty=0) # fmt: skip
|
||||
self.coef_, self.intercept_ = plain.coef_[:-1], plain.intercept_
|
||||
return self
|
||||
|
||||
def predict_proba(self, X):
|
||||
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
|
||||
return np.column_stack([1 - p, p])
|
||||
|
||||
|
||||
def same(a: pd.Series, b: pd.Series) -> bool:
|
||||
return bool(((a == b) | (a.isna() & b.isna())).all())
|
||||
|
||||
|
||||
def candidates(X: pd.DataFrame, coverage: float, limit: int) -> list[str]:
|
||||
"""Binary columns known for `coverage` of the rows, best covered first, without one
|
||||
identical or complementary to another, at most `limit`."""
|
||||
known = X.notna().mean()
|
||||
found = []
|
||||
for name in sorted(X, key=lambda n: (-known[n], n)):
|
||||
values = set(X[name].dropna().unique())
|
||||
if known[name] < coverage or values != {0, 1}:
|
||||
continue
|
||||
if not any(same(X[name], X[o]) or same(X[name], 1 - X[o]) for o in found):
|
||||
found.append(name)
|
||||
if len(found) == limit:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def predicted(train, y, test, columns, method, cv=None) -> np.ndarray:
|
||||
"""The probabilities for `test` (or, with `cv`, out of fold for `train`)."""
|
||||
if not columns:
|
||||
return np.repeat(np.mean(y), len(train) if cv else len(test))
|
||||
model = make_pipeline(SimpleImputer(strategy="median"), Firth(method))
|
||||
if cv is not None:
|
||||
return cross_val_predict(model, train[list(columns)], y, cv=cv,
|
||||
method="predict_proba")[:, 1] # fmt: skip
|
||||
return clone(model).fit(train[list(columns)], y).predict_proba(test[list(columns)])[:, 1]
|
||||
|
||||
|
||||
def metrics(y, p) -> dict:
|
||||
names = ("auc", "brier", "calibration_intercept", "calibration_slope", "log_loss")
|
||||
if not np.isfinite(p).all() or len(np.unique(y)) != 2:
|
||||
return dict.fromkeys(names)
|
||||
calibration = LogisticRegression(C=1e6).fit(logit(np.clip(p, 1e-12, 1 - 1e-12))[:, None], y)
|
||||
return dict(zip(names, map(float, (
|
||||
roc_auc_score(y, p), brier_score_loss(y, p), calibration.intercept_[0],
|
||||
calibration.coef_[0, 0], log_loss(y, p, labels=[0, 1]))), strict=True)) # fmt: skip
|
||||
|
||||
|
||||
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=100_000) -> dict: # fmt: skip
|
||||
"""Per method and validation (3-fold CV, leave-one-out): the subset each outer split
|
||||
chooses by inner out-of-fold log loss, the outer predictions' metrics, and every subset
|
||||
tried (with why it failed)."""
|
||||
X, y = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce"), np.asarray(y, int)
|
||||
if min(np.bincount(y, minlength=2)) < max(outer_folds, inner_folds + 1):
|
||||
raise ValueError("too few of each outcome for nested CV and leave-one-out")
|
||||
subsets_max = sum(math.comb(candidate_limit, k) for k in range(subset_limit + 1))
|
||||
fits = (outer_folds + len(X)) * len(METHODS) * (subsets_max * inner_folds + 1)
|
||||
if fits > max_fits:
|
||||
raise ValueError(f"estimated {fits} fits exceeds the limit {max_fits}")
|
||||
started, attempts, validation = time.monotonic(), [], {}
|
||||
inner = StratifiedKFold(inner_folds, shuffle=True, random_state=seed)
|
||||
plans = {"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed),
|
||||
"loocv": LeaveOneOut()} # fmt: skip
|
||||
for plan, outer in plans.items():
|
||||
p = {m: np.full(len(X), np.nan) for m in METHODS}
|
||||
chosen = {m: [] for m in METHODS}
|
||||
for fold, (a, b) in enumerate(outer.split(X, y)):
|
||||
train, test = X.iloc[a], X.iloc[b]
|
||||
names = candidates(train, coverage, candidate_limit)
|
||||
subsets = [c for k in range(min(len(names), subset_limit) + 1)
|
||||
for c in itertools.combinations(names, k)] # fmt: skip
|
||||
for method in METHODS:
|
||||
ranked = []
|
||||
for columns in subsets:
|
||||
loss = error = None
|
||||
try:
|
||||
oof = predicted(train, y[a], None, columns, method, cv=inner)
|
||||
loss = float(log_loss(y[a], oof, labels=[0, 1]))
|
||||
ranked.append((loss, len(columns), columns))
|
||||
except FAILED as e:
|
||||
error = type(e).__name__
|
||||
attempts.append({"validation": plan, "fold": fold, "method": method,
|
||||
"variables": list(columns), "inner_log_loss": loss,
|
||||
"error": error}) # fmt: skip
|
||||
best = min(ranked)[2]
|
||||
chosen[method].append(list(best))
|
||||
try:
|
||||
p[method][b] = predicted(train, y[a], test, best, method)
|
||||
except FAILED:
|
||||
pass
|
||||
validation[plan] = {m: {
|
||||
"metrics": metrics(y, p[m]), "selected": chosen[m],
|
||||
"unscored": int(np.isnan(p[m]).sum()),
|
||||
"stability": {n: sum(n in c for c in chosen[m]) for n in X},
|
||||
} for m in METHODS} # fmt: skip
|
||||
return {"development_only": True, "candidate_limit": candidate_limit,
|
||||
"subset_limit": subset_limit, "coverage_minimum": coverage,
|
||||
"max_subsets": subsets_max, "maximum_fits": fits,
|
||||
"elapsed_seconds": time.monotonic() - started, "attempts": attempts,
|
||||
"validation": validation} # fmt: skip
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import brentq
|
||||
from scipy.special import expit
|
||||
from sklearn.base import BaseEstimator, ClassifierMixin
|
||||
from sklearn.exceptions import ConvergenceWarning
|
||||
|
||||
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
|
||||
|
||||
|
||||
class ConvergenceError(RuntimeError):
|
||||
"""Raised when the remaining Newton step fails the convergence check."""
|
||||
|
||||
|
||||
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
|
||||
"""Fit logistic regression and return the fitted solver and leverages.
|
||||
|
||||
Check the remaining Newton step directly because numerical precision can
|
||||
affect the solver's convergence flag.
|
||||
"""
|
||||
y = np.asarray(y)
|
||||
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
|
||||
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
|
||||
y = y.astype(int, copy=False)
|
||||
|
||||
from firthmodels import FirthLogisticRegression
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", ConvergenceWarning)
|
||||
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
|
||||
X, y, sample_weight=sample_weight
|
||||
)
|
||||
design = np.column_stack([np.ones(len(y)), X])
|
||||
weights = np.ones(len(y)) if sample_weight is None else sample_weight
|
||||
p = expit(model.intercept_ + X @ model.coef_)
|
||||
w = weights * p * (1 - p)
|
||||
info = design.T @ (w[:, None] * design)
|
||||
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
|
||||
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
|
||||
step = np.abs(np.linalg.solve(info, score)).max()
|
||||
if not np.isfinite(step) or step >= 1e-4:
|
||||
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
|
||||
return model, h
|
||||
|
||||
|
||||
class FirthFamily(ClassifierMixin, BaseEstimator):
|
||||
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
|
||||
|
||||
def __init__(self, method="firth"):
|
||||
self.method = method
|
||||
|
||||
def fit(self, X, y):
|
||||
"""Fit the selected method to a binary outcome."""
|
||||
if self.method not in ("firth", "flic", "flac"):
|
||||
raise ValueError(f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'.")
|
||||
X = np.asarray(X, float)
|
||||
firth, h = solve_logistic(X, y)
|
||||
y = np.asarray(y, int)
|
||||
self.classes_ = np.array([0, 1])
|
||||
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
|
||||
|
||||
if self.method == "flic":
|
||||
eta = X @ self.coef_
|
||||
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
|
||||
|
||||
elif self.method == "flac":
|
||||
# Pseudo-observations use both outcomes, each with half the leverage.
|
||||
g = np.repeat([0, 1, 1], len(y))
|
||||
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
|
||||
self.y_aug_ = np.concatenate([y, y, 1 - y])
|
||||
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
|
||||
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
|
||||
# Predict on original observations, where the indicator is zero.
|
||||
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
|
||||
return self
|
||||
|
||||
def predict_proba(self, X):
|
||||
"""Return probabilities for classes 0 and 1 in that order."""
|
||||
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
|
||||
return np.column_stack([1 - p, p])
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Nested, exhaustive evaluation of a bounded set of CaCu binary encoders.
|
||||
|
||||
Development only. Selection, coverage screening, rank checks and imputation use training
|
||||
partitions only. Methods follow edgar/camodels commit 2392d54fd4a3942b56dae803906586bc65600728.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
import math
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.special import expit, logit
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
|
||||
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
|
||||
|
||||
from models.cacu.development_firth import FirthFamily
|
||||
|
||||
METHODS = ('firth', 'flic', 'flac')
|
||||
|
||||
|
||||
def _candidates(X, coverage, limit):
|
||||
eligible = []
|
||||
for name in sorted(X.columns):
|
||||
col = pd.to_numeric(X[name], errors='coerce')
|
||||
known = col.dropna()
|
||||
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
|
||||
eligible.append((name, col.notna().mean()))
|
||||
# Perfectly identical or complementary observed columns are not distinguishable.
|
||||
chosen = []
|
||||
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
|
||||
a = X[name]
|
||||
if any(((a == X[other]) | (a.isna() & X[other].isna())).all() or
|
||||
((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
|
||||
for other in chosen):
|
||||
continue
|
||||
chosen.append(name)
|
||||
if len(chosen) == limit:
|
||||
break
|
||||
return chosen
|
||||
|
||||
|
||||
def _matrix(train, test, columns):
|
||||
tr = train[list(columns)].to_numpy(dtype=float)
|
||||
te = test[list(columns)].to_numpy(dtype=float)
|
||||
if tr.shape[1] and np.isnan(tr).all(axis=0).any():
|
||||
raise ValueError('predictor absent in training partition')
|
||||
median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([])
|
||||
tr, te = np.where(np.isnan(tr), median, tr), np.where(np.isnan(te), median, te)
|
||||
if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1:
|
||||
raise ValueError('collinear predictors in training partition')
|
||||
return tr, te
|
||||
|
||||
|
||||
def _predict(train, y, test, columns, method):
|
||||
tr, te = _matrix(train, test, columns)
|
||||
if not columns:
|
||||
return np.repeat(np.mean(y), len(test))
|
||||
return FirthFamily(method).fit(tr, y).predict_proba(te)[:, 1]
|
||||
|
||||
|
||||
def _metrics(y, probability):
|
||||
y, p = np.asarray(y), np.asarray(probability)
|
||||
valid = np.isfinite(p)
|
||||
if valid.sum() != len(y) or len(np.unique(y)) != 2:
|
||||
return {'auc': None, 'brier': None, 'calibration_intercept': None,
|
||||
'calibration_slope': None, 'log_loss': None}
|
||||
logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1)
|
||||
calibration = LogisticRegression(C=1e6).fit(logits, y)
|
||||
return {'auc': float(roc_auc_score(y, p)), 'brier': float(brier_score_loss(y, p)),
|
||||
'calibration_intercept': float(calibration.intercept_[0]),
|
||||
'calibration_slope': float(calibration.coef_[0, 0]),
|
||||
'log_loss': float(log_loss(y, p, labels=[0, 1]))}
|
||||
|
||||
|
||||
def evaluate(X: pd.DataFrame, y, *, coverage=0.7, candidate_limit=5, subset_limit=2,
|
||||
outer_folds=3, inner_folds=2, seed=17, max_fits=100000):
|
||||
"""Evaluate Firth/FLIC/FLAC with nested stratified CV and nested leave-one-out.
|
||||
|
||||
A fixed upper bound (default five candidates, pairs at most) permits at most 16 subsets
|
||||
including the intercept. Each method selects a subset by inner out-of-fold log loss for
|
||||
every outer split; all attempted subsets and failures are recorded.
|
||||
"""
|
||||
X = X.reset_index(drop=True).apply(pd.to_numeric, errors='coerce')
|
||||
y = np.asarray(y)
|
||||
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
|
||||
raise ValueError('one known binary outcome is required per row')
|
||||
if min(np.bincount(y.astype(int), minlength=2)) < max(outer_folds, inner_folds + 1):
|
||||
raise ValueError('insufficient members of each outcome for nested CV and LOOCV')
|
||||
if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit:
|
||||
raise ValueError('candidate and subset limits exceed the supported bounds')
|
||||
max_subsets = sum(math.comb(candidate_limit, k)
|
||||
for k in range(min(candidate_limit, subset_limit) + 1))
|
||||
estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1)
|
||||
if estimated_fits > max_fits:
|
||||
raise ValueError(f'estimated {estimated_fits} fits exceeds configured limit {max_fits}')
|
||||
attempted, outputs = [], {}
|
||||
started = time.monotonic()
|
||||
plans = {'cv': StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
|
||||
'loocv': LeaveOneOut().split(X, y)}
|
||||
for plan, splits in plans.items():
|
||||
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
|
||||
selected = {m: [] for m in METHODS}
|
||||
for fold, (train_idx, test_idx) in enumerate(splits):
|
||||
train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int)
|
||||
candidates = _candidates(train, coverage, candidate_limit)
|
||||
subsets = [()] + [c for size in range(1, min(len(candidates), subset_limit) + 1)
|
||||
for c in itertools.combinations(candidates, size)]
|
||||
inner = list(StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain))
|
||||
for method in METHODS:
|
||||
ranking = []
|
||||
for columns in subsets:
|
||||
probs = np.full(len(train), np.nan)
|
||||
error = None
|
||||
try:
|
||||
for a, b in inner:
|
||||
probs[b] = _predict(train.iloc[a], ytrain[a], train.iloc[b], columns, method)
|
||||
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
|
||||
ranking.append((loss, len(columns), columns))
|
||||
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
|
||||
loss, error = None, type(exc).__name__
|
||||
attempted.append({'validation': plan, 'fold': fold, 'method': method,
|
||||
'variables': list(columns), 'inner_log_loss': loss, 'error': error})
|
||||
_, _, best = min(ranking)
|
||||
selected[method].append(list(best))
|
||||
try:
|
||||
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
|
||||
except (ValueError, np.linalg.LinAlgError, RuntimeError):
|
||||
pass
|
||||
outputs[plan] = {m: {'metrics': _metrics(y, predictions[m]), 'selected': selected[m],
|
||||
'unscored': int(np.isnan(predictions[m]).sum()),
|
||||
'stability': {name: sum(name in cols for cols in selected[m])
|
||||
for name in X.columns}}
|
||||
for m in METHODS}
|
||||
return {'development_only': True, 'candidate_limit': candidate_limit,
|
||||
'subset_limit': subset_limit, 'coverage_minimum': coverage,
|
||||
'max_subsets': max_subsets, 'maximum_fits': estimated_fits,
|
||||
'estimated_seconds_at_50ms_per_fit': estimated_fits * 0.05,
|
||||
'elapsed_seconds': time.monotonic() - started,
|
||||
'source': 'edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728',
|
||||
'attempts': attempted, 'validation': outputs}
|
||||
+179
-104
@@ -1,159 +1,234 @@
|
||||
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her index
|
||||
date, for development (models.cacu.development): NaN is missing, an absent value is never 0.
|
||||
"""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 (`visible`). Inputs: the gold timeline with its
|
||||
`evidence_date` and `source_available_at` (persistance.gold.evidence_timelines) and, for the
|
||||
form fields gold doesn't carry, the cytology forms (persistance.gold.cervical_forms)."""
|
||||
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 _worst, prepared
|
||||
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 may be (or follow) the outcome.
|
||||
# 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")
|
||||
EVIDENCE = "cacu_eligibility_evidence"
|
||||
FORM = catalog.studies()["cervical_cytology"].fields
|
||||
FINDINGS = tuple(n for n, f in FORM.items() if n.startswith("finding_") and f.type == "boolean")
|
||||
GENOTYPES = cacu.HPV_GENOTYPE_FIELDS
|
||||
EVIDENCE_TABLE = "cacu_eligibility_evidence"
|
||||
|
||||
|
||||
def codes(field: str) -> list[str]:
|
||||
return list(FORM[field].codes)
|
||||
def _codes(field: str) -> list[str]:
|
||||
return list(catalog.studies()["cervical_cytology"].fields[field].codes)
|
||||
|
||||
|
||||
def day(values: pd.Series) -> pd.Series:
|
||||
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:
|
||||
"""Her events available at her index: dated and clinically dated by it, made available
|
||||
by it when the source says when (else by its date; standalone evidence then left out, as
|
||||
the cohorts do), and procedures and a hysterectomy strictly before it. When the platform
|
||||
loaded it (`known_at`) isn't read."""
|
||||
"""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") # fmt: skip
|
||||
members[["person_id", "index_date"]], on="person_id"
|
||||
)
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
date, clinical, available = (day(found[c]) for c in ("date", "evidence_date",
|
||||
"source_available_at")) # fmt: skip
|
||||
date, clinical = _day(found["date"]), _day(found["evidence_date"])
|
||||
available = _day(found["source_available_at"])
|
||||
keep = (date <= index) & (clinical.isna() | (clinical <= index))
|
||||
keep &= (available.isna() & (found["source_table"] != EVIDENCE)) | (available <= index)
|
||||
before = (date < index) & (clinical.isna() | (clinical < index))
|
||||
done = found["type"].isin(PROCEDURES) | (found["value_code"] == "hysterectomy")
|
||||
return prepared(found[keep & (before | ~done)])
|
||||
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:
|
||||
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, of: list[str]) -> dict[str, pd.Series]:
|
||||
"""A column per code; a value that is none of them is missing, not 0 in all."""
|
||||
return {f"{prefix}__{c}": flag(values.isin(of), values == c) for c in of}
|
||||
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, else missing (no record doesn't show it never happened)."""
|
||||
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:
|
||||
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 results(seen: pd.DataFrame, members: pd.DataFrame, people: pd.Index) -> dict:
|
||||
"""Her age group, her latest cytology (its worst result that day) and HPV results."""
|
||||
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)
|
||||
ages = age_group(seen, keyed.assign(index_date=pd.to_datetime(keyed["index_date"])), cuts)
|
||||
out = one_hot(ages, "age", list(band(pd.Series([cuts[0] - 1, *cuts]), cuts)))
|
||||
found = seen[(seen["type"] == "bethesda") & seen["value_code"].isin(codes("result"))]
|
||||
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
|
||||
severity = {n: [n] for names in cacu.KPNC.values() for n in names if n in codes("result")}
|
||||
result = _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
|
||||
out |= one_hot(result, "bethesda", codes("result"))
|
||||
out |= {f"cytology_{name}": flag(result.notna(), result.isin(of))
|
||||
for name, of in cacu.PROCEDURE_CYTOLOGY.items()} # fmt: skip
|
||||
for kind in ("hpv", *cacu.HPV_GENOTYPE_FIELDS):
|
||||
value = latest(seen, kind, people)
|
||||
out[f"{kind}_positive"] = flag(value.isin(["positive", "negative"]), value == "positive")
|
||||
# from one sample's two genotypes: positive if either is, negative only if both are
|
||||
typed = seen[seen["type"].isin(cacu.HPV_GENOTYPE_FIELDS) & seen["value_code"].notna()]
|
||||
wide = typed.pivot_table(index=["person_id", "date", "source_id"], columns="type",
|
||||
values="value_code", aggfunc="first") # fmt: skip
|
||||
wide = wide.reindex(columns=cacu.HPV_GENOTYPE_FIELDS).sort_index().reset_index()
|
||||
last = wide.drop_duplicates("person_id", keep="last").set_index("person_id").reindex(people)
|
||||
positive = (last[cacu.HPV_GENOTYPE_FIELDS] == "positive").any(axis=1)
|
||||
negative = (last[cacu.HPV_GENOTYPE_FIELDS] == "negative").all(axis=1)
|
||||
out["hpv_16_or_18_positive"] = flag(positive | negative, positive)
|
||||
return out
|
||||
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 history(seen: pd.DataFrame, people: pd.Index) -> dict:
|
||||
"""What was done to her before, the worst biopsy, and her referral's grade (the last
|
||||
sample before her first colposcopy, as gold links it)."""
|
||||
of = {kind: seen[seen["type"] == kind] for kind in (*PROCEDURES, "cytology")}
|
||||
sampled = of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]]
|
||||
removed = seen[(seen["type"] == "gynecologic_condition")
|
||||
& (seen["value_code"] == "hysterectomy")] # fmt: skip
|
||||
out = {"prior_cytology_sample": present(sampled, people),
|
||||
**{f"prior_{n}": present(of[k], people) for n, k in (
|
||||
("biopsy_order", "biopsy_order"), ("biopsy_report", "biopsy"),
|
||||
("colposcopy", "colposcopy"), ("treatment", "treatment"),
|
||||
("diagnosis_note", "diagnosis"))},
|
||||
"history_cancer_icd10": present(of["history"], people),
|
||||
"history_hysterectomy": present(removed, people)} # fmt: skip
|
||||
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")):
|
||||
out[f"prior_biopsy_{name}"] = flag(worst.notna(), worst >= rank[grade])
|
||||
first = of["colposcopy"].groupby("person_id")["date"].min()
|
||||
graded = seen[seen["type"].isin(["bethesda", "glandular"]) & seen["value_code"].notna()]
|
||||
graded = graded[graded["date"] < graded["person_id"].map(first)]
|
||||
graded = graded[graded["date"] == graded.groupby("person_id")["date"].transform("max")]
|
||||
referral = _worst(graded.set_index("person_id")["value_code"], cacu.KPNC_3).reindex(people)
|
||||
out["referral_high_grade"] = flag(referral.notna(), referral == "High Grade")
|
||||
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "HSIL"), ("carcinoma", "carcinoma")):
|
||||
columns[f"prior_biopsy_{name}"] = _flag(worst.notna(), worst >= rank[grade])
|
||||
|
||||
persons = pd.Series(people, index=people)
|
||||
if events["type"].eq("colposcopy").any():
|
||||
grade = _referral_grade(events, persons, _REFERRAL | {"cytology": cacu.KPNC_3})
|
||||
else:
|
||||
grade = pd.Series(None, index=people, dtype=object)
|
||||
columns["referral_high_grade"] = _flag(grade.notna(), grade == "high")
|
||||
return columns
|
||||
|
||||
|
||||
def _forms(forms: pd.DataFrame | None, members: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
"""The cytology form's fields gold does not carry. Silver keeps no
|
||||
`source_available_at` for them: what the sample form says counts from the sample day,
|
||||
what the report says from the report day."""
|
||||
people = pd.Index(members["person_id"])
|
||||
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
|
||||
*FINDINGS] # fmt: skip
|
||||
if forms is None:
|
||||
forms = pd.DataFrame(columns=columns)
|
||||
found = forms[columns].merge(members[["person_id", "index_date"]], on="person_id")
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
|
||||
sampled = found[(_day(found["sample_date"]) <= index) & found["screening_history"].notna()]
|
||||
sampled = sampled.sort_values("sample_date", key=_day, kind="stable")
|
||||
history = sampled.groupby("person_id")["screening_history"].last().reindex(people)
|
||||
|
||||
reported = found[(_day(found["report_date"]) <= index) & (_day(found["sample_date"]) <= index)]
|
||||
reported = reported.assign(r=_day(reported["report_date"]), s=_day(reported["sample_date"]))
|
||||
# Her latest report, whole: a finding it does not state is unknown, whatever older
|
||||
# reports said.
|
||||
report = reported.sort_values(["r", "s"], kind="stable").drop_duplicates(
|
||||
"person_id", keep="last"
|
||||
)
|
||||
report = report.set_index("person_id").reindex(people)
|
||||
|
||||
out = _one_hot(history, "screening_history", _codes("screening_history"))
|
||||
adequacy = report["adequacy"]
|
||||
out["sample_unsatisfactory"] = _flag(
|
||||
adequacy.isin(_codes("adequacy")), adequacy == "unsatisfactory"
|
||||
)
|
||||
for name in FINDINGS:
|
||||
value = report[name]
|
||||
out[name] = _flag(value.notna(), value.eq(True))
|
||||
return out
|
||||
|
||||
|
||||
def forms(found: pd.DataFrame | None, members: pd.DataFrame, people: pd.Index) -> dict:
|
||||
"""The form's fields gold doesn't carry: what the sample form says counts from the
|
||||
sample day, the latest report (whole: what it doesn't state is unknown) from its day."""
|
||||
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
|
||||
*FINDINGS] # fmt: skip
|
||||
found = (pd.DataFrame(columns=columns) if found is None else found[columns]).merge(
|
||||
members[["person_id", "index_date"]], on="person_id") # fmt: skip
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
found = found.assign(s=day(found["sample_date"]), r=day(found["report_date"]))
|
||||
told = found[(found["s"] <= index) & found["screening_history"].notna()].sort_values("s")
|
||||
said = told.groupby("person_id")["screening_history"].last().reindex(people)
|
||||
report = found[(found["r"] <= index) & (found["s"] <= index)].sort_values(["r", "s"])
|
||||
report = report.drop_duplicates("person_id", keep="last").set_index("person_id")
|
||||
report = report.reindex(people)
|
||||
out = one_hot(said, "screening_history", codes("screening_history"))
|
||||
adequacy = report["adequacy"]
|
||||
out["sample_unsatisfactory"] = flag(adequacy.isin(codes("adequacy")),
|
||||
adequacy == "unsatisfactory") # fmt: skip
|
||||
return out | {n: flag(report[n].notna(), report[n].eq(True)) for n in FINDINGS}
|
||||
|
||||
|
||||
def encode(events: pd.DataFrame, cytology_forms: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
"""One row per member (`person_id`, `index_date`, one index each) with every encoder's
|
||||
column: 0.0, 1.0 or NaN."""
|
||||
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"]
|
||||
columns = {**results(seen, members, people), **history(seen, people),
|
||||
**forms(cytology_forms, members, people)} # fmt: skip
|
||||
for field in EXAM_FIELDS:
|
||||
columns |= one_hot(latest(exam, field, people), field, codes(field))
|
||||
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)
|
||||
|
||||
+27
-9
@@ -30,11 +30,26 @@ def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
|
||||
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
|
||||
|
||||
|
||||
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
|
||||
"""Why she was referred: the worst result in the year before her first colposcopy."""
|
||||
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
|
||||
before = (events["person_id"].map(first) - events["date"]).dt.days
|
||||
near = events[before.between(0, history["lookback_days"])]
|
||||
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
|
||||
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
|
||||
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
|
||||
positive = persons.isin(hpv["person_id"])
|
||||
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
|
||||
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
|
||||
& positive.to_numpy()), "low", None)) # fmt: skip
|
||||
return pd.Series(grade, index=persons.index, dtype=object)
|
||||
|
||||
|
||||
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
|
||||
(gold's, from the cytology linked to her colposcopy) when `history` asks for it. One
|
||||
without an HPV result is left out: not evaluated, never read as negative."""
|
||||
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"
|
||||
@@ -45,7 +60,8 @@ 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:
|
||||
grades = events[events["type"] == history["feature"]].groupby("person_id")["value_code"]
|
||||
# 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)
|
||||
|
||||
@@ -97,16 +113,18 @@ def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
|
||||
|
||||
|
||||
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
||||
"""Per patient never referred: her latest sample with both a cytology and an HPV result,
|
||||
before any hysterectomy her cytology forms record."""
|
||||
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
|
||||
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
|
||||
key = ["person_id", "source_table", "source_id"]
|
||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||
[*key, "date"]] # fmt: skip
|
||||
removed = events[(events["type"] == "gynecologic_condition")
|
||||
& (events["value_code"] == "hysterectomy")] # fmt: skip
|
||||
since = samples["person_id"].map(removed.groupby("person_id")["date"].min())
|
||||
samples = samples[since.isna() | (samples["date"] < since)]
|
||||
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))
|
||||
|
||||
+8
-6
@@ -1,5 +1,4 @@
|
||||
"""CaCu's training and scoring jobs (models.jobs) over its models and reports, with who
|
||||
each cohort lost (gold.cacu_eligibility, the scenario named after the cohort)."""
|
||||
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
@@ -9,10 +8,13 @@ from models.jobs import Jobs
|
||||
from persistance import gold
|
||||
|
||||
|
||||
def attrition(spec, as_of: date) -> dict:
|
||||
scenario = spec.cohort.removeprefix("cacu_cohort_")
|
||||
rows = gold.eligibility(scenario, as_of)
|
||||
return reports.attrition(spec.cohort, scenario, rows, gold.people("cacu_events", as_of), as_of)
|
||||
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)
|
||||
|
||||
+41
-30
@@ -140,16 +140,8 @@ class Fit:
|
||||
for t in years
|
||||
]) # fmt: skip
|
||||
|
||||
def estimable(self) -> tuple[np.ndarray, bool]:
|
||||
"""The estimated (not frozen) parameters; whether their covariance is positive definite."""
|
||||
free = np.isfinite(np.diag(self.covariance))
|
||||
block = self.covariance[np.ix_(free, free)]
|
||||
finite = bool(block.size and np.isfinite(block).all() and np.allclose(block, block.T))
|
||||
return free, finite and bool((np.linalg.eigvalsh(block) > 0).all())
|
||||
|
||||
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Risk and its delta-method variance (central-difference gradient); the variance is
|
||||
unknown (NaN) where the covariance isn't proper or a frozen parameter moves it."""
|
||||
"""Risk and its delta-method variance (central-difference gradient)."""
|
||||
gradient = np.empty((len(self.params), len(X), len(years)))
|
||||
for k, value in enumerate(self.params):
|
||||
step = 1e-5 * max(1.0, abs(value))
|
||||
@@ -157,14 +149,19 @@ class Fit:
|
||||
up[k] += step
|
||||
down[k] -= step
|
||||
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
||||
free = np.isfinite(np.diag(self.covariance))
|
||||
variance = np.full((len(X), len(years)), np.nan)
|
||||
free, proper = self.estimable()
|
||||
if proper:
|
||||
block = self.covariance[np.ix_(free, free)]
|
||||
found = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free])
|
||||
moved = np.any(np.abs(gradient[~free]) > 1e-10, axis=0)
|
||||
known = ~moved & np.isfinite(found) & (found >= 0)
|
||||
variance[known] = found[known]
|
||||
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
|
||||
|
||||
|
||||
@@ -265,7 +262,7 @@ class Mixture(BaseEstimator):
|
||||
continue
|
||||
members = X.iloc[index]
|
||||
placed = self._placed(members, self.seen_[key])
|
||||
if not placed.any(): # nobody it can place
|
||||
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])
|
||||
@@ -274,24 +271,38 @@ class Mixture(BaseEstimator):
|
||||
point, variance = self.fits_[key].risk_with_variance(
|
||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||
)
|
||||
relative = np.sqrt(variance) / np.maximum(point, 1e-300) # NaN: no interval
|
||||
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: its covariance's state and how many rows of `X` get no interval."""
|
||||
h, found = len(self.horizons_years), []
|
||||
"""Per stratum covariance properties and input rows without a complete interval."""
|
||||
h = len(self.horizons_years)
|
||||
result = []
|
||||
for key, index in self._groups(X):
|
||||
missing = np.isnan(self.predict(X.iloc[index])[:, h:]).any(axis=1)
|
||||
f = self.fits_.get(key)
|
||||
d, params = (np.diag(f.covariance), f.params) if f else (np.array([]), np.array([]))
|
||||
status = "unseen_stratum" if f is None else (
|
||||
"positive_definite" if f.estimable()[1] else "not_estimable") # fmt: skip
|
||||
negative = np.flatnonzero(np.isfinite(d) & (d < 0)).tolist()
|
||||
found.append({"stratum": [str(v) for v in key], "rows": len(index),
|
||||
"rows_without_interval": int(missing.sum()), "status": status,
|
||||
"frozen_parameters": np.flatnonzero(np.abs(params) >= FROZEN).tolist(),
|
||||
"negative_variances": negative}) # fmt: skip
|
||||
return {"strata": found, "horizons_years": list(self.horizons_years)}
|
||||
predictions = self.predict(X.iloc[index])
|
||||
missing = np.isnan(predictions[:, h:]).any(axis=1)
|
||||
entry = {"stratum": [str(v) for v in key], "rows": len(index),
|
||||
"rows_without_interval": int(missing.sum())}
|
||||
if f is None:
|
||||
entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[])
|
||||
else:
|
||||
diagonal = np.diag(f.covariance)
|
||||
frozen = np.flatnonzero(np.abs(f.params) >= FROZEN).tolist()
|
||||
negative = np.flatnonzero(np.isfinite(diagonal) & (diagonal < 0)).tolist()
|
||||
free = np.isfinite(diagonal)
|
||||
block = f.covariance[np.ix_(free, free)]
|
||||
try:
|
||||
positive = bool(block.size and np.isfinite(block).all()
|
||||
and np.allclose(block, block.T)
|
||||
and (np.linalg.eigvalsh(block) > 0).all())
|
||||
except np.linalg.LinAlgError:
|
||||
positive = False
|
||||
entry.update(status="positive_definite" if positive else "not_estimable",
|
||||
frozen_parameters=frozen, negative_variances=negative)
|
||||
result.append(entry)
|
||||
return {"strata": result, "horizons_years": list(self.horizons_years)}
|
||||
|
||||
+59
-35
@@ -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
|
||||
@@ -19,19 +21,65 @@ from models.cacu.pim import Mixture
|
||||
from models.cacu.specs import Logistic, Pim
|
||||
|
||||
GRID_STEP = 0.1 # years between points of a curve
|
||||
# Reasons a result still to arrive could lift, and the clinical stage of each (a candidate
|
||||
# may be excluded at several).
|
||||
AWAITING = {"unreported_biopsy", "no_index_result"}
|
||||
STAGES = {"eligibility": ("hysterectomy", "under_18", "no_birth_date", "died_by_index"),
|
||||
"history": ("prior_outcome", "outcome_by_index", "cancer_history", "prior_treatment",
|
||||
"outcome_before_index", "no_pretreatment_biopsy"),
|
||||
"index": ("no_referral", "referral_not_graded", "no_cotest", "no_index_result",
|
||||
"unreported_biopsy")} # fmt: skip
|
||||
STAGE = {reason: stage for stage, reasons in STAGES.items() for reason in reasons}
|
||||
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):
|
||||
@@ -81,7 +129,8 @@ def _label(feature: str, value) -> str:
|
||||
|
||||
|
||||
def _band(curve, variance) -> tuple[list, list]:
|
||||
relative = np.sqrt(variance) / np.maximum(curve, 1e-300) # NaN where it can't be had
|
||||
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
|
||||
|
||||
@@ -179,28 +228,3 @@ def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
||||
],
|
||||
}, # fmt: skip
|
||||
}
|
||||
|
||||
|
||||
def attrition(cohort: str, scenario: str, rows: pd.DataFrame, people: int, as_of) -> dict:
|
||||
"""Who a cohort lost and why by `as_of`. `rows`: its candidates' eligibility (one per
|
||||
candidate and reason). A candidate with several reasons is excluded once and counted in
|
||||
each reason; `pending`: the excluded whose every reason awaits a result."""
|
||||
key = ["person_id", "index_date", "index_sample_id"]
|
||||
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
|
||||
candidates = rows[key].drop_duplicates()
|
||||
excluded = rows[rows["criterion"].notna()]
|
||||
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
|
||||
stages = excluded.assign(stage=excluded["criterion"].map(STAGE).fillna("unknown"))
|
||||
return {
|
||||
"cohort": cohort, "scenario": scenario, "as_of": as_of.isoformat(), "people": people,
|
||||
"without_candidate": people - candidates["person_id"].nunique(),
|
||||
"candidates": len(candidates), "eligible": len(candidates) - len(reasons),
|
||||
"excluded": len(reasons), "pending": int(sum(r <= AWAITING for r in reasons)),
|
||||
"by_reason": {str(r): int(n) for r, n in
|
||||
excluded["criterion"].value_counts().sort_index().items()},
|
||||
"by_stage": {str(s): len(g[key].drop_duplicates())
|
||||
for s, g in stages.groupby("stage", sort=True)},
|
||||
"stage_by_reason": {str(r): STAGE.get(r, "unknown")
|
||||
for r in sorted(excluded["criterion"].unique())},
|
||||
"stage_counts_overlap": True, # one candidate may be out at several stages
|
||||
} # fmt: skip
|
||||
|
||||
+25
-26
@@ -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
|
||||
|
||||
@@ -15,17 +16,25 @@ from sklearn.preprocessing import OneHotEncoder
|
||||
from core import cacu
|
||||
from models.cacu import features as f
|
||||
from models.cacu.pim import Mixture
|
||||
from models.survival import Spec, age_group, band, inputs
|
||||
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",
|
||||
"input_values"] # fmt: skip
|
||||
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, read) -> pd.DataFrame:
|
||||
"""One row per patient and horizon, with what her estimate `read`; patients the model
|
||||
can't score are left out."""
|
||||
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)
|
||||
members, risks = members[scored], risks[scored]
|
||||
@@ -35,13 +44,15 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, read) -> pd.DataFr
|
||||
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
||||
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
||||
"probability": risks[:, :h].ravel(),
|
||||
"input_values": inputs(members, read, h),
|
||||
}) # fmt: skip
|
||||
if risks.shape[1] == 3 * h:
|
||||
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)
|
||||
@@ -64,7 +75,7 @@ class Pim:
|
||||
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
|
||||
|
||||
def _history(self) -> dict | None:
|
||||
return self.history
|
||||
return self.history and {**self.history, "cytology": self.cytology}
|
||||
|
||||
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
|
||||
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
|
||||
@@ -113,8 +124,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,
|
||||
self.features) # fmt: skip
|
||||
return _rows(members, mixture.predict(members[self.features]), self.horizons, self.features)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -181,14 +191,10 @@ def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataF
|
||||
return found.astype(object)
|
||||
|
||||
|
||||
_REFERRAL = {"feature": "referral_grade", "levels": ["low", "high"]} # graded in gold
|
||||
SURVIVAL_AGE_CUTS = (35, 45, 55)
|
||||
# The clinical scenarios survival's report draws, and her record with them.
|
||||
SURVIVAL_SCENARIOS = {
|
||||
**{f"Edad al diagnóstico · {g} años": (("age_group", "==", g),)
|
||||
for g in band(pd.Series([0, *SURVIVAL_AGE_CUTS]), list(SURVIVAL_AGE_CUTS))},
|
||||
**{f"Citología · {g}": (("cytology", "==", g),) for g in cacu.KPNC},
|
||||
"VPH positivo": (("hpv", "==", "positive"),), "VPH negativo": (("hpv", "==", "negative"),),
|
||||
_REFERRAL = {
|
||||
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
||||
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
|
||||
"high": ["High Grade"],
|
||||
} # fmt: skip
|
||||
|
||||
MODELS = {
|
||||
@@ -205,13 +211,6 @@ MODELS = {
|
||||
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
||||
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
|
||||
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
|
||||
# Hidden (core.models.HIDDEN): CIN3+ needs biopsies that tell CIN3 from CIN2.
|
||||
Pim("cin3_pim", "cacu_cohort_surveillance", cacu.CIN3_PLUS, cacu.KPNC,
|
||||
strata=("hpv_positive",), incidence_features=("cytology",),
|
||||
predict_at="last_screening_cytology"),
|
||||
Pim("cin3_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN3_PLUS,
|
||||
cacu.KPNC_3, strata=("referral_grade",),
|
||||
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
||||
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,
|
||||
|
||||
+47
-67
@@ -6,7 +6,7 @@ from datetime import date
|
||||
|
||||
import dagster as dg
|
||||
|
||||
from models import draft, graph
|
||||
from models import graph
|
||||
from models.jobs import EmptyCohort
|
||||
from persistance import backup as backups
|
||||
from persistance import config_log, silver
|
||||
@@ -33,28 +33,6 @@ def ingest():
|
||||
run_pipeline()
|
||||
|
||||
|
||||
class DraftRun(dg.Config):
|
||||
pipeline: str
|
||||
run: bool = True # False: drawn and saved only (a large site, read later)
|
||||
|
||||
|
||||
@dg.op
|
||||
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
|
||||
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
|
||||
run (unless `run` is off). Returns that version."""
|
||||
drafted = draft.draft(config.pipeline, log=context.log.info)
|
||||
version = config_log.save(config.pipeline, drafted)
|
||||
context.log.info(f"{config.pipeline} v{version}: {len(drafted.nodes)} nodes drafted")
|
||||
if config.run:
|
||||
graph.run(config.pipeline, drafted, log=context.log.info)
|
||||
return version
|
||||
|
||||
|
||||
@dg.job(name="draft", tags=WRITES)
|
||||
def draft_job():
|
||||
draft_pipeline()
|
||||
|
||||
|
||||
def _jobs(domain: str):
|
||||
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
||||
try:
|
||||
@@ -100,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") + "+"])
|
||||
@@ -112,6 +90,47 @@ 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
|
||||
|
||||
@@ -129,49 +148,10 @@ def analyze():
|
||||
analyze_studies()
|
||||
|
||||
|
||||
class Development(dg.Config):
|
||||
as_of: str
|
||||
max_fits: int = 100_000
|
||||
|
||||
|
||||
@dg.op
|
||||
def evaluate_cacu_development(context: dg.OpExecutionContext, config: Development) -> str:
|
||||
"""Opt-in research (models.cacu.development): which encoders predict CIN2+ at one year
|
||||
in the surveillance cohort; logged to MLflow, nothing registered, promoted or scored."""
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import development, encoders, features
|
||||
from persistance import gold, registry
|
||||
|
||||
as_of, cohort = date.fromisoformat(config.as_of), "cacu_cohort_surveillance"
|
||||
events = gold.evidence_timelines("cacu_events", cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"nobody in {cohort}")
|
||||
outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0,
|
||||
pd.Timestamp(as_of)) # fmt: skip
|
||||
rows = encoders.encode(events, gold.cervical_forms(cohort)).merge(outcome, on="person_id")
|
||||
rows = rows[rows["known"]].reset_index(drop=True)
|
||||
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
|
||||
report = development.evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
|
||||
report |= {"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(f"development evaluation logged as {run.info.run_id}")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
@dg.job
|
||||
def cacu_development_evaluation():
|
||||
evaluate_cacu_development()
|
||||
|
||||
|
||||
@dg.op
|
||||
def build_gold(context: dg.OpExecutionContext) -> None:
|
||||
"""Silver and all that derives from it, with the deployed code: an ingest's end without
|
||||
ingesting (after deploying a version that changes the tables)."""
|
||||
"""Silver and everything derived from it, with the deployed code: what an ingest ends
|
||||
with, without ingesting (after deploying a version that changes the tables)."""
|
||||
silver.build(["silver+"])
|
||||
context.log.info("silver and gold rebuilt")
|
||||
|
||||
@@ -205,5 +185,5 @@ nightly = (
|
||||
else []
|
||||
)
|
||||
|
||||
JOBS = [ingest, draft_job, train, score, analyze, rebuild, backup, cacu_development_evaluation]
|
||||
defs = dg.Definitions(jobs=JOBS, schedules=nightly)
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup,
|
||||
cacu_development_evaluation], schedules=nightly)
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
"""Automático: a whole pipeline drafted from the sources an operator connected. Each source
|
||||
is loaded and its files read as a run would; documents are drafted by layout
|
||||
(models.draft.documents), tables by column (models.draft.tables); one link node gathers
|
||||
every record's identity and one target per study saves it. The model only fills typed
|
||||
slots that code checks; who is the same patient stays with the reviewers."""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
|
||||
from core.pipeline import ENTITY_TITLES, Link, Pipeline, Read, Target
|
||||
from models import graph
|
||||
from models.draft import documents, fields, tables
|
||||
from persistance import config_log, files, nodes
|
||||
|
||||
FILE_KEY = re.compile(r"^[0-9a-f]{64}$") # a kept file's key (persistance.files)
|
||||
SCANNED = 50 # rows looked at to tell a column of files
|
||||
|
||||
|
||||
class Draft:
|
||||
"""The nodes drafted so far, their ids unique, and the site's codes found."""
|
||||
|
||||
def __init__(self, pipeline_id: str, sources: list):
|
||||
self.pipeline_id, self.nodes = pipeline_id, list(sources)
|
||||
self.identity: list[str] = []
|
||||
self.studies: dict[str, list[str]] = {}
|
||||
self.codes = fields.Codes(pipeline_id)
|
||||
|
||||
def id(self, text: str) -> str:
|
||||
plain = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
|
||||
base = re.sub(r"[^a-z0-9]+", "_", plain).strip("_")[:34] or "nodo"
|
||||
base = base if base[0].isalpha() else f"n_{base}"[:34]
|
||||
taken, found, n = {n.id for n in self.nodes}, base, 1
|
||||
while found in taken:
|
||||
n += 1
|
||||
found = f"{base}_{n}"
|
||||
return found
|
||||
|
||||
def add(self, node):
|
||||
self.nodes.append(node)
|
||||
return node
|
||||
|
||||
def finish(self) -> Pipeline:
|
||||
"""The site's codes saved as its ConceptMap, one link node, a target per study."""
|
||||
if not self.identity:
|
||||
raise ValueError("nothing read says whom a record is about: nothing to link")
|
||||
if (found := self.codes.concept_map()) is not None:
|
||||
config_log.save(self.codes.map_id, found, "concept_maps")
|
||||
link = self.add(Link(id=self.id("personas"), label="Quién es quién",
|
||||
inputs=self.identity)) # fmt: skip
|
||||
for entity, inputs in self.studies.items():
|
||||
self.add(Target(id=self.id(f"guardar_{entity}"), label=ENTITY_TITLES[entity],
|
||||
inputs=[*inputs, link.id], entity=entity)) # fmt: skip
|
||||
return Pipeline(nodes=self.nodes)
|
||||
|
||||
|
||||
def file_columns(rows: list[dict]) -> list[str]:
|
||||
"""Columns whose values are kept files (a source keeps each file once and passes its key)."""
|
||||
found = []
|
||||
for column in sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")}):
|
||||
values = {r.get(column) for r in rows[:SCANNED]} - {None}
|
||||
if values and all(isinstance(v, str) and FILE_KEY.match(v) for v in values):
|
||||
if files.known(values):
|
||||
found.append(column)
|
||||
return found
|
||||
|
||||
|
||||
def draft(pipeline_id: str, log: Callable[[str], None] = print) -> Pipeline:
|
||||
"""The pipeline Automático draws from a saved pipeline made of sources only."""
|
||||
_, saved = config_log.get(pipeline_id)
|
||||
sources = [n for n in saved.nodes if n.kind == "source"]
|
||||
if not sources or len(sources) != len(saved.nodes):
|
||||
raise ValueError("Automático starts from a pipeline that holds only its sources")
|
||||
d = Draft(pipeline_id, sources)
|
||||
for source in sources:
|
||||
nodes.run_source(pipeline_id, source)
|
||||
rows = list(nodes.rows(pipeline_id, source.id))
|
||||
log(f"{source.id}: {len(rows)} rows")
|
||||
found = file_columns(rows)
|
||||
for column in found:
|
||||
read = d.add(Read(id=d.id(f"texto_{source.id}"), label="Texto de cada documento",
|
||||
inputs=[source.id], column=column)) # fmt: skip
|
||||
graph.run_read(pipeline_id, read)
|
||||
documents.draft(d, read, list(nodes.rows(pipeline_id, read.id)), log)
|
||||
if not found:
|
||||
tables.draft(d, source, rows, log)
|
||||
return d.finish()
|
||||
@@ -1,214 +0,0 @@
|
||||
"""Documents (a column of files, read to text): grouped by layout, each layout named by the
|
||||
model with the studies it reports and the phrases that mark it and each of them (a route,
|
||||
and a route under it for a study only some of its documents report: the organ a
|
||||
pathology report is about, a note that records a death), and read for each study (joined
|
||||
to the documents it answers, if it needs them: joins) and for whom it is about (extract
|
||||
nodes, with patterns for when no model answers). What no layout claims goes to the
|
||||
unrecognised route, for a reviewer."""
|
||||
|
||||
import dataclasses
|
||||
import re
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
|
||||
from core.drafting import LAYOUT, layout_schema, studies_text
|
||||
from core.pipeline import ENTITY_TITLES, Condition, Extract, Join, Read, Route, ground
|
||||
from models import graph
|
||||
from models.draft import fields, joins
|
||||
from models.draft.joins import Kind
|
||||
from models.draft.layouts import (
|
||||
LOOSE,
|
||||
condition,
|
||||
diverse,
|
||||
kinds_of,
|
||||
layouts,
|
||||
marks,
|
||||
phrase,
|
||||
printed_line,
|
||||
shared_words,
|
||||
spread,
|
||||
)
|
||||
from persistance import llm
|
||||
|
||||
SAMPLE = 2000 # documents grouped by layout at most (grouping compares every pair)
|
||||
SHOWN = 8 # documents of a layout the model is shown to name its studies
|
||||
PER_STUDY = 3 # documents of a study the model reads for where each field is written
|
||||
CHARS = 3000 # of each document shown to name a layout (its title and labels come first)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Layout:
|
||||
label: str
|
||||
marker: str
|
||||
members: list[dict] = dataclasses.field(default_factory=list)
|
||||
everyone: list[dict] = dataclasses.field(default_factory=list)
|
||||
route: Route | None = None
|
||||
|
||||
|
||||
def draft(d, read: Read, rows: list[dict], log) -> None:
|
||||
"""Routes, extracts (and joins) and the unrecognised route for one read node's
|
||||
documents."""
|
||||
documents = sorted((r for r in rows if r.get("text")), key=lambda r: r["_record"])
|
||||
sample = spread(documents, SAMPLE)
|
||||
groups: dict[int, list[dict]] = {}
|
||||
for row, group in zip(sample, layouts([r["text"] for r in sample]), strict=True):
|
||||
if group >= 0:
|
||||
groups.setdefault(group, []).append(row)
|
||||
answers = []
|
||||
for members in groups.values():
|
||||
shown = diverse(members, SHOWN)
|
||||
text = "\n\n".join(f"=== Documento {i} ===\n{r['text'][:CHARS]}"
|
||||
for i, r in enumerate(shown, 1)) # fmt: skip
|
||||
try:
|
||||
answer = llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema(len(shown)))
|
||||
except llm.Unreadable as e: # left undrawn: a person draws its route
|
||||
log(f"layout of {len(members)} left out, the model's answer: {e}")
|
||||
continue
|
||||
answers.append((answer, members, shown))
|
||||
found, kinds = {}, {}
|
||||
for answer, members, shown in answers:
|
||||
entities = {s["entity"] for s in answer["studies"]}
|
||||
others = [r for a, m, _ in answers if not entities & {s["entity"] for s in a["studies"]}
|
||||
for r in m] # fmt: skip
|
||||
marker = " ".join(answer["marker"].split())
|
||||
marker = phrase(marker, members, others) or printed_line(
|
||||
members, [r for _, m, _ in answers if m is not members for r in m]
|
||||
)
|
||||
log(f"layout of {len(members)}: «{marker}» {sorted(entities) or 'no study'}")
|
||||
if marker is None or not entities:
|
||||
continue
|
||||
layout = found.setdefault(marker.casefold(), Layout(answer["label"], marker))
|
||||
layout.members.extend(members)
|
||||
for one in answer["studies"]:
|
||||
claimed = {i for o in answer["studies"] if o is not one for i in o["documents"]}
|
||||
if (sub := apart(one, shown, claimed, log, members)) is False:
|
||||
continue
|
||||
kind = kinds.setdefault((marker.casefold(), one["entity"], (sub or "").casefold()),
|
||||
Kind(one["entity"], one["label"], sub or "", [],
|
||||
layout=layout)) # fmt: skip
|
||||
kind.members.extend(r for r in members if not sub or marks(sub, r["text"]))
|
||||
routes(d, read, documents, list(found.values()), list(kinds.values()))
|
||||
for kind in kinds.values():
|
||||
d.studies.setdefault(kind.entity, []).append(study(d, kind, list(kinds.values()), log))
|
||||
for layout in found.values():
|
||||
shown = [(r["text"], r) for r in diverse(layout.members, PER_STUDY)]
|
||||
texts = [r["text"] for r in layout.everyone]
|
||||
d.identity.append(extract(d, layout.route, layout.route.id, "identity", "text",
|
||||
reading("identity", shown), texts)) # fmt: skip
|
||||
d.add(Route(id=d.id("no_reconocidos"), label="Documentos no reconocidos",
|
||||
inputs=[read.id], otherwise=True)) # fmt: skip
|
||||
|
||||
|
||||
def apart(study: dict, shown: list[dict], claimed: set[int], log, layout=()) -> str | None | bool:
|
||||
"""What marks the documents of a layout that report `study`: None when all of them do,
|
||||
or when those the model left out report no other study (`claimed`: those another does;
|
||||
the model is not asked to be exhaustive), a phrase found in each of those it named and
|
||||
in none of the others, False when no such phrase is found (the study is left out)."""
|
||||
named = {i for i in study["documents"] if 1 <= i <= len(shown)}
|
||||
if not named:
|
||||
return False
|
||||
if not (set(range(1, len(shown) + 1)) - named) & claimed:
|
||||
return None
|
||||
mine = [r for i, r in enumerate(shown, 1) if i in named]
|
||||
rest = [r for i, r in enumerate(shown, 1) if i not in named]
|
||||
if found := phrase(" ".join((study["marker"] or "").split()), mine, rest, share=1.0):
|
||||
return found
|
||||
if found := shared_words(mine, rest, study["label"], layout, only=True):
|
||||
return found # the study's own name: what a person would route by
|
||||
telling = lambda line: (-kinds_of(line, shown), len(line)) # noqa: E731
|
||||
line = printed_line(mine, rest, share=1.0, rank=telling)
|
||||
if line and kinds_of(line, shown) < len(shown): # a value others share: no one's name
|
||||
return line
|
||||
if found := shared_words(mine, rest, study["label"], layout):
|
||||
return found
|
||||
log(f"{study['label']}: nothing marks its documents apart from the layout's others")
|
||||
return False
|
||||
|
||||
|
||||
def routes(d, read: Read, documents, found: list[Layout], kinds: list[Kind]) -> None:
|
||||
"""A route per layout, and under it one per study only some of its documents report;
|
||||
two named alike are told apart by what marks them."""
|
||||
routed = [*found, *(k for k in kinds if k.marker)]
|
||||
named, seen = Counter(x.label.casefold() for x in routed), Counter()
|
||||
for x in routed:
|
||||
if named[x.label.casefold()] > 1:
|
||||
seen[x.label.casefold()] += 1
|
||||
said = x.marker[:40] + ("…" if len(x.marker) > 40 else "")
|
||||
x.label += (
|
||||
f" {seen[x.label.casefold()]}" if x.marker.startswith(LOOSE) else f" · {said}"
|
||||
)
|
||||
for layout in found:
|
||||
layout.route = d.add(Route(id=d.id(layout.label), label=layout.label, inputs=[read.id],
|
||||
when=[Condition(**condition(layout.marker))])) # fmt: skip
|
||||
layout.everyone = [r for r in documents if marks(layout.marker, r["text"])]
|
||||
for kind in kinds:
|
||||
kind.route, kind.everyone = kind.layout.route, kind.layout.everyone
|
||||
if kind.marker:
|
||||
kind.route = d.add(Route(id=d.id(kind.label), label=kind.label,
|
||||
inputs=[kind.layout.route.id],
|
||||
when=[Condition(**condition(kind.marker))])) # fmt: skip
|
||||
kind.everyone = [r for r in kind.everyone if marks(kind.marker, r["text"])]
|
||||
|
||||
|
||||
def study(d, kind: Kind, kinds: list[Kind], log) -> str:
|
||||
"""The extract node of a kind's study; on a join with the kind that pairs with it when,
|
||||
reading both, the model takes a field the study requires from the other document (an
|
||||
outsourced report's sample date is the order's, not the report's own date)."""
|
||||
shown = diverse(kind.members, PER_STUDY)
|
||||
read = reading(kind.entity, [(r["text"], r) for r in shown])
|
||||
texts = [r["text"] for r in kind.everyone]
|
||||
if found := joins.partner(kind, kinds):
|
||||
other, column = found
|
||||
node = Join(
|
||||
id=d.id(f"{kind.route.id}_con_{other.route.id}"),
|
||||
label=f"{kind.label} con {other.label}",
|
||||
inputs=[kind.route.id, other.route.id],
|
||||
on=[(column, column)],
|
||||
how="left",
|
||||
)
|
||||
paired = [(t, r) for t, r in joins.joined(node, kind.members, other)
|
||||
if joins.apart_from(r, other)] # fmt: skip
|
||||
pairs = spread(paired, PER_STUDY) or joins.joined(node, shown, other)
|
||||
again = reading(kind.entity, pairs)
|
||||
if taken := joins.taken(kind.entity, again, [r for _, r in pairs], other):
|
||||
log(f"{kind.label}: read with {other.label} (same {column}): {taken} is in it")
|
||||
d.add(node)
|
||||
texts = [t for t, _ in joins.joined(node, kind.everyone, other)]
|
||||
return extract(d, node, kind.route.id, kind.entity, joins.text_columns(other),
|
||||
again, texts) # fmt: skip
|
||||
log(f"{kind.label}: pairs with {other.label} (same {column}), needs nothing of it")
|
||||
return extract(d, kind.route, kind.route.id, kind.entity, "text", read, texts)
|
||||
|
||||
|
||||
def reading(entity: str, shown: list[tuple[str, dict]]) -> list[tuple[str, dict, dict]]:
|
||||
"""What the model reads of `entity` in each text, only what the text says: (text,
|
||||
values, the text each was read from)."""
|
||||
out = []
|
||||
for text, row in shown:
|
||||
try:
|
||||
answered = ground(graph.answer(entity, text, "", graph.images(row)), text)
|
||||
except llm.Unreadable: # nothing read from this one
|
||||
answered = []
|
||||
values, quotes, _ = answered[0] if answered else ({}, {}, [])
|
||||
kept = {f: v for f, v in values.items() if v is not None}
|
||||
out.append((text, kept, {f: quotes[f] for f in kept}))
|
||||
return out
|
||||
|
||||
|
||||
def extract(d, source, name: str, entity: str, column, read, texts: list[str]) -> str:
|
||||
"""An extract node of `entity` on `source`'s rows: the model's reading of a few of them
|
||||
gives each field's pattern (and the site's codes), kept if it checks out."""
|
||||
patterns, formats = fields.rules(entity, [(t, v) for t, v, _ in read], d.codes)
|
||||
for field, pattern in patterns.items():
|
||||
if fields.coded(entity, field):
|
||||
raws = set()
|
||||
for text in texts:
|
||||
if found := re.search(pattern, text, re.IGNORECASE):
|
||||
raws.add(" ".join(found.group(1).split()))
|
||||
d.codes.ask(entity, field, raws)
|
||||
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
||||
node = Extract(id=d.id(f"{entity}_{name}"), label=f"{title} ({source.label})",
|
||||
inputs=[source.id], column=column, entity=entity, method="auto",
|
||||
patterns=patterns, formats=formats,
|
||||
concept_map=d.codes.for_node(entity, patterns)) # fmt: skip
|
||||
return d.add(node).id
|
||||
@@ -1,185 +0,0 @@
|
||||
"""Where each field is written, checked against the documents: the model proposes a pattern
|
||||
per field from a few documents and the values it read there; a pattern is kept only when
|
||||
it captures those very values (through its date format and the site's codes). And the
|
||||
site's codes in platform terms, gathered into one ConceptMap."""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
|
||||
from core import catalog, concept_map
|
||||
from core.drafting import CODES, PATTERNS, codes_schema, is_date, patterns_schema
|
||||
from core.pipeline import Extract, convert
|
||||
from core.schema import ENTITIES
|
||||
from persistance import llm
|
||||
|
||||
DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d", "%m/%d/%Y")
|
||||
MANY_CODES = 200 # distinct values of a coded column asked about at most
|
||||
|
||||
|
||||
def _plain(value) -> str:
|
||||
return " ".join(str(value).split()).casefold()
|
||||
|
||||
|
||||
def _same(got, want) -> bool:
|
||||
"""A captured value, converted, is the value the model read (dates, numbers, text)."""
|
||||
got = got.isoformat() if hasattr(got, "isoformat") else got
|
||||
try:
|
||||
return float(got) == float(want)
|
||||
except (TypeError, ValueError):
|
||||
return _plain(got) == _plain(want)
|
||||
|
||||
|
||||
def _code(value) -> str:
|
||||
"""A model's value as a code: booleans as the platform's yes/no codes."""
|
||||
return str(value).lower() if isinstance(value, bool) else str(value)
|
||||
|
||||
|
||||
def target(entity: str, field: str) -> tuple[str | None, set[str] | None]:
|
||||
"""The system a field of this study takes codes from (None: not coded) and its allowed
|
||||
codes (None: any of the system's)."""
|
||||
if entity == "identity":
|
||||
return (concept_map.GENDER, {"female", "male"}) if field == "sex" else (None, set())
|
||||
found = catalog.studies()[entity].fields[field]
|
||||
if found.type == "boolean":
|
||||
return concept_map.BOOLEAN, {"true", "false"}
|
||||
if found.type == "code":
|
||||
return catalog.systems()[found.system].url, set(found.codes) or None
|
||||
return None, set()
|
||||
|
||||
|
||||
def coded(entity: str, field: str) -> bool:
|
||||
return target(entity, field)[0] is not None
|
||||
|
||||
|
||||
class Codes:
|
||||
"""The site's codes found so far: (study, field) -> site value (case ignored) ->
|
||||
platform code."""
|
||||
|
||||
def __init__(self, map_id: str):
|
||||
self.map_id, self.found = map_id, {}
|
||||
|
||||
def known(self, entity: str, field: str, raw: str) -> bool:
|
||||
allowed = target(entity, field)[1]
|
||||
mapped = self.found.get((entity, field), {})
|
||||
return raw.casefold() in mapped or (allowed is not None and raw in allowed)
|
||||
|
||||
def add(self, entity: str, field: str, raw: str, code: str) -> None:
|
||||
if not raw.strip():
|
||||
return # nothing written is no code
|
||||
self.found.setdefault((entity, field), {})[raw.casefold()] = code
|
||||
|
||||
def table(self) -> dict[tuple[str, str], dict[str, str]]:
|
||||
return self.found
|
||||
|
||||
def ask(self, entity: str, field: str, raws: set[str]) -> None:
|
||||
"""What the platform code is of each value the site writes for `field` that isn't
|
||||
one already."""
|
||||
new = sorted(r for r in raws if r and not self.known(entity, field, r))[:MANY_CODES]
|
||||
if not new:
|
||||
return
|
||||
allowed = target(entity, field)[1]
|
||||
title = ENTITIES[entity].model_fields[field].title or field
|
||||
system = CODES.format(title=title, codes=", ".join(sorted(allowed)) if allowed else "any")
|
||||
try:
|
||||
answer = llm.ask(system, "\n".join(new), codes_schema(new, sorted(allowed or ())))
|
||||
except llm.Unreadable: # left uncoded: the run holds them for a reviewer
|
||||
return
|
||||
for item in answer["codes"]:
|
||||
if item["code"] is not None and (allowed is None or item["code"] in allowed):
|
||||
self.add(entity, field, item["raw"], item["code"])
|
||||
|
||||
def for_node(self, entity: str, fields) -> str | None:
|
||||
return self.map_id if any((entity, f) in self.found for f in fields) else None
|
||||
|
||||
def concept_map(self) -> ConceptMap | None:
|
||||
"""One group per platform system the codes go to; None when there are none."""
|
||||
groups: dict[str, list] = {}
|
||||
for (entity, field), codes in self.found.items():
|
||||
system = target(entity, field)[0]
|
||||
for raw, code in sorted(codes.items()):
|
||||
element = {"code": raw, "target": [{"code": code, "equivalence": "equivalent"}]}
|
||||
if element not in groups.setdefault(system, []):
|
||||
groups[system].append(element)
|
||||
if not groups:
|
||||
return None
|
||||
found = ConceptMap.model_validate({
|
||||
"resourceType": "ConceptMap", "status": "active", "id": self.map_id.replace("_", "-"),
|
||||
"title": f"{self.map_id}: los códigos del sitio, como los leyó Automático",
|
||||
"group": [{"source": f"urn:isssteleon:site:{self.map_id}", "target": t, "element": e}
|
||||
for t, e in groups.items()],
|
||||
}) # fmt: skip
|
||||
if problems := concept_map.problems(found):
|
||||
raise ValueError(f"drafted codes refused: {problems}")
|
||||
return found
|
||||
|
||||
|
||||
def rules(entity: str, read: list[tuple[str, dict]], codes: Codes) -> tuple[dict, dict]:
|
||||
"""Patterns and date formats for the fields the model read in these documents (text,
|
||||
values): one per field, kept only if it captures every value read."""
|
||||
fields = sorted({f for _, values in read for f in values})
|
||||
if not fields:
|
||||
return {}, {}
|
||||
shown = "\n\n---\n\n".join(
|
||||
f"{text}\n\nVALUES: " + "; ".join(f"{f} = {v}" for f, v in values.items())
|
||||
for text, values in read
|
||||
)
|
||||
try:
|
||||
proposed = llm.ask(PATTERNS, shown, patterns_schema(fields))
|
||||
except llm.Unreadable: # no patterns: these fields are read by the model alone
|
||||
return {}, {}
|
||||
patterns, formats = {}, {}
|
||||
for field in fields:
|
||||
rule = proposed.get(field) or {}
|
||||
fmt = rule.get("format") if is_date(entity, field) else None
|
||||
if checks(entity, field, rule.get("pattern") or "", fmt, read, codes):
|
||||
patterns[field] = rule["pattern"]
|
||||
if fmt:
|
||||
formats[field] = fmt
|
||||
return patterns, formats
|
||||
|
||||
|
||||
def checks(entity, field, pattern, fmt, read, codes: Codes) -> bool:
|
||||
try:
|
||||
if re.compile(pattern, re.IGNORECASE).groups != 1:
|
||||
return False
|
||||
except re.error:
|
||||
return False
|
||||
probe = Extract(id="probe", column="text", entity=entity, formats={field: fmt} if fmt else {})
|
||||
pairs = {}
|
||||
for text, values in read:
|
||||
if field not in values:
|
||||
continue
|
||||
found = re.search(pattern, text, re.IGNORECASE)
|
||||
if not found or not (found.group(1) or "").strip():
|
||||
return False # where the model read a value, the pattern takes text
|
||||
raw, want = " ".join(found.group(1).split()), values[field]
|
||||
if coded(entity, field):
|
||||
pairs.setdefault(raw.casefold(), set()).add(_code(want))
|
||||
elif not _same(convert(probe, field, raw, {}), want):
|
||||
return False
|
||||
if any(len(v) > 1 for v in pairs.values()):
|
||||
return False # one written value, two meanings: the pattern takes the wrong text
|
||||
for raw, (code,) in pairs.items():
|
||||
if raw != code.casefold():
|
||||
codes.add(entity, field, raw, code)
|
||||
return True
|
||||
|
||||
|
||||
def date_format(values: list) -> str | None:
|
||||
"""The strptime format every written date of a column parses with (None: they are
|
||||
dates already, or none fits)."""
|
||||
written = [v.strip() for v in values if isinstance(v, str) and v.strip()]
|
||||
for fmt in DATE_FORMATS:
|
||||
if written and all(_parses(v, fmt) for v in written):
|
||||
return fmt
|
||||
return None
|
||||
|
||||
|
||||
def _parses(value: str, fmt: str) -> bool:
|
||||
try:
|
||||
datetime.strptime(value, fmt)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
@@ -1,99 +0,0 @@
|
||||
"""A kind of document that leaves a date its study requires to another (an outsourced
|
||||
lab's report leaves the sample's date to the order it answers) is read together with
|
||||
it: the kind of the same source a column both carry pairs each of its documents with, one
|
||||
to one. The pairing is kept only if the model, reading both, takes such a field from the
|
||||
other document."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from core.pipeline import Join, Route, grounded, join
|
||||
from core.schema import ENTITIES
|
||||
from models.graph import FILE, READ_COLUMNS
|
||||
|
||||
PAIRED = 0.5 # share of a kind's documents that must find exactly one partner
|
||||
|
||||
|
||||
@dataclass
|
||||
class Kind:
|
||||
"""Documents of a layout that report one study (all of the layout's, or those `marker`
|
||||
sets apart): their route, those sampled, all of them."""
|
||||
|
||||
entity: str
|
||||
label: str
|
||||
marker: str
|
||||
members: list[dict] # those sampled
|
||||
everyone: list[dict] = field(default_factory=list)
|
||||
route: Route | None = None
|
||||
layout: object = None # the layout these documents are of (documents.Layout)
|
||||
|
||||
|
||||
def required(entity: str) -> set[str]:
|
||||
return {f for f, info in ENTITIES[entity].model_fields.items() if info.is_required()}
|
||||
|
||||
|
||||
def _keys(row: dict) -> dict:
|
||||
"""The columns of a row that may pair it: the source's own, never its text or file."""
|
||||
return {
|
||||
c: v
|
||||
for c, v in row.items()
|
||||
if not c.startswith("_") and c not in READ_COLUMNS and c != FILE
|
||||
and isinstance(v, str | int) and v != ""
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def partner(kind: Kind, kinds: list[Kind]) -> tuple[Kind, str] | None:
|
||||
"""The other kind and the column that pair most of this kind's documents with exactly
|
||||
one document each (never with themselves); None if none pairs half."""
|
||||
best = None
|
||||
for other in kinds:
|
||||
if other is kind or not kind.everyone:
|
||||
continue
|
||||
index: dict[tuple[str, object], set] = {}
|
||||
for row in other.everyone:
|
||||
for c, v in _keys(row).items():
|
||||
index.setdefault((c, v), set()).add(row["_record"])
|
||||
paired: dict[str, int] = {}
|
||||
for row in kind.everyone:
|
||||
for c, v in _keys(row).items():
|
||||
if len(index.get((c, v), set()) - {row["_record"]}) == 1:
|
||||
paired[c] = paired.get(c, 0) + 1
|
||||
for c, n in paired.items():
|
||||
share = n / len(kind.everyone)
|
||||
if share >= PAIRED and (best is None or share > best[0]):
|
||||
best = (share, other, c)
|
||||
return (best[1], best[2]) if best else None
|
||||
|
||||
|
||||
def joined(node: Join, rows: list[dict], other: Kind) -> list[tuple[str, dict]]:
|
||||
"""Each row with its partner's text before its own, as the extract node will read it."""
|
||||
columns = text_columns(other)
|
||||
return [("\n".join(str(r[c]) for c in columns if r.get(c)), r)
|
||||
for r in join(node, rows, other.everyone, other.route.id)] # fmt: skip
|
||||
|
||||
|
||||
def apart_from(row: dict, other: Kind) -> bool:
|
||||
"""A joined row whose partner is another document (a file holding both the order and
|
||||
the report pairs with itself: it needs no join)."""
|
||||
return row.get(f"_record__{other.route.id}") not in (None, row["_record"])
|
||||
|
||||
|
||||
def taken(entity: str, read, rows: list[dict], other: Kind) -> set[str]:
|
||||
"""Fields the study requires that the model, reading a document with its partner, took
|
||||
from the partner's text (not its own) in most of the documents that have one."""
|
||||
theirs_column = text_columns(other)[0]
|
||||
partnered = [(quotes, row) for (_, _, quotes), row in zip(read, rows, strict=True)
|
||||
if row.get(theirs_column) and apart_from(row, other)] # fmt: skip
|
||||
found = set()
|
||||
for name in required(entity):
|
||||
theirs = sum(
|
||||
name in quotes and grounded(quotes[name], row[theirs_column])
|
||||
and not grounded(quotes[name], row["text"])
|
||||
for quotes, row in partnered
|
||||
) # fmt: skip
|
||||
if partnered and theirs * 2 > len(partnered):
|
||||
found.add(name)
|
||||
return found
|
||||
|
||||
|
||||
def text_columns(other: Kind) -> list[str]:
|
||||
return [f"text__{other.route.id}", "text"]
|
||||
@@ -1,161 +0,0 @@
|
||||
"""Documents told apart by their layout (the words a form prints), the documents of a
|
||||
layout the model is shown (as unlike each other as they come, so a rare kind of note is
|
||||
among them), and the phrases that mark documents (what a route tests)."""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from collections import Counter
|
||||
|
||||
import numpy as np
|
||||
from sklearn.cluster import AgglomerativeClustering
|
||||
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
|
||||
|
||||
DISTANCE = 0.5 # cosine distance under which two documents share a layout
|
||||
COVERED = 0.9 # share of a layout's documents its marker must be found in
|
||||
WORDS = r"(?u)\b[^\W\d_]{3,}\b" # words, never numbers: a layout, not its values
|
||||
LINE = re.compile(r"^(?=.*[^\W\d_]{4})[^\d]{8,}$") # a printed label: words, no values
|
||||
LOOSE = "(?i)" # a marker written as a pattern (op `matches`), not a phrase (`contains`)
|
||||
ACCENTED = {"a": "aá", "e": "eé", "i": "ií", "o": "oó", "u": "uúü", "n": "nñ"}
|
||||
GAP = r"\W+(?:[^\W_]+\W+){0,2}?" # up to two words the model left out (DERECHA)
|
||||
|
||||
|
||||
def layouts(texts: list[str]) -> list[int]:
|
||||
"""A layout number per document: documents that print mostly the same words (a form's
|
||||
labels) share one. Words seen in a single document (a name) don't count."""
|
||||
if len(texts) < 2:
|
||||
return [0] * len(texts)
|
||||
try:
|
||||
words = CountVectorizer(token_pattern=WORDS, binary=True, min_df=2).fit_transform(texts)
|
||||
except ValueError: # no word in two documents: nothing to tell them apart by
|
||||
return [0] * len(texts)
|
||||
found = [-1] * len(texts)
|
||||
worded = [i for i in range(len(texts)) if words[i].nnz]
|
||||
if len(worded) < 2:
|
||||
return [0 if i in worded else -1 for i in range(len(texts))]
|
||||
groups = AgglomerativeClustering(
|
||||
n_clusters=None, metric="cosine", linkage="average", distance_threshold=DISTANCE
|
||||
).fit_predict(words[worded].toarray())
|
||||
for i, group in zip(worded, groups, strict=True):
|
||||
found[i] = int(group)
|
||||
return found
|
||||
|
||||
|
||||
def diverse(rows: list[dict], n: int) -> list[dict]:
|
||||
"""`n` of a layout's documents, each the least like those already taken (the first, the
|
||||
most typical): what sets a few documents apart (an organ, a death) is among them."""
|
||||
if len(rows) <= n:
|
||||
return rows
|
||||
try:
|
||||
x = TfidfVectorizer(token_pattern=WORDS).fit_transform([r["text"] for r in rows])
|
||||
except ValueError:
|
||||
return spread(rows, n)
|
||||
alike = (x @ x.T).toarray()
|
||||
taken = [int(alike.sum(axis=1).argmax())]
|
||||
nearest = alike[taken[0]].copy()
|
||||
while len(taken) < n:
|
||||
nearest[taken] = np.inf
|
||||
taken.append(int(nearest.argmin()))
|
||||
nearest = np.maximum(nearest, alike[taken[-1]])
|
||||
return [rows[i] for i in sorted(taken)]
|
||||
|
||||
|
||||
def spread(items: list, n: int) -> list:
|
||||
"""`n` items from first to last."""
|
||||
if len(items) <= n:
|
||||
return items
|
||||
return [items[round(i * (len(items) - 1) / (n - 1))] for i in range(n)]
|
||||
|
||||
|
||||
def marks(marker: str, text: str) -> bool:
|
||||
"""As the route will test it (core.pipeline.matches: `contains`, or `matches`)."""
|
||||
if marker.startswith(LOOSE):
|
||||
return re.search(marker, text) is not None
|
||||
return marker.casefold() in text.casefold()
|
||||
|
||||
|
||||
def condition(marker: str) -> dict:
|
||||
"""The route condition that tests a marker."""
|
||||
return {"column": "text", "op": "matches" if marker.startswith(LOOSE) else "contains",
|
||||
"value": marker} # fmt: skip
|
||||
|
||||
|
||||
def loose(phrase: str | None, least: int = 2) -> str | None:
|
||||
"""A phrase the model wrote as a pattern its document may write a little apart: its
|
||||
words in order, accents either way, up to two words between them ("MAMA, BIOPSIA"
|
||||
finds "MAMA DERECHA, BIOPSIA:")."""
|
||||
words = re.findall(r"[^\W_]+", phrase or "")
|
||||
if len(words) < least:
|
||||
return None
|
||||
|
||||
def letter(c: str) -> str:
|
||||
bare = unicodedata.normalize("NFD", c.casefold())[0]
|
||||
return f"[{ACCENTED[bare]}]" if bare in ACCENTED else re.escape(c)
|
||||
|
||||
return LOOSE + r"\b" + GAP.join("".join(letter(c) for c in w) for w in words) + r"\b"
|
||||
|
||||
|
||||
def phrase(marker: str | None, members, others, share=COVERED) -> str | None:
|
||||
"""The model's marker as written if it holds, else written loosely if that holds."""
|
||||
for found in (marker, loose(marker)):
|
||||
if found and holds(found, members, others, share):
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
def kinds_of(line: str, documents: list[dict]) -> int:
|
||||
"""How many different lines these documents print under this line's label (`ÓRGANO:
|
||||
MAMA` → the organs): few for what tells studies apart, many for a diagnosis."""
|
||||
label = line.split(":", 1)[0].strip().casefold() if ":" in line else None
|
||||
if label is None:
|
||||
return 2 # a line some print and others don't
|
||||
return len({x.strip().casefold() for r in documents for x in r["text"].splitlines()
|
||||
if x.strip().casefold().startswith(label + ":")}) # fmt: skip
|
||||
|
||||
|
||||
def holds(marker: str | None, members: list[dict], others: list[dict], share=COVERED) -> bool:
|
||||
"""A marker found in (nearly) all of these documents and in none of the others."""
|
||||
if not marker or len(marker) < 4:
|
||||
return False
|
||||
covered = sum(marks(marker, r["text"]) for r in members) / len(members)
|
||||
return covered >= share and not any(marks(marker, r["text"]) for r in others)
|
||||
|
||||
|
||||
def printed_line(members: list[dict], others: list[dict], share=COVERED, rank=None) -> str | None:
|
||||
"""The wordiest line printed in (nearly) all of these documents and in none of the
|
||||
others (a form's label): the marker when the model's isn't (a title the printer
|
||||
overstrikes reads "DDDDEEEE" in the text layer, so the title the model sees is not
|
||||
in the text)."""
|
||||
counts = Counter(
|
||||
line for r in members for line in {x.strip() for x in r["text"].splitlines()}
|
||||
if LINE.match(line)
|
||||
) # fmt: skip
|
||||
candidates = [line for line, n in counts.items() if n / len(members) >= share]
|
||||
readable = lambda line: (len(re.findall(WORDS, line)), len(line)) # noqa: E731
|
||||
for line in sorted(candidates, key=rank or readable, reverse=True):
|
||||
if holds(line, members, others, share):
|
||||
return line
|
||||
return None
|
||||
|
||||
|
||||
def bare(word: str) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFD", word.casefold()) if c.isalpha())
|
||||
|
||||
|
||||
def shared_words(members: list[dict], others: list[dict], first="", layout=(), most=3, only=False):
|
||||
"""The fewest words, in order, all of these documents write and none of the others,
|
||||
accents and case aside (a breast biopsy writes MAMA, whichever side): when no line
|
||||
marks them. Words of `first` (the study's name) are tried before the others (`only`:
|
||||
those alone); a word only one of the `layout`'s documents writes (a name) is never one."""
|
||||
words = re.findall(r"[^\W\d_]+", members[0]["text"])
|
||||
preferred = {bare(w) for w in re.findall(r"[^\W\d_]+", first)}
|
||||
written = Counter(w for r in layout or [*members, *others]
|
||||
for w in {bare(x) for x in re.findall(r"[^\W\d_]+", r["text"])}) # fmt: skip
|
||||
for n in range(1, most + 1):
|
||||
grams = [words[i : i + n] for i in range(len(words) - n + 1)]
|
||||
grams = [g for g in grams if sum(map(len, g)) >= 4 and all(written[bare(w)] > 1 for w in g)]
|
||||
grams.sort(key=lambda g: not all(bare(w) in preferred for w in g)) # stable
|
||||
grams = [g for g in grams if not only or all(bare(w) in preferred for w in g)]
|
||||
for gram in grams:
|
||||
if holds(found := loose(" ".join(gram), least=1), members, others, 1.0):
|
||||
return found
|
||||
return None
|
||||
@@ -1,60 +0,0 @@
|
||||
"""A table (columns, no files): the model says which column holds each fact about whom a
|
||||
row is about and each field of the studies its rows report; dates get the format all of
|
||||
a column's values parse with, and coded columns their values in platform terms."""
|
||||
|
||||
import json
|
||||
|
||||
from core.drafting import TABLE, is_date, studies_text, table_schema
|
||||
from core.pipeline import ENTITY_TITLES, Map, Source
|
||||
from core.schema import ENTITIES
|
||||
from models.draft import fields
|
||||
from persistance import llm
|
||||
|
||||
SHOWN = 15 # rows the model sees
|
||||
SCANNED = 2000 # rows whose values give the date formats and the codes
|
||||
LONG = 80 # characters of a value shown
|
||||
|
||||
|
||||
def _shown(value):
|
||||
text = value if isinstance(value, str) else json.dumps(value, default=str)
|
||||
return text[:LONG]
|
||||
|
||||
|
||||
def draft(d, source: Source, rows: list[dict], log) -> None:
|
||||
"""One map node for identity and one per study the table reports."""
|
||||
columns = sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")})
|
||||
if not columns:
|
||||
return
|
||||
shown = "\n".join(json.dumps({c: _shown(r.get(c)) for c in columns}, ensure_ascii=False)
|
||||
for r in rows[:SHOWN]) # fmt: skip
|
||||
try:
|
||||
answer = llm.ask(TABLE.format(studies=studies_text()), f"{columns}\n{shown}",
|
||||
table_schema(columns)) # fmt: skip
|
||||
except llm.Unreadable as e: # left undrawn: a person maps it
|
||||
log(f"{source.id} left out, the model's answer: {e}")
|
||||
return
|
||||
wanted = [("identity", answer["identity"])]
|
||||
wanted += [(s["entity"], s["fields"]) for s in answer["studies"]]
|
||||
for entity, held in wanted:
|
||||
mapped = {h["field"]: h["column"] for h in held
|
||||
if h["field"] in ENTITIES[entity].model_fields} # fmt: skip
|
||||
if not mapped:
|
||||
continue
|
||||
node = mapping(d, source, entity, mapped, rows[:SCANNED])
|
||||
(d.identity if entity == "identity" else d.studies.setdefault(entity, [])).append(node)
|
||||
log(f"{source.id}: {entity} from {sorted(mapped.values())}")
|
||||
|
||||
|
||||
def mapping(d, source: Source, entity: str, mapped: dict[str, str], rows: list[dict]) -> str:
|
||||
formats = {}
|
||||
for field, column in mapped.items():
|
||||
values = [r.get(column) for r in rows]
|
||||
if is_date(entity, field) and (fmt := fields.date_format(values)):
|
||||
formats[field] = fmt
|
||||
elif fields.coded(entity, field):
|
||||
d.codes.ask(entity, field, {str(v).strip() for v in values if v not in (None, "")})
|
||||
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
||||
node = Map(id=d.id(f"{source.id}_{entity}"), label=f"{title} ({source.label or source.id})",
|
||||
inputs=[source.id], fields=mapped, formats=formats,
|
||||
concept_map=d.codes.for_node(entity, mapped)) # fmt: skip
|
||||
return d.add(node).id
|
||||
+55
-54
@@ -1,8 +1,10 @@
|
||||
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
||||
places what the targets staged into silver."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
@@ -15,12 +17,12 @@ import pdfplumber
|
||||
import pikepdf
|
||||
import splink.comparison_library as cl
|
||||
from markitdown import MarkItDown
|
||||
from openai import OpenAI, OpenAIError
|
||||
from splink import Linker, SettingsCreator, block_on
|
||||
from splink.backends.duckdb import DuckDBAPI
|
||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||
|
||||
from core import catalog, concept_map, fhir_in
|
||||
from core.drafting import extract_prompt
|
||||
from core.pipeline import (
|
||||
FIELD_EVIDENCE,
|
||||
HELD,
|
||||
@@ -44,19 +46,16 @@ from core.pipeline import (
|
||||
matches,
|
||||
validate,
|
||||
)
|
||||
from models import suggest
|
||||
from persistance import config_log, files, llm, nodes, silver
|
||||
from persistance import config_log, files, nodes, silver
|
||||
|
||||
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
|
||||
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
|
||||
FILE = "_file" # the read file's key (persistance.files): its pages, for a model that sees
|
||||
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
||||
"text": {"data_type": "text", "nullable": True},
|
||||
"ocr": {"data_type": "bool"},
|
||||
"error": {"data_type": "text", "nullable": True},
|
||||
"format": {"data_type": "text", "nullable": True},
|
||||
}
|
||||
ROW_COLUMNS = {**READ_COLUMNS, FILE: {"data_type": "text", "nullable": True}}
|
||||
|
||||
|
||||
def file_format(content: bytes) -> str:
|
||||
@@ -159,10 +158,9 @@ def run_read(p: str, node: Read):
|
||||
READ_COLUMNS) # fmt: skip
|
||||
found |= read
|
||||
for row in rows:
|
||||
row[FILE] = row.pop("key")
|
||||
result = found.get(row[FILE], {"text": None, "ocr": False, "error": "empty"})
|
||||
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
||||
row |= {k: result[k] for k in READ_COLUMNS}
|
||||
return nodes.write(p, node.id, rows, ROW_COLUMNS)
|
||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||
|
||||
|
||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||
@@ -187,11 +185,10 @@ def run_map(p: str, node: Map):
|
||||
|
||||
|
||||
def run_fhir(p: str, node: Fhir):
|
||||
"""The node's entity from every Bundle at its source, as one: a resource sent again is
|
||||
its latest, and one Bundle may name what another sent."""
|
||||
"""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 []
|
||||
sent = 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 sent)
|
||||
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))
|
||||
|
||||
|
||||
@@ -200,43 +197,51 @@ def run_join(p: str, node: Join):
|
||||
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
||||
|
||||
|
||||
def page_images(content: bytes, pages: int = 2) -> list[bytes]:
|
||||
"""The first pages of a PDF as PNG pictures, for a model that reads images (a scan's
|
||||
OCR text misses what the picture still shows)."""
|
||||
out = []
|
||||
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||
for page in pdf.pages[:pages]:
|
||||
picture = io.BytesIO()
|
||||
page.to_image(resolution=110).original.save(picture, format="PNG")
|
||||
out.append(picture.getvalue())
|
||||
return out
|
||||
@cache
|
||||
def _llm() -> tuple[OpenAI, str] | None:
|
||||
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
|
||||
if not (url := os.environ.get("LLM_URL")):
|
||||
return None
|
||||
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
|
||||
try:
|
||||
client.models.list()
|
||||
except OpenAIError:
|
||||
return None
|
||||
return client, os.environ["LLM_MODEL"]
|
||||
|
||||
|
||||
def images(row: dict) -> list[bytes]:
|
||||
"""A scanned document's pages as pictures, when the model reads them."""
|
||||
if not (row.get("ocr") and row.get(FILE) and llm.vision()):
|
||||
return []
|
||||
content = files.content(row[FILE])
|
||||
return page_images(content) if content and file_format(content) == "pdf" else []
|
||||
PROMPT = (
|
||||
"Extract every {entity} record stated in the document. For each field give its value "
|
||||
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
||||
"copied character by character. Leave out fields the document does not state.{hints}"
|
||||
)
|
||||
|
||||
|
||||
def answer(entity: str, text: str, hints: str = "", pictures: list[bytes] = ()) -> dict:
|
||||
"""The model's records of `entity` in `text`, each value with the text it was read
|
||||
from (the same question for the same document is asked once)."""
|
||||
return llm.ask(extract_prompt(entity, hints), text, answer_schema(entity), pictures)
|
||||
def _ask_llm(node: Extract, text: str) -> dict:
|
||||
client, model = _llm()
|
||||
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
|
||||
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
|
||||
if found := nodes.cached("llm_cache", {key}):
|
||||
return json.loads(found[key]["answer"])
|
||||
reply = client.chat.completions.create(
|
||||
model=model, temperature=0, seed=7,
|
||||
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
||||
response_format={"type": "json_schema", "json_schema": {
|
||||
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
||||
) # fmt: skip
|
||||
answer = reply.choices[0].message.content
|
||||
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
||||
return json.loads(answer)
|
||||
|
||||
|
||||
def run_extract(p: str, node: Extract):
|
||||
use_llm = node.method == "llm" or (node.method == "auto" and llm.available())
|
||||
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
||||
codes = _codes(node, node.patterns)
|
||||
out = []
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
text = node.text(row)
|
||||
if use_llm:
|
||||
try:
|
||||
found = ground(answer(node.entity, text, node.hints, images(row)), text)
|
||||
except llm.Unreadable as e: # this document waits for a reviewer, not the run
|
||||
found = [({}, {}, [f"the model's answer could not be read: {e}"])]
|
||||
found = ground(_ask_llm(node, text), text)
|
||||
elif node.patterns:
|
||||
found = apply_patterns(node, text, codes)
|
||||
else:
|
||||
@@ -471,15 +476,6 @@ def run_link(p: str, node: Link):
|
||||
return nodes.write(p, f"{node.id}__review", queue)
|
||||
|
||||
|
||||
def provenance(study, clean, field, record: str) -> dict:
|
||||
"""Where a value comes from when its source doesn't say: the day of its event, made
|
||||
available with the study's report (its own event's day without one)."""
|
||||
day = getattr(clean, study.events[field.event].date)
|
||||
available = getattr(clean, study.events["report"].date) if "report" in study.events else day
|
||||
return {"source_ref": record, "source_clinical_date": day and str(day),
|
||||
"source_available_at": available and str(available)} # fmt: skip
|
||||
|
||||
|
||||
def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
"""Rows of one study into silver's staging, each given its person by the link node:
|
||||
a clean row becomes one observation per field it has (long), keyed by its study
|
||||
@@ -488,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):
|
||||
@@ -508,11 +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])
|
||||
sent = json.loads(row.get(FIELD_EVIDENCE) or "{}")
|
||||
evidence = json.loads(row.get(FIELD_EVIDENCE) or "{}")
|
||||
for name, field in study.fields.items():
|
||||
if (value := getattr(clean, name)) is not None:
|
||||
source = sent.get(name) or provenance(study, clean, field, row[RECORD])
|
||||
observations.append({**base, **source, "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)
|
||||
@@ -539,8 +545,3 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
||||
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
|
||||
log(f"silver and gold, from {', '.join(entities)}")
|
||||
links = [n.id for n in pipeline.nodes if n.kind == "link"]
|
||||
if links and llm.available(): # the model's reading beside what waits for reviewers
|
||||
for link in links:
|
||||
suggest.persons(pipeline_id, link)
|
||||
log(f"suggestions for review: {', '.join(links)}")
|
||||
|
||||
+20
-15
@@ -11,7 +11,6 @@ import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
|
||||
from core import models
|
||||
from persistance import gold, registry
|
||||
|
||||
|
||||
@@ -36,8 +35,7 @@ class Jobs:
|
||||
models: dict
|
||||
technical_validation: Callable[..., dict]
|
||||
interpretability: Callable[..., dict]
|
||||
# (spec, as_of) -> who the model's cohort lost and why, kept beside its reports (not one
|
||||
# promotion asks for); None: not kept
|
||||
# (spec, as_of) -> who the model's cohort lost, kept beside the reports; None: not kept
|
||||
attrition: Callable[..., dict | None] | None = None
|
||||
|
||||
@property
|
||||
@@ -45,8 +43,12 @@ class Jobs:
|
||||
return f"{self.domain}_events"
|
||||
|
||||
def routine(self) -> list[str]:
|
||||
"""The models a run takes when none is named: all but the hidden ones."""
|
||||
return [n for n in self.models if self.registered(n) not in models.HIDDEN]
|
||||
"""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:
|
||||
return f"{self.domain}.{name}"
|
||||
@@ -55,25 +57,28 @@ class Jobs:
|
||||
"""A new registered version of the model, trained on its cohort's timelines up to
|
||||
`as_of` (default: today), with its metrics and its two generated reports."""
|
||||
spec, as_of = self.models[name], as_of or date.today()
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, found = spec.train(events, as_of)
|
||||
if not getattr(spec, "reports", False): # else trained with its own reports
|
||||
data = found
|
||||
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, found = spec.train(events, as_of)
|
||||
else:
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, data = spec.train(events, as_of)
|
||||
found = {
|
||||
"technical_validation": self.technical_validation(spec, metrics, data),
|
||||
"interpretability": self.interpretability(spec, fitted, data),
|
||||
}
|
||||
if hasattr(fitted, "variance_diagnostics"): # where its intervals can't be had
|
||||
if hasattr(fitted, "variance_diagnostics"):
|
||||
found["variance_diagnostics"] = fitted.variance_diagnostics(
|
||||
data["coded"][spec.features]
|
||||
)
|
||||
data["coded"][spec.features])
|
||||
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
|
||||
# for its idle workers to time out (5 minutes) before it can end.
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
if self.attrition and (lost := self.attrition(spec, as_of)) is not None:
|
||||
found["attrition"] = lost
|
||||
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)
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
"""The model's reading of what a link node leaves to reviewers, shown beside each case:
|
||||
whether a person and a possible owner are one patient, and which record of a torn person
|
||||
belongs to someone else, each with its reason. A suggestion decides nothing: reviewers
|
||||
still answer every case (persistance.nodes)."""
|
||||
|
||||
import json
|
||||
|
||||
from core.drafting import SAME_PERSON, TORN, same_person_schema, torn_schema
|
||||
from core.pipeline import HELD, RECORD
|
||||
from persistance import llm, nodes
|
||||
|
||||
PAIRS, TORN_PERSONS = "__suggestions", "__torn_suggestions"
|
||||
|
||||
|
||||
def _side(row: dict, prefix: str) -> dict:
|
||||
return {k.removeprefix(prefix): v for k, v in row.items()
|
||||
if k.startswith(prefix) and v is not None} # fmt: skip
|
||||
|
||||
|
||||
def _ask(system: str, text: str, schema: dict, unsure: dict) -> dict:
|
||||
"""The model's suggestion; an answer it couldn't give says so to the reviewer."""
|
||||
try:
|
||||
return llm.ask(system, text, schema)
|
||||
except llm.Unreadable:
|
||||
return {**unsure, "reason": "El modelo no dio una respuesta legible para este caso."}
|
||||
|
||||
|
||||
def persons(pipeline_id: str, link: str) -> None:
|
||||
"""Suggestions for the link node's queue (pairs) and its torn persons."""
|
||||
pairs = []
|
||||
for row in nodes.rows(pipeline_id, f"{link}__review"):
|
||||
case = {"a": _side(row, "person_"), "b": _side(row, "candidate_"), "why": row["reason"]}
|
||||
text = json.dumps(case, default=str, ensure_ascii=False)
|
||||
answer = _ask(SAME_PERSON, text, same_person_schema(), {"same": None})
|
||||
pairs.append({"person": row["person"], "candidate": row["candidate"],
|
||||
"same": answer["same"], "reason": answer["reason"]}) # fmt: skip
|
||||
nodes.write(pipeline_id, f"{link}{PAIRS}", pairs)
|
||||
torn: dict[str, list[dict]] = {}
|
||||
for row in nodes.rows(pipeline_id, link):
|
||||
if "disagree" in (row.get(HELD) or ""):
|
||||
record = {k: v for k, v in row.items() if not k.startswith("_") and v is not None}
|
||||
torn.setdefault(row["person_id"], []).append({**record, "id": row[RECORD]})
|
||||
found = []
|
||||
for person, records in torn.items():
|
||||
text = json.dumps(records, default=str, ensure_ascii=False)
|
||||
answer = _ask(TORN, text, torn_schema([r["id"] for r in records]), {"record": None})
|
||||
found.append({"person": person, "record": answer["record"], "reason": answer["reason"]})
|
||||
nodes.write(pipeline_id, f"{link}{TORN_PERSONS}", found)
|
||||
+62
-13
@@ -222,17 +222,8 @@ class IntervalSurvival(BaseEstimator):
|
||||
# ---------------------------------------------------------------- a model over gold timelines
|
||||
|
||||
TRAIN_FRACTION = 0.7
|
||||
|
||||
|
||||
def inputs(members: pd.DataFrame, columns, repeat: int) -> np.ndarray:
|
||||
"""What each member's estimate read (JSON, unknown as null), once per horizon."""
|
||||
rows = members[list(columns)].astype(object).where(members[list(columns)].notna(), None)
|
||||
found = [json.dumps(row, default=str) for row in rows.to_dict("records")]
|
||||
return np.repeat(np.asarray(found, dtype=object), repeat)
|
||||
|
||||
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
|
||||
"scenarios", "input_values"] # fmt: skip
|
||||
"scenarios"] # fmt: skip
|
||||
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
|
||||
|
||||
|
||||
@@ -350,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),
|
||||
@@ -358,8 +349,12 @@ class Spec:
|
||||
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
|
||||
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
|
||||
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
||||
"input_values": inputs(members, self.features, 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)
|
||||
@@ -440,6 +435,40 @@ 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
|
||||
@@ -497,7 +526,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
for n, m in masks.items() if n not in drawn] # fmt: skip
|
||||
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,
|
||||
@@ -519,6 +548,26 @@ 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
|
||||
|
||||
+313
-140
@@ -2,28 +2,29 @@
|
||||
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),
|
||||
with a cumulative-logit model of the item's level as sensitivity; the CSS, and a composite
|
||||
of items with too few events (by how many are altered), the other way round.
|
||||
- q: Benjamini–Hochberg within each biomarker, exploratory pairs apart.
|
||||
- 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).
|
||||
A child the association was fitted on is scored by the model refitted without her
|
||||
(leave-one-out); spikes enter as present or not over a group of zones (`spikes_any`), and an
|
||||
estimate on fewer than MIN_EVENTS children with (or without) the event is flagged. The
|
||||
models are models.tea.logit's."""
|
||||
The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py)."""
|
||||
|
||||
import hashlib
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import optimize, stats
|
||||
from scipy.special import expit
|
||||
from statsmodels.stats.multitest import multipletests
|
||||
|
||||
from core.tea import association as spec
|
||||
from core.tea.reasons import INSUFFICIENT_DATA
|
||||
from models.tea.eeg.spindles import ZONES
|
||||
from models.tea.logit import firth, firth_fit, ordinal, ordinal_fit, probability, rows
|
||||
|
||||
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:
|
||||
@@ -41,17 +42,244 @@ def has_items(frame: pd.DataFrame) -> bool:
|
||||
return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN
|
||||
|
||||
|
||||
def _state(model: str, t: pd.DataFrame, pair: dict) -> dict | None:
|
||||
"""Only the scoring state of a pair's model refitted on `t` (leave-one-out)."""
|
||||
try:
|
||||
if model == "firth":
|
||||
fitted = firth_fit(rows(t, "_yes", pair["predictor"]), "_yes", pair["predictor"])
|
||||
return fitted and fitted[-1]
|
||||
fitted = ordinal_fit(rows(t, "_level", pair["predictor"]), "_level", pair["predictor"],
|
||||
_high(pair)) # fmt: skip
|
||||
return fitted[-1] if isinstance(fitted, tuple) else None
|
||||
except (np.linalg.LinAlgError, ValueError):
|
||||
return None
|
||||
@dataclass
|
||||
class Design:
|
||||
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
|
||||
the cohort's mean and each categorical one against its commonest level."""
|
||||
|
||||
predictor: str
|
||||
numeric: dict[str, float] = field(default_factory=dict)
|
||||
categorical: dict[str, list[str]] = field(default_factory=dict)
|
||||
reference: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
|
||||
d = cls(predictor)
|
||||
for a in (a for a in spec.ADJUST if a in t):
|
||||
v = t[a]
|
||||
if pd.api.types.is_numeric_dtype(v):
|
||||
if v.astype(float).std() > 0:
|
||||
d.numeric[a] = float(v.astype(float).mean())
|
||||
continue
|
||||
commonest = v.value_counts().index[0]
|
||||
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
|
||||
if levels:
|
||||
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
|
||||
return d
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return [
|
||||
"intercept",
|
||||
self.predictor,
|
||||
*self.numeric,
|
||||
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
|
||||
]
|
||||
|
||||
def matrix(self, t: pd.DataFrame) -> np.ndarray:
|
||||
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
|
||||
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()]
|
||||
known = np.ones(len(t), bool)
|
||||
for a, levels in self.categorical.items():
|
||||
v = t[a].astype(str)
|
||||
cols += [(v == x).to_numpy(float) for x in levels]
|
||||
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy()
|
||||
X = np.column_stack(cols)
|
||||
X[~known] = np.nan
|
||||
return X
|
||||
|
||||
def state(self) -> dict:
|
||||
return {
|
||||
"predictor": self.predictor,
|
||||
"numeric": self.numeric,
|
||||
"categorical": self.categorical,
|
||||
"reference": self.reference,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_state(cls, s: dict) -> "Design":
|
||||
return cls(
|
||||
s["predictor"],
|
||||
dict(s["numeric"]),
|
||||
{k: list(v) for k, v in s["categorical"].items()},
|
||||
dict(s["reference"]),
|
||||
)
|
||||
|
||||
|
||||
# Firth: the log-likelihood penalised by half the log-determinant of the information.
|
||||
def _penalised(b, X, y) -> float:
|
||||
eta = X @ b
|
||||
w = expit(eta) * (1 - expit(eta))
|
||||
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
|
||||
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
|
||||
|
||||
|
||||
def _gradient(b, X, y):
|
||||
"""The penalised score and the information at `b`."""
|
||||
p = expit(X @ b)
|
||||
w = p * (1 - p)
|
||||
info = X.T @ (X * w[:, None])
|
||||
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||
return X.T @ (y - p + leverage * (0.5 - p)), info
|
||||
|
||||
|
||||
def _firth_fit(X, y, max_iter=200, tol=1e-10):
|
||||
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
|
||||
b = np.zeros(X.shape[1])
|
||||
best = _penalised(b, X, y)
|
||||
for _ in range(max_iter):
|
||||
score, info = _gradient(b, X, y)
|
||||
step, t = np.linalg.solve(info, score), 1.0
|
||||
while t > 1e-8:
|
||||
trial = _penalised(b + t * step, X, y)
|
||||
if trial >= best - 1e-12:
|
||||
break
|
||||
t /= 2
|
||||
b, best = b + t * step, trial
|
||||
if np.max(np.abs(t * step)) < tol:
|
||||
break
|
||||
return b, best
|
||||
|
||||
|
||||
def _firth_profile(value, j, X, y, start) -> float:
|
||||
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
|
||||
free = [k for k in range(X.shape[1]) if k != j]
|
||||
|
||||
def negative(bf):
|
||||
b = np.empty(X.shape[1])
|
||||
b[free], b[j] = bf, value
|
||||
v = _penalised(b, X, y)
|
||||
if not np.isfinite(v):
|
||||
return 1e10, np.zeros(len(free))
|
||||
return -v, -_gradient(b, X, y)[0][free]
|
||||
|
||||
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
||||
|
||||
|
||||
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
||||
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
|
||||
each side of `centre`, searched in steps of `scale` (infinite if never)."""
|
||||
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
||||
limits = []
|
||||
for sign in (-1, 1):
|
||||
previous, limit = centre, sign * np.inf
|
||||
for k in range(1, 80):
|
||||
v = centre + sign * scale * k
|
||||
if drop(v) > 0:
|
||||
limit = optimize.brentq(drop, min(previous, v), max(previous, v))
|
||||
break
|
||||
previous = v
|
||||
limits.append(limit)
|
||||
return limits[0], limits[1]
|
||||
|
||||
|
||||
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
|
||||
return {
|
||||
"model": model,
|
||||
"n": n,
|
||||
"coef": round(float(coef), 4),
|
||||
"odds_ratio": round(float(np.exp(coef)), 4),
|
||||
"ci_low": round(float(np.exp(low)), 4),
|
||||
"ci_high": round(float(np.exp(high)), 4),
|
||||
"p": round(p, 5),
|
||||
"adjusted_for": ", ".join(design.names[2:]),
|
||||
"reason": "",
|
||||
**extra,
|
||||
"state": {"design": design.state(), **state},
|
||||
}
|
||||
|
||||
|
||||
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
|
||||
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
|
||||
y = d[outcome].to_numpy(float)
|
||||
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
|
||||
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)
|
||||
b, top = _firth_fit(X, y)
|
||||
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
|
||||
profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731
|
||||
low, high = _interval(profile, b[1], top, max(se, 0.05))
|
||||
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
|
||||
# FLIC: the intercept refitted so the probabilities add up to the events.
|
||||
eta = X[:, 1:] @ b[1:]
|
||||
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
|
||||
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
|
||||
|
||||
|
||||
# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing.
|
||||
def _ordinal_nll(par, X, y, K) -> float:
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
eta = X @ par[K - 1 :]
|
||||
n = len(y)
|
||||
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
|
||||
return -float(
|
||||
np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None)))
|
||||
)
|
||||
|
||||
|
||||
def _ordinal_fit(X, y, K, fixed=None):
|
||||
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
||||
if fixed is None:
|
||||
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
||||
return r.x, float(r.fun)
|
||||
j, value = fixed
|
||||
free = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
|
||||
def nll(q):
|
||||
par = np.empty(len(start))
|
||||
par[free], par[K - 1 + j] = q, value
|
||||
return _ordinal_nll(par, X, y, K)
|
||||
|
||||
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
|
||||
|
||||
|
||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
||||
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
|
||||
levels = np.sort(d[outcome].unique())
|
||||
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
|
||||
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)[:, 1:]
|
||||
K = len(levels)
|
||||
y = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
par, nll = _ordinal_fit(X, y, K)
|
||||
beta = par[K - 1 :]
|
||||
if abs(beta[0]) > 20:
|
||||
return {**out, "reason": "does not converge (separation)"}
|
||||
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731
|
||||
low, high_ = _interval(profile, beta[0], -nll, 0.1)
|
||||
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
k = int(np.searchsorted(levels, high))
|
||||
inside = 0 < k < K
|
||||
state = {
|
||||
"beta": [float(v) for v in beta],
|
||||
"threshold": float(theta[k - 1]) if inside else None,
|
||||
"always": None if inside else float(k == 0),
|
||||
}
|
||||
return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K)
|
||||
|
||||
|
||||
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||
"""Each child's probability of the outcome under `fit`, and the reference child's."""
|
||||
s = fit["state"]
|
||||
X = Design.from_state(s["design"]).matrix(t)
|
||||
if fit["model"] == "firth":
|
||||
return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float(
|
||||
expit(s["intercept"])
|
||||
)
|
||||
if s["threshold"] is None:
|
||||
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]
|
||||
return (
|
||||
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
|
||||
float(1 - expit(s["threshold"])),
|
||||
)
|
||||
|
||||
|
||||
def _guarded(fit, *args) -> dict:
|
||||
@@ -62,101 +290,41 @@ def _guarded(fit, *args) -> dict:
|
||||
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
|
||||
|
||||
|
||||
def _high(pair: dict) -> int:
|
||||
return {"composite": 1, "domain": spec.CSS_HIGH}.get(pair["kind"], spec.ALTERED)
|
||||
|
||||
|
||||
def outcome(t: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
|
||||
"""(event, level): the CSS high, or any of the items altered; the level is the CSS, the
|
||||
item's score or how many of the items are altered."""
|
||||
if pair["kind"] == "domain":
|
||||
css = pd.to_numeric(t["css"] if "css" in t else np.nan, errors="coerce")
|
||||
css = pd.Series(css, index=t.index)
|
||||
return (css >= spec.CSS_HIGH).astype(float).where(css.notna()), css
|
||||
scores = pd.concat([item_scores(t, n) for n in spec.outcome_items(pair)], axis=1)
|
||||
complete = scores.notna().all(axis=1)
|
||||
altered = (scores >= spec.ALTERED).sum(axis=1).astype(float).where(complete)
|
||||
level = altered if pair["kind"] == "composite" else scores.iloc[:, 0]
|
||||
return (altered >= 1).astype(float).where(complete), level
|
||||
|
||||
|
||||
def _fit_pair(d: pd.DataFrame, pair: dict) -> dict:
|
||||
"""A pair's principal and sensitivity models: the CSS and a composite with too few events
|
||||
by its level (the cumulative logit), an item by whether it is altered (Firth); an
|
||||
estimate on fewer than MIN_EVENTS children with (or without) the event is flagged."""
|
||||
used = d[["_yes", pair["predictor"]]].dropna()
|
||||
events = int(used["_yes"].sum())
|
||||
without = len(used) - events
|
||||
short = min(events, without) < spec.MIN_EVENTS
|
||||
counted = short and pair["kind"] == "composite"
|
||||
binary = _guarded(firth, d, "_yes", pair["predictor"])
|
||||
graded = _guarded(ordinal, d, "_level", pair["predictor"], _high(pair))
|
||||
principal, sensitivity = ((graded, binary) if pair["kind"] == "domain" or counted
|
||||
else (binary, graded)) # fmt: skip
|
||||
if short and principal.get("odds_ratio") is not None:
|
||||
note = (f"{INSUFFICIENT_DATA}{events} con evento y {without} sin evento "
|
||||
f"(mínimo {spec.MIN_EVENTS})") # fmt: skip
|
||||
if counted:
|
||||
note += "; se usa el número de reactivos alterados"
|
||||
principal = {**principal, "reason": note}
|
||||
return {**pair, "principal": principal, "sensitivity": sensitivity}
|
||||
|
||||
|
||||
def spikes_any(features: dict) -> dict[str, float]:
|
||||
"""Whether the EEG shows any spike while asleep over each group of zones (NaN when no
|
||||
minute or electrode of the group was read), from the spikes' rates by electrode."""
|
||||
minutes = features.get("minutes") or 0
|
||||
out = {}
|
||||
for group, zones in spec.SPIKE_GROUPS.items():
|
||||
rates = [features.get(f"electrode_{e}") for z in zones for e in ZONES[z]]
|
||||
counts = [r * minutes for r in rates if r is not None]
|
||||
out[f"spikes_any_{group}"] = (float(any(n > 0 for n in counts))
|
||||
if minutes > 0 and counts else np.nan) # fmt: skip
|
||||
return out
|
||||
|
||||
|
||||
def _key(key) -> str:
|
||||
return hashlib.sha256(str(key).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
|
||||
"""Every pair's principal and sensitivity models and its q (Benjamini–Hochberg within
|
||||
each biomarker, exploratory pairs apart): what the association is."""
|
||||
"""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"
|
||||
tested, rows = spec.pairs(level), []
|
||||
for pair in tested:
|
||||
rows = []
|
||||
for pair in spec.pairs(level):
|
||||
if pair["predictor"] not in cohort:
|
||||
continue
|
||||
d = cohort.copy()
|
||||
d[pair["predictor"]] = pd.to_numeric(d[pair["predictor"]], errors="coerce").replace(
|
||||
[np.inf, -np.inf], np.nan) # fmt: skip
|
||||
d["_yes"], d["_level"] = outcome(d, pair)
|
||||
rows.append(_fit_pair(d, pair))
|
||||
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)
|
||||
families = np.array([r["biomarker"] for r in rows])
|
||||
tested_rows = np.array([r["kind"] != "exploratory" for r in rows], bool)
|
||||
biomarkers = np.array([r["biomarker"] for r in rows])
|
||||
q = np.full(len(rows), np.nan)
|
||||
for b in dict.fromkeys(families):
|
||||
mine = (families == b) & np.isfinite(p) & tested_rows
|
||||
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 {"version": spec.VERSION, "level": level, "n": len(cohort), "rows": rows,
|
||||
"pairs": tested, "keys": sorted(_key(k) for k in cohort.get("key", []))} # fmt: skip
|
||||
return {"level": level, "n": len(cohort), "rows": rows}
|
||||
|
||||
|
||||
def check(fitted: dict) -> dict:
|
||||
"""A saved association this version can score (one fitted before it must be retrained)."""
|
||||
if fitted.get("version") != spec.VERSION:
|
||||
raise ValueError(f"association {fitted.get('version', '0.1.0')} was fitted before "
|
||||
f"{spec.VERSION}: retrain it") # fmt: skip
|
||||
return fitted
|
||||
|
||||
|
||||
def _event(pair: dict) -> str:
|
||||
return f"alguno >={spec.ALTERED}" if pair["kind"] == "composite" else f">={_high(pair)}"
|
||||
def outcome_code(row: dict) -> str:
|
||||
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
|
||||
|
||||
|
||||
def associations(fitted: dict) -> list[dict]:
|
||||
@@ -165,52 +333,57 @@ def associations(fitted: dict) -> list[dict]:
|
||||
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": spec.outcome_code(r), "event": _event(r),
|
||||
"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", ""),
|
||||
}) # fmt: skip
|
||||
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 _scored(t: pd.DataFrame, fitted: dict, pair: dict) -> tuple[np.ndarray, float]:
|
||||
"""Each child's probability under the pair's principal model; a child the association
|
||||
was fitted on, under the model refitted without her (leave-one-out)."""
|
||||
f = pair["principal"]
|
||||
found, reference = probability(f["model"], f["state"], t)
|
||||
keys = set(fitted.get("keys", ()))
|
||||
child = t["person"] if "person" in t else t["key"]
|
||||
trained = t["key"].map(_key).isin(keys).to_numpy()
|
||||
for name in child[trained].unique():
|
||||
own = (child == name).to_numpy()
|
||||
state = _state(f["model"], t[trained & ~own], pair)
|
||||
found[own] = np.nan if state is None else probability(f["model"], state, t[own])[0]
|
||||
return found, reference
|
||||
|
||||
|
||||
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 check(fitted)["rows"]:
|
||||
if r["principal"].get("odds_ratio") is None or r["predictor"] not in cohort:
|
||||
for r in fitted["rows"]:
|
||||
f = r["principal"]
|
||||
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
|
||||
continue
|
||||
t = cohort
|
||||
for n in spec.outcome_items(r):
|
||||
t = t[t["module"].isin(spec.ITEMS[n][1])]
|
||||
t = t[pd.to_numeric(t[r["predictor"]], errors="coerce").notna()].copy()
|
||||
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
|
||||
t["_yes"], t["_level"] = outcome(t, r)
|
||||
found, reference = _scored(t, fitted, r)
|
||||
found, reference = probability(f, t)
|
||||
for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True):
|
||||
if np.isfinite(p):
|
||||
out.append({"key": key, "biomarker": r["biomarker"], "zone": r["zone"],
|
||||
"outcome_code": spec.outcome_code(r), "z": float(z),
|
||||
"probability": round(float(p), 4),
|
||||
"reference_probability": round(reference, 4)}) # fmt: skip
|
||||
out.append(
|
||||
{
|
||||
"key": key,
|
||||
"biomarker": r["biomarker"],
|
||||
"zone": r["zone"],
|
||||
"outcome_code": outcome_code(r),
|
||||
"z": float(z),
|
||||
"probability": round(float(p), 4),
|
||||
"reference_probability": round(reference, 4),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
+28
-31
@@ -1,13 +1,10 @@
|
||||
"""One EEG, from its EDF bytes: whether it can be analysed (and why not) and its four metrics.
|
||||
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
|
||||
|
||||
analysis = analyze(edf_bytes, birth_date)
|
||||
|
||||
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
|
||||
(`preprocess.py`), its windows get a state (`sleep.py`), and the metrics are measured
|
||||
(`biomarkers.py`) along with the features the age baselines score (`curves.py`), why a metric
|
||||
was not measured (`core.tea.reasons.METRIC_REASONS`) and the minutes the spike gate left out
|
||||
(`REJECTED_MINUTES`, with the stable start as `start_s`); an EEG not valid has every metric,
|
||||
none measured, for `invalid-eeg`.
|
||||
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are
|
||||
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
|
||||
|
||||
The age is the EDF header's (recording start minus birth date) when it has both dates, else the
|
||||
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
|
||||
@@ -20,7 +17,6 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
from core.tea.reasons import METRIC_REASONS, REJECTED_MINUTES
|
||||
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
|
||||
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
@@ -39,7 +35,6 @@ class Metric:
|
||||
class Analysis:
|
||||
valid: bool | None
|
||||
level: str
|
||||
reasons: list[str] # why it is not valid (checks.Validation.reasons)
|
||||
age_months: float | None
|
||||
clean_fraction: float | None
|
||||
bad_channels: int | None
|
||||
@@ -48,8 +43,9 @@ class Analysis:
|
||||
line_noise_db: float | None
|
||||
sleep: bool | None
|
||||
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
|
||||
metrics: list[Metric] # biomarkers.CODES
|
||||
features: dict[str, dict] # by scenario (`curves.SCENARIOS`), None missing; and the reasons
|
||||
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes,
|
||||
# anteroposterior_gradient
|
||||
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
|
||||
error: str | None
|
||||
|
||||
|
||||
@@ -57,16 +53,6 @@ def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def _result(out: dict, measured: biomarkers.Measured, **fields) -> Analysis:
|
||||
metrics = [Metric(code, _number(value), {k: _number(v) for k, v in electrodes.items()},
|
||||
{k: _number(v) for k, v in zones.items()})
|
||||
for code, (value, electrodes, zones) in measured.metrics.items()] # fmt: skip
|
||||
features = {s: {k: _number(v) for k, v in f.items()} for s, f in measured.features.items()}
|
||||
features[METRIC_REASONS] = measured.reasons
|
||||
features[REJECTED_MINUTES] = {k: _number(v) for k, v in measured.rejected.items()}
|
||||
return Analysis(**out | dict(metrics=metrics, features=features) | fields)
|
||||
|
||||
|
||||
def _error(exc: Exception) -> str:
|
||||
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
||||
return f"{type(exc).__name__}: {message}"
|
||||
@@ -78,14 +64,12 @@ def analyze(
|
||||
*,
|
||||
age_months: float | None = None,
|
||||
mains_hz: float = MAINS_HZ,
|
||||
keep_flat: bool = False,
|
||||
) -> Analysis:
|
||||
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
|
||||
of the recording's mains; `keep_flat` keeps a reference study's one flat electrode."""
|
||||
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`)."""
|
||||
out = dict(
|
||||
valid=None,
|
||||
level=checks.NOT_ANALYZABLE,
|
||||
reasons=[],
|
||||
age_months=age_months,
|
||||
clean_fraction=None,
|
||||
bad_channels=None,
|
||||
@@ -103,8 +87,9 @@ def analyze(
|
||||
rec = read.read(edf)
|
||||
except read.FileNotValid as exc:
|
||||
verdict = checks.file_not_valid(str(exc))
|
||||
return _result(out, biomarkers.invalid(), valid=False, reasons=verdict.reasons,
|
||||
clean_fraction=0.0, bad_channels=0, checks=verdict.checks) # fmt: skip
|
||||
return Analysis(
|
||||
**out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks)
|
||||
)
|
||||
if age_months is None:
|
||||
header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH)
|
||||
given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH)
|
||||
@@ -115,7 +100,6 @@ def analyze(
|
||||
out.update(
|
||||
valid=verdict.valid,
|
||||
level=verdict.level,
|
||||
reasons=verdict.reasons,
|
||||
clean_fraction=verdict.clean_pct / 100,
|
||||
bad_channels=len(verdict.bad),
|
||||
channels=len(rec.names) or None,
|
||||
@@ -124,12 +108,25 @@ def analyze(
|
||||
checks=verdict.checks,
|
||||
)
|
||||
if not verdict.valid:
|
||||
return _result(out, biomarkers.invalid())
|
||||
prep = preprocess.prepare(rec, verdict.bad, mains_hz, keep_flat=keep_flat)
|
||||
return Analysis(**out)
|
||||
prep = preprocess.prepare(rec, verdict.bad)
|
||||
notes = sleep.note_intervals(prep.annotations, prep.duration_s)
|
||||
states = sleep.states(prep, notes, age)
|
||||
measured = biomarkers.measure(prep, states, notes)
|
||||
measured.rejected["start_s"] = preprocess.stable_start(rec)
|
||||
return _result(out, measured, sleep=bool((states == "sleep").any()))
|
||||
staged = sleep.stages(prep, states)
|
||||
metrics, features = biomarkers.measure(prep, states, staged, notes)
|
||||
out.update(
|
||||
sleep=bool((states == "sleep").any()),
|
||||
metrics=[
|
||||
Metric(
|
||||
code,
|
||||
_number(value),
|
||||
{k: _number(v) for k, v in electrodes.items()},
|
||||
{k: _number(v) for k, v in zones.items()},
|
||||
)
|
||||
for code, (value, electrodes, zones) in metrics.items()
|
||||
],
|
||||
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
|
||||
)
|
||||
return Analysis(**out)
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch
|
||||
return Analysis(**out | dict(error=_error(exc)))
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""The four metrics of an EEG, their per-electrode and per-zone values, the features each age
|
||||
baseline scores (by scenario, `curves.SCENARIOS`) and why a metric was not measured (its reason:
|
||||
few-wake-windows, no-dominant-peak, no-sleep, few-electrodes, no-spindles; invalid-eeg for every
|
||||
metric of an EEG not valid).
|
||||
"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features
|
||||
each age baseline scores (by scenario, `curves.SCENARIOS`).
|
||||
|
||||
Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior
|
||||
electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more.
|
||||
@@ -10,13 +8,10 @@ Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-
|
||||
each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the
|
||||
electrode's front-back position (6 electrodes at least).
|
||||
|
||||
Spindles in NREM sleep (`spindles.py`): density, per zone, and enhancement per electrode, noting
|
||||
a posterior rhythm near sigma. Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode
|
||||
and per zone, against the minutes; awake, and the minutes the gate left out by reason.
|
||||
Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode.
|
||||
Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
import numpy as np
|
||||
from scipy.fft import rfft, rfftfreq
|
||||
from scipy.signal.windows import hann
|
||||
@@ -27,58 +22,49 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
from models.tea.eeg.sleep import POSTERIOR
|
||||
|
||||
MIN_WINDOWS = 15
|
||||
MIN_GRADIENT_ELECTRODES = 6
|
||||
INVALID = "invalid-eeg"
|
||||
FRONT_BACK = {
|
||||
"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
|
||||
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
|
||||
"Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
|
||||
} # fmt: skip
|
||||
CODES = ("posterior_rhythm", "spindles", "paroxysmal_spikes", "anteroposterior_gradient")
|
||||
CODES = (
|
||||
"posterior_rhythm",
|
||||
"spindles_n2",
|
||||
"spindles_n3",
|
||||
"paroxysmal_spikes",
|
||||
"anteroposterior_gradient",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Measured:
|
||||
metrics: dict[str, tuple[float, dict, dict]] # code -> (value, electrodes, zones)
|
||||
features: dict[str, dict[str, float]] # by scenario
|
||||
reasons: dict[str, str] # code -> why it was not measured
|
||||
rejected: dict[str, float] # minutes the spike gate left out, by reason
|
||||
|
||||
|
||||
def _segments(prep: Prepared, names, states, state) -> tuple[list[np.ndarray], int]:
|
||||
"""The gap-free 4 s windows labelled `state`, (channels, samples) each, and how many
|
||||
windows bear the label."""
|
||||
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None:
|
||||
"""The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15."""
|
||||
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
|
||||
if len(starts) < MIN_WINDOWS or not names:
|
||||
return None
|
||||
x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
|
||||
found = []
|
||||
for a in (int(round(float(s) * prep.fs)) for s in starts if names):
|
||||
for a in (int(round(float(s) * prep.fs)) for s in starts):
|
||||
if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
|
||||
found.append(x[a : a + n].T)
|
||||
return found, len(starts)
|
||||
return found or None
|
||||
|
||||
|
||||
def posterior_rhythm(prep: Prepared, states) -> tuple[float, str | None]:
|
||||
def posterior_rhythm(prep: Prepared, states) -> float:
|
||||
names = prep.columns(POSTERIOR)
|
||||
segments, windows = _segments(prep, names, states, "wake")
|
||||
if windows < MIN_WINDOWS:
|
||||
return np.nan, "few-wake-windows"
|
||||
if not segments:
|
||||
return np.nan, "no-dominant-peak"
|
||||
segments = _segments(prep, names, states, "wake")
|
||||
if segments is None:
|
||||
return np.nan
|
||||
f, power = signals.periodograms(np.stack(segments), prep.fs)
|
||||
peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))]
|
||||
found = [hz for hz, _, ok in peaks if ok]
|
||||
return (float(np.median(found)), None) if len(found) >= 2 else (np.nan, "no-dominant-peak")
|
||||
return float(np.median(found)) if len(found) >= 2 else np.nan
|
||||
|
||||
|
||||
def delta_gradient(prep: Prepared, states) -> tuple[float, str | None]:
|
||||
def delta_gradient(prep: Prepared, states) -> float:
|
||||
names = [c for c in prep.names if c in FRONT_BACK]
|
||||
segments, windows = _segments(prep, names, states, "sleep")
|
||||
if windows < MIN_WINDOWS:
|
||||
return np.nan, "no-sleep"
|
||||
if len(names) < MIN_GRADIENT_ELECTRODES:
|
||||
return np.nan, "few-electrodes"
|
||||
if not segments:
|
||||
return np.nan, "no-sleep"
|
||||
segments = _segments(prep, names, states, "sleep")
|
||||
if segments is None:
|
||||
return np.nan
|
||||
stack = np.stack(segments)
|
||||
n = stack.shape[-1]
|
||||
f = rfftfreq(n, 1 / prep.fs)
|
||||
@@ -87,50 +73,41 @@ def delta_gradient(prep: Prepared, states) -> tuple[float, str | None]:
|
||||
log_power = np.log10(np.maximum(delta, 1e-30))
|
||||
y = np.array([FRONT_BACK[c] for c in names])
|
||||
finite = np.isfinite(log_power)
|
||||
if finite.sum() < MIN_GRADIENT_ELECTRODES:
|
||||
return np.nan, "few-electrodes"
|
||||
return float(theilslopes(log_power[finite], y[finite])[0]), None
|
||||
return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan
|
||||
|
||||
|
||||
def invalid() -> Measured:
|
||||
"""An EEG not valid: no metric, each for that reason."""
|
||||
return Measured({c: (np.nan, {}, {}) for c in CODES}, {}, dict.fromkeys(CODES, INVALID), {})
|
||||
|
||||
|
||||
def measure(prep: Prepared, states, intervals) -> Measured:
|
||||
metrics, features, reasons = {}, {}, {}
|
||||
rhythm, reasons["posterior_rhythm"] = posterior_rhythm(prep, states)
|
||||
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
|
||||
"""(metrics: code -> (value, electrodes, zones), features by scenario)."""
|
||||
metrics, features = {}, {}
|
||||
rhythm = posterior_rhythm(prep, states)
|
||||
metrics["posterior_rhythm"] = (rhythm, {}, {})
|
||||
features["eeg-posterior-rhythm"] = {"value": rhythm}
|
||||
found = replace(spindles.detect(prep, states), rhythm_near_sigma=spindles.near_sigma(rhythm))
|
||||
value, zones = spindles.density(found)
|
||||
electrodes = spindles.enhancement(prep, found, states)
|
||||
metrics["spindles"] = (value, electrodes, zones)
|
||||
features["eeg-spindles"] = {"value": value, **{f"zone_{z}": v for z, v in zones.items()},
|
||||
"rhythm_near_sigma": float(found.rhythm_near_sigma)} # fmt: skip
|
||||
features["eeg-spindle-topography"] = {f"electrode_{e}": v for e, v in electrodes.items()}
|
||||
if np.isnan(value):
|
||||
reasons["spindles"] = "no-sleep" if found.minutes < spindles.MIN_MINUTES else "no-spindles"
|
||||
spiked = spikes.detect(prep, states, intervals)
|
||||
if spiked is None:
|
||||
reasons["paroxysmal_spikes"] = "few-electrodes"
|
||||
recorded = {z: sum(e in prep.names for e in m) for z, m in spindles.ZONES.items()}
|
||||
spiked = spikes.Spikes(np.nan, dict.fromkeys(spikes.ELECTRODES, np.nan),
|
||||
dict.fromkeys(spindles.ZONES, np.nan), 0.0, {}, np.nan, 0.0,
|
||||
recorded) # fmt: skip
|
||||
elif np.isnan(spiked.rate):
|
||||
reasons["paroxysmal_spikes"] = "no-sleep"
|
||||
metrics["paroxysmal_spikes"] = (spiked.rate, spiked.electrodes, spiked.zones)
|
||||
for stage in ("N2", "N3"):
|
||||
found = spindles.detect(prep, staged, stage)
|
||||
value, zones = spindles.density(found)
|
||||
electrodes = spindles.enhancement(prep, found, states)
|
||||
metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones)
|
||||
features[f"eeg-spindles-{stage.lower()}"] = {
|
||||
"value": value,
|
||||
**{f"zone_{z}": v for z, v in zones.items()},
|
||||
}
|
||||
features[f"eeg-spindle-topography-{stage.lower()}"] = {
|
||||
f"electrode_{e}": v for e, v in electrodes.items()
|
||||
}
|
||||
found = spikes.detect(prep, states, intervals)
|
||||
if found is None:
|
||||
nan = dict.fromkeys
|
||||
found = spikes.Spikes(
|
||||
np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0
|
||||
)
|
||||
metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones)
|
||||
features["eeg-spikes"] = {
|
||||
"value": spiked.rate,
|
||||
**{f"electrode_{e}": v for e, v in spiked.electrodes.items()},
|
||||
**{f"zone_{z}": v for z, v in spiked.zones.items()},
|
||||
"minutes": spiked.minutes, "awake_rate": spiked.awake_rate,
|
||||
"awake_minutes": spiked.awake_minutes,
|
||||
**{f"zone_electrodes_{z}": n for z, n in spiked.zone_electrodes.items()},
|
||||
} # fmt: skip
|
||||
gradient, reasons["anteroposterior_gradient"] = delta_gradient(prep, states)
|
||||
"value": found.rate,
|
||||
**{f"electrode_{e}": v for e, v in found.electrodes.items()},
|
||||
**{f"zone_{z}": v for z, v in found.zones.items()},
|
||||
"minutes": found.minutes,
|
||||
}
|
||||
gradient = delta_gradient(prep, states)
|
||||
metrics["anteroposterior_gradient"] = (gradient, {}, {})
|
||||
features["eeg-gradient"] = {"value": gradient}
|
||||
reasons = {code: why for code, why in reasons.items() if why}
|
||||
return Measured({code: metrics[code] for code in CODES}, features, reasons, spiked.rejected)
|
||||
return {code: metrics[code] for code in CODES}, features
|
||||
|
||||
+31
-36
@@ -37,8 +37,6 @@ MAX_BAD_SCALP = 2
|
||||
MIN_SCALP = 12
|
||||
MAX_LINE_DB = 45.0
|
||||
NOT_ANALYZABLE = "not_analyzable"
|
||||
LEVELS = {NOT_ANALYZABLE: "No analizable", "partial": "Parcial",
|
||||
"no_ear_reference": "Sin referencia auricular", "complete": "Completo"} # fmt: skip
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,7 +47,10 @@ class Validation:
|
||||
clean_pct: float
|
||||
line_db: float
|
||||
checks: list[dict] = field(default_factory=list)
|
||||
reasons: list[str] = field(default_factory=list) # why it is not valid
|
||||
|
||||
@property
|
||||
def ears_usable(self) -> bool:
|
||||
return all(ear not in self.bad for ear in ("A1", "A2"))
|
||||
|
||||
|
||||
def check(
|
||||
@@ -79,7 +80,7 @@ def check(
|
||||
|
||||
def file_not_valid(reason: str) -> Validation:
|
||||
rows = [check("file", text=reason, decisive=True, abnormal=True)]
|
||||
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows, ["invalid-file"])
|
||||
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows)
|
||||
|
||||
|
||||
def _filtered(x, fs, mains_hz, lo, hi):
|
||||
@@ -90,14 +91,14 @@ def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
|
||||
"""Rules on a channel's raw samples: (code, reason)."""
|
||||
finite = v[np.isfinite(v)]
|
||||
if len(finite) < 10 or np.std(finite) < 0.5:
|
||||
return [("dead-channel", "Canal muerto")]
|
||||
return [("dead-channel", "dead channel")]
|
||||
out = []
|
||||
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
|
||||
out.append(("frozen", "Señal congelada"))
|
||||
out.append(("frozen", "frozen"))
|
||||
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
|
||||
out.append(("saturated", "Señal saturada"))
|
||||
out.append(("saturated", "saturated"))
|
||||
if np.isinf(v).any():
|
||||
out.append(("inf-values", "Valores infinitos"))
|
||||
out.append(("inf-values", "Inf values"))
|
||||
return out
|
||||
|
||||
|
||||
@@ -165,7 +166,9 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
||||
"""Channel -> [(code, reason)] of every channel some rule flags."""
|
||||
x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
|
||||
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
|
||||
dead = {name for name, found in reasons.items() if found and found[0][0] == "dead-channel"}
|
||||
dead = {
|
||||
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
|
||||
}
|
||||
notched = signals.notch(x, fs, mains_hz)
|
||||
y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9))
|
||||
y40 = signals.bandpass(notched, fs, 1.0, 40.0)
|
||||
@@ -181,38 +184,34 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
||||
found, k = reasons[name], kinds[name]
|
||||
if missing[i] > missing.min() + 0.02:
|
||||
excess = 100 * (missing[i] - missing.min())
|
||||
found.append(
|
||||
("own-gaps", f"Interrupciones del canal ({excess:.1f} % más que el resto)")
|
||||
)
|
||||
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
|
||||
if name in dead:
|
||||
continue
|
||||
if k == "eeg" and name in bridges:
|
||||
found.append(("bridge", f"Puente con {bridges[name]}"))
|
||||
found.append(("bridge", f"bridge with {bridges[name]}"))
|
||||
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
|
||||
found.append(
|
||||
("amplitude", f"Amplitud {ratio[i]:.1f} veces la mediana del cuero cabelludo")
|
||||
)
|
||||
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
|
||||
if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
|
||||
c, e = ears[name]
|
||||
found.append(
|
||||
(
|
||||
"does-not-correlate",
|
||||
f"Sin correlación con los vecinos ({c:.2f} frente a {e:.2f})",
|
||||
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
|
||||
)
|
||||
)
|
||||
if np.isfinite(low[i]) and low[i] > 0.10:
|
||||
found.append(
|
||||
(
|
||||
"intermittent-contact",
|
||||
f"Contacto intermitente ({100 * low[i]:.0f} % de bloques sin señal)",
|
||||
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
|
||||
)
|
||||
)
|
||||
if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
|
||||
found.append(
|
||||
(
|
||||
"intermittent-bursts",
|
||||
f"Contacto intermitente por ráfagas "
|
||||
f"({100 * burst[i]:.0f} % de bloques por encima de 4 veces el montaje)",
|
||||
f"intermittent contact by bursts "
|
||||
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
|
||||
)
|
||||
)
|
||||
if k in ("eog", "ecg"):
|
||||
@@ -221,19 +220,18 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
||||
found.append(
|
||||
(
|
||||
"aux-amplitude",
|
||||
f"Amplitud {np.sqrt(np.mean(v**2)):.0f} µV, "
|
||||
f"fuera de rango incluso para {k.upper()}",
|
||||
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, "
|
||||
f"out of range even for {k.upper()}",
|
||||
)
|
||||
)
|
||||
return {name: found for name, found in reasons.items() if found}
|
||||
|
||||
|
||||
def window_qc(y: np.ndarray, fs: float, start_s: float = 0.0) -> list[tuple[float, float, str]]:
|
||||
def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
|
||||
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
|
||||
verdict `gap`, `suspect` or `clean`; its fixed lines are sought after `start_s` (when 30 s
|
||||
or more remain)."""
|
||||
n, start = int(4 * fs), int(start_s * fs)
|
||||
lines = signals.fixed_lines(y[start:] if len(y) - start > 30 * fs else y, fs, f_max=44.0)
|
||||
verdict `gap`, `suspect` or `clean`."""
|
||||
n = int(4 * fs)
|
||||
lines = signals.fixed_lines(y, fs, f_max=44.0)
|
||||
starts = list(range(0, len(y) - n + 1, n))
|
||||
segments = [y[a : a + n] for a in starts]
|
||||
whole = [bool(np.isfinite(s).all()) for s in segments]
|
||||
@@ -317,7 +315,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
check(
|
||||
"internal-coverage",
|
||||
value=coverage,
|
||||
unit="fracción",
|
||||
unit="fraction",
|
||||
low=MIN_COVERAGE,
|
||||
abnormal=coverage < MIN_COVERAGE,
|
||||
decisive=True,
|
||||
@@ -325,7 +323,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
check(
|
||||
"bad-scalp-triage",
|
||||
value=float(len(triaged)),
|
||||
unit="electrodos",
|
||||
unit="electrodes",
|
||||
high=float(MAX_BAD_SCALP),
|
||||
abnormal=len(triaged) > MAX_BAD_SCALP,
|
||||
decisive=True,
|
||||
@@ -333,12 +331,12 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
check(
|
||||
"usable-scalp",
|
||||
value=float(len(usable)),
|
||||
unit="electrodos",
|
||||
unit="electrodes",
|
||||
low=float(MIN_SCALP),
|
||||
abnormal=len(usable) < MIN_SCALP,
|
||||
decisive=True,
|
||||
),
|
||||
check("triage-level", text=LEVELS[level], abnormal=level == NOT_ANALYZABLE, decisive=True),
|
||||
check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True),
|
||||
]
|
||||
if np.isfinite(line):
|
||||
rows.append(
|
||||
@@ -346,9 +344,6 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
|
||||
)
|
||||
)
|
||||
failed = {"triage-not-analyzable": level == NOT_ANALYZABLE,
|
||||
"few-clean-minutes": clean_pct < MIN_CLEAN_PCT,
|
||||
"few-electrodes": len(usable) < MIN_SCALP} # fmt: skip
|
||||
reasons = [reason for reason, fails in failed.items() if fails]
|
||||
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP
|
||||
bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
|
||||
return Validation(not reasons, level, bad, clean_pct, line, rows, reasons)
|
||||
return Validation(valid, level, bad, clean_pct, line, rows)
|
||||
|
||||
+47
-72
@@ -1,7 +1,7 @@
|
||||
"""Age baselines: each metric's value (and per electrode and zone) against children of the same
|
||||
age in a reference cohort.
|
||||
|
||||
Five scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
|
||||
Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
|
||||
study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets
|
||||
its own baseline, plain JSON-able data (`train`), scored by `score`:
|
||||
|
||||
@@ -14,9 +14,7 @@ its own baseline, plain JSON-able data (`train`), scored by `score`:
|
||||
minute (16 to 37 months) and its dispersion between children (negative binomial by moments,
|
||||
Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from
|
||||
the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5,
|
||||
median and p95 are the rates at those quantiles of the count in those minutes. A zone's rate
|
||||
is per minute and electrode: its exposure is its minutes times its electrodes recorded.
|
||||
A value without a score says why (`reason`): no-age, age-out-of-range or no-exposure.
|
||||
median and p95 are the rates at those quantiles of the count in those minutes.
|
||||
"""
|
||||
|
||||
import math
|
||||
@@ -33,21 +31,22 @@ MIN_EFFECTIVE = 30
|
||||
COUNT_AGES = (16.0, 37.0)
|
||||
Z_MAX = 8.0
|
||||
EXPOSURE = "minutes"
|
||||
NOT_MEASURES = ("age_months", EXPOSURE, "rhythm_near_sigma") # in a table, not baselines
|
||||
SCORE_FIELDS = ("z", "outside", "p5", "median", "p95")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Scenario:
|
||||
metric: str # the metric code it scores
|
||||
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones"
|
||||
stage: str | None = None
|
||||
counts: bool = False # a count against the `minutes` feature, not centile curves
|
||||
|
||||
|
||||
SCENARIOS = {
|
||||
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
|
||||
"eeg-spindles": Scenario("spindles", ("value", "zones")),
|
||||
"eeg-spindle-topography": Scenario("spindles", ("electrodes",)),
|
||||
"eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"),
|
||||
"eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"),
|
||||
"eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"),
|
||||
"eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"),
|
||||
"eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True),
|
||||
"eeg-gradient": Scenario("anteroposterior_gradient", ("value",)),
|
||||
}
|
||||
@@ -82,10 +81,7 @@ def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray,
|
||||
electrodes: np.ndarray) -> dict: # fmt: skip
|
||||
"""A zone's rate per minute and electrode: its count over its minutes x electrodes."""
|
||||
exposure = exposure * electrodes
|
||||
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict:
|
||||
n = np.round(values * exposure)
|
||||
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
|
||||
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
|
||||
@@ -105,21 +101,15 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray,
|
||||
|
||||
|
||||
def train(features: pd.DataFrame, scenario: str) -> dict:
|
||||
"""Feature -> baseline, for every measure of the scenario's table (NOT_MEASURES, a zone's
|
||||
electrodes and the awake spikes excepted)."""
|
||||
"""Feature -> baseline, for every feature of the scenario's table (`age_months` and the
|
||||
count's `minutes` excepted)."""
|
||||
counts = SCENARIOS[scenario].counts
|
||||
ages = features["age_months"].to_numpy(float)
|
||||
out = {}
|
||||
for name in features.columns.drop(list(NOT_MEASURES), errors="ignore"):
|
||||
if name.startswith(("zone_electrodes_", "awake_")):
|
||||
continue
|
||||
for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"):
|
||||
values = pd.to_numeric(features[name]).to_numpy(float)
|
||||
if counts:
|
||||
column = f"zone_electrodes_{name.removeprefix('zone_')}"
|
||||
electrodes = np.ones(len(features))
|
||||
if name.startswith("zone_") and column in features:
|
||||
electrodes = pd.to_numeric(features[column]).fillna(1).to_numpy(float)
|
||||
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes)
|
||||
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float))
|
||||
else:
|
||||
out[name] = _curve(values, ages)
|
||||
return out
|
||||
@@ -129,64 +119,51 @@ def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def _unscored(reason: str | None = None) -> dict:
|
||||
"""No score, and why: no-age, age-out-of-range, no-exposure (None: no value)."""
|
||||
return {**dict.fromkeys(SCORE_FIELDS), "reason": reason}
|
||||
|
||||
|
||||
def centiles(baseline: dict, age_months: float) -> dict:
|
||||
"""A curve's centiles at an age (None outside the curve)."""
|
||||
curve = pd.DataFrame(baseline["curve"]).astype(float).dropna()
|
||||
names = [name for name in QUANTILES if name in curve]
|
||||
if curve.empty or not age_months > 0:
|
||||
return dict.fromkeys(QUANTILES)
|
||||
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(age_months))
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return dict.fromkeys(QUANTILES)
|
||||
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 _unscored("age-out-of-range")
|
||||
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
|
||||
return {"z": _number(z), "outside": outside, "p5": q["p5"], "median": q["median"],
|
||||
"p95": q["p95"], "reason": None} # fmt: skip
|
||||
return {
|
||||
"z": _number(z),
|
||||
"outside": outside,
|
||||
"p5": q["p5"],
|
||||
"median": q["median"],
|
||||
"p95": q["p95"],
|
||||
}
|
||||
|
||||
|
||||
def _score_count(baseline: dict, value: float, age: float, exposure: float | None,
|
||||
electrodes: float) -> dict: # fmt: skip
|
||||
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
|
||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
rate, k = baseline["rate"], baseline["k"]
|
||||
lo, hi = baseline["ages"]
|
||||
if not lo <= age < hi:
|
||||
return _unscored("age-out-of-range")
|
||||
if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0:
|
||||
return _unscored("no-exposure")
|
||||
n, mu = float(np.round(value * exposure)), rate * exposure * electrodes
|
||||
if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi):
|
||||
return out
|
||||
n, mu = float(np.round(value * exposure)), rate * exposure
|
||||
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
|
||||
tail, at = law.sf(n - 1), law.pmf(n)
|
||||
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
|
||||
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
|
||||
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95,
|
||||
"reason": None} # fmt: skip
|
||||
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95}
|
||||
|
||||
|
||||
def score(baseline: dict, value: float | None, age_months: float | None,
|
||||
exposure: float | None = None, electrodes: float | None = None) -> dict: # fmt: skip
|
||||
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age, and the reason when it has
|
||||
none; a count against its minutes (`exposure`) and, a zone's, its electrodes."""
|
||||
def score(
|
||||
baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None
|
||||
) -> dict:
|
||||
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the
|
||||
age or the baseline's coverage is missing."""
|
||||
value, age_months = _number(value), _number(age_months)
|
||||
if value is None:
|
||||
return _unscored()
|
||||
if age_months is None:
|
||||
return _unscored("no-age")
|
||||
if value is None or age_months is None:
|
||||
return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
if baseline["kind"] == "count_rate":
|
||||
electrodes = _number(electrodes)
|
||||
return _score_count(baseline, value, age_months, _number(exposure),
|
||||
1.0 if electrodes is None else electrodes) # fmt: skip
|
||||
return _score_count(baseline, value, age_months, _number(exposure))
|
||||
return _score_curve(baseline, value, age_months)
|
||||
|
||||
|
||||
@@ -200,17 +177,15 @@ def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
|
||||
model, metric = models.get(name), metrics.get(scenario.metric)
|
||||
if model is None or metric is None:
|
||||
continue
|
||||
features = analysis.features.get(name, {})
|
||||
exposure = features.get(EXPOSURE) if scenario.counts else None
|
||||
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
|
||||
for part in scenario.parts:
|
||||
if part == "value":
|
||||
out[metric.code]["value"] = score(
|
||||
model["value"], metric.value, analysis.age_months, exposure
|
||||
)
|
||||
continue
|
||||
out[metric.code][part] = {
|
||||
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure,
|
||||
features.get(f"zone_electrodes_{key}") if part == "zones" else None)
|
||||
for key, v in getattr(metric, part).items()
|
||||
} # fmt: skip
|
||||
else:
|
||||
out[metric.code][part] = {
|
||||
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure)
|
||||
for key, v in getattr(metric, part).items()
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -1,35 +1,26 @@
|
||||
"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
|
||||
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
|
||||
|
||||
The mains notch (at the recording's mains) runs when the line stands at least 6 dB over its
|
||||
neighbourhood on the kept scalp channels. A reference study's one flat electrode can be kept
|
||||
(`keep_flat`), outside QC. The QC behind the unclean spans is the validation's window rule on the
|
||||
kept scalp channels with every mains harmonic notched (IIR, Q 30) at 0.5-45 Hz; everything
|
||||
before the stable start (`stable_start`) is unclean too.
|
||||
|
||||
Stable start: on back-to-back 10 s blocks of the scalp channels, the first block from which at
|
||||
least 90 % of the rest (6 blocks or more) stay under twice the median spread of the recording's
|
||||
second half; a later note of the recording's start (start record, inicio...) or the last note
|
||||
of its set-up (impedances, montage, calibration...) moves it there.
|
||||
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp
|
||||
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given:
|
||||
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so.
|
||||
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp
|
||||
channels at 0.5-45 Hz.
|
||||
"""
|
||||
|
||||
import unicodedata
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.checks import window_qc
|
||||
from models.tea.eeg.read import Recording
|
||||
|
||||
NOTCH_HZ = 60.0
|
||||
NOTCH_MIN_DB = 6.0
|
||||
WINDOW_S = 4.0
|
||||
STEP_S = 2.0
|
||||
START_MARKS = ("start record", "inicio", "comienzo", "begin record", "recording on",
|
||||
"start of record") # fmt: skip
|
||||
SETUP_MARKS = ("impedanc", "montaje", "montage", "electrod", "calibrac", "colocac", "prueba")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -53,54 +44,12 @@ class Prepared:
|
||||
return self.x[:, [self.names.index(name) for name in names]]
|
||||
|
||||
|
||||
def _plain(text) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFD", str(text))
|
||||
if unicodedata.category(c) != "Mn").lower() # fmt: skip
|
||||
|
||||
|
||||
def stable_start(rec: Recording) -> float:
|
||||
"""Seconds from which the recording settles (module docstring)."""
|
||||
x = rec.x[:, [rec.names.index(name) for name in rec.of("eeg")]]
|
||||
n = int(10 * rec.fs)
|
||||
blocks = [x[a : a + n] for a in range(0, len(x) - n + 1, n)]
|
||||
rms = np.array([np.median(np.std(b, axis=0)) if np.isfinite(b).all() else np.nan
|
||||
for b in blocks]) # fmt: skip
|
||||
finite = np.isfinite(rms)
|
||||
if finite.sum() < 12:
|
||||
return 0.0
|
||||
limit = 2.0 * np.median(rms[finite][finite.sum() // 2 :])
|
||||
start = 0.0
|
||||
for i in np.flatnonzero(finite):
|
||||
rest = rms[i:][np.isfinite(rms[i:])]
|
||||
if len(rest) >= 6 and np.mean(rest <= limit) >= 0.9:
|
||||
start = i * n / rec.fs
|
||||
break
|
||||
mark = None
|
||||
for onset, _, text in sorted(rec.annotations, key=lambda a: a[0]):
|
||||
if any(m in _plain(text) for m in START_MARKS):
|
||||
mark = onset
|
||||
break
|
||||
if any(m in _plain(text) for m in SETUP_MARKS):
|
||||
mark = onset
|
||||
return float(mark) if mark is not None and mark >= start else start
|
||||
|
||||
|
||||
def _harmonics_notched(x: np.ndarray, fs: float, mains_hz: float) -> np.ndarray:
|
||||
nyquist = fs / 2 * 0.98
|
||||
sos = np.vstack([np.hstack(signal.iirnotch(k * mains_hz, 30.0, fs))
|
||||
for k in range(1, 100) if k * mains_hz < nyquist]) # fmt: skip
|
||||
minimum = max(3 * (len(sos) * 2 + 1), int(fs))
|
||||
return signals.by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
|
||||
|
||||
|
||||
def prepare(rec: Recording, bad, mains_hz: float, keep_flat: bool = False) -> Prepared:
|
||||
eeg = rec.of("eeg")
|
||||
flat = [n for n in eeg if not np.nanstd(rec.x[:, rec.names.index(n)]) > 0.5]
|
||||
keep = flat if keep_flat and len(flat) == 1 else []
|
||||
scalp = [name for name in eeg if name not in bad or name in keep]
|
||||
def prepare(rec: Recording, bad) -> Prepared:
|
||||
scalp = [name for name in rec.of("eeg") if name not in bad]
|
||||
x = rec.x[:, [rec.names.index(name) for name in scalp]]
|
||||
if np.nanmedian(signals.line_db(x, rec.fs, mains_hz)) >= NOTCH_MIN_DB:
|
||||
x = signals.notch(x, rec.fs, mains_hz, width=1.5)
|
||||
if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB:
|
||||
x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5)
|
||||
gaps = ~np.isfinite(x).all(axis=1)
|
||||
y = signals.bandpass(x, rec.fs, 0.5, 100.0)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row
|
||||
@@ -108,10 +57,10 @@ def prepare(rec: Recording, bad, mains_hz: float, keep_flat: bool = False) -> Pr
|
||||
# Kept as the reference analysis read it from MNE: through volts and back, column-major in
|
||||
# memory (the layout decides the order of float sums along time).
|
||||
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
|
||||
raw = rec.x[:, [rec.names.index(name) for name in scalp if name not in keep]]
|
||||
qc = signals.bandpass(_harmonics_notched(raw, rec.fs, mains_hz), rec.fs, 0.5, 45.0)
|
||||
start = stable_start(rec)
|
||||
unclean = tuple((float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs, start)
|
||||
if v != "clean" or t0 < start) # fmt: skip
|
||||
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
|
||||
qc[gaps] = np.nan
|
||||
unclean = tuple(
|
||||
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
|
||||
)
|
||||
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
|
||||
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
|
||||
|
||||
+3
-47
@@ -75,58 +75,14 @@ class Recording:
|
||||
return [name for name in self.names if kind(name) in kinds]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Header:
|
||||
"""What an EDF's header says of its patient and recording (EDF+ fields; None when not
|
||||
given)."""
|
||||
|
||||
patient_code: str | None
|
||||
sex: str | None
|
||||
birthdate: date | None
|
||||
start_date: date | None
|
||||
record_code: str | None
|
||||
duration_s: float | None
|
||||
channels: int
|
||||
|
||||
|
||||
def _open(edf: bytes) -> edfio.Edf:
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
if len(edf) < 256:
|
||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||
try:
|
||||
opened = edfio.read_edf(edf, lazy_load_data=True)
|
||||
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 int(edf[236:244]) > opened.num_data_records:
|
||||
raise FileNotValid("the EDF signal data is truncated")
|
||||
return opened
|
||||
|
||||
|
||||
def _given(read) -> object | None:
|
||||
"""An EDF+ subfield, None when not given ('X' or not compliant)."""
|
||||
try:
|
||||
value = read()
|
||||
except ValueError:
|
||||
return None
|
||||
return None if value in ("", "X") else value
|
||||
|
||||
|
||||
def header(edf: bytes) -> Header:
|
||||
opened = _open(edf)
|
||||
start = _given(lambda: opened.recording.startdate)
|
||||
return Header(
|
||||
patient_code=_given(lambda: opened.patient.code),
|
||||
sex=sex if (sex := _given(lambda: opened.patient.sex)) in ("F", "M") else None,
|
||||
birthdate=_given(lambda: opened.patient.birthdate),
|
||||
start_date=None if start == UNKNOWN_START else start,
|
||||
record_code=_given(lambda: opened.recording.hospital_administration_code),
|
||||
duration_s=opened.duration,
|
||||
channels=opened.num_signals,
|
||||
)
|
||||
|
||||
|
||||
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 not signals:
|
||||
raise FileNotValid("the EDF declares zero signals")
|
||||
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
|
||||
|
||||
+17
-16
@@ -1,11 +1,11 @@
|
||||
"""A reference cohort the age baselines can be trained on (a folder of EDFs of children of 16
|
||||
to 36 months, such as HK1K, the Helsinki EEGs) instead of the site's own.
|
||||
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
|
||||
children of 16 to 36 months, recorded on 50 Hz mains.
|
||||
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (`path`, relative
|
||||
to the folder, and `age` in months, kept to one decimal); keys are the folder's name and a
|
||||
position in path order, never file names. `measure` analyses each study as a hospital EEG (at
|
||||
the cohort's mains, with the table's age, keeping a single flat electrode) in worker
|
||||
processes; `tables` gives each scenario's training table from the valid studies.
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
||||
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
||||
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
||||
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
|
||||
from the valid studies.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
@@ -16,23 +16,25 @@ from models import cluster
|
||||
from models.tea.eeg.analysis import analyze
|
||||
from models.tea.eeg.curves import SCENARIOS
|
||||
|
||||
NAME = "hk1k"
|
||||
MAINS_HZ = 50.0
|
||||
AGES = (16.0, 36.0)
|
||||
|
||||
|
||||
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
|
||||
"""(key, path, age in months) of each EDF with an age within `ages`."""
|
||||
table = pd.read_csv(ages_table)
|
||||
months = dict(zip(table["path"].astype(str), table["age"].astype(float), strict=True))
|
||||
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
|
||||
found = []
|
||||
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
|
||||
age = months.get(path.relative_to(folder).as_posix())
|
||||
age = round(float(years[path.name] * 12), 1) if path.name in years else None
|
||||
if age is not None and age == age and ages[0] <= age <= ages[1]:
|
||||
found.append((path, round(age, 1)))
|
||||
return [(f"{Path(folder).name}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||
found.append((path, age))
|
||||
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||
|
||||
|
||||
def _one(key: str, edf: bytes, age: float, mains_hz: float) -> dict:
|
||||
a = analyze(edf, age_months=age, mains_hz=mains_hz, keep_flat=True)
|
||||
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,
|
||||
@@ -42,12 +44,11 @@ def _one(key: str, edf: bytes, age: float, mains_hz: float) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def measure(studies, mains_hz: float) -> list[dict]:
|
||||
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, mains_hz)
|
||||
for key, path, age in studies)) # fmt: skip
|
||||
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]:
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A
|
||||
filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum
|
||||
stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge
|
||||
padding) and so are the periodograms (`periodogram`, a symmetric Hann window). The mains
|
||||
padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains
|
||||
notch, the fixed-line search and the dominant peak are small rules of their own: no library
|
||||
computes the same thing (MNE's notch filters change the signal by microvolts).
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from mne.time_frequency import psd_array_welch
|
||||
from scipy import signal
|
||||
from scipy.ndimage import median_filter
|
||||
|
||||
@@ -84,8 +85,9 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
|
||||
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""One Hann periodogram (density, mean removed) of each segment along the last axis:
|
||||
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
|
||||
window = np.hanning(segments.shape[-1])
|
||||
return signal.periodogram(segments, fs, window=window, detrend="constant", axis=-1)
|
||||
n = segments.shape[-1]
|
||||
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
|
||||
return f, power
|
||||
|
||||
|
||||
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
|
||||
|
||||
+82
-37
@@ -1,11 +1,9 @@
|
||||
"""The state of each grid window: wake, drowsy or sleep.
|
||||
"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3).
|
||||
|
||||
Notes: a note's state is the first whose cues its text holds (lower case, accents removed, ñ
|
||||
read as n): a cue is a word prefix (`hipervent`) or, for short ones, a whole word (`hv`, `n2`);
|
||||
a note that ends something (off, fin, end, stop) has none. It lasts its duration or, without
|
||||
one, until the next note with a state or 60 s; pieces under 1 s are dropped and the stretches
|
||||
between notes are `unmarked`. Crying, movement, disconnection, photic stimulation and
|
||||
hyperventilation are masked.
|
||||
Notes: a note's state is the first whose words its text contains (lower case, accents removed,
|
||||
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s;
|
||||
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement,
|
||||
disconnection, photic stimulation and hyperventilation are masked.
|
||||
|
||||
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
|
||||
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
|
||||
@@ -13,10 +11,13 @@ muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is s
|
||||
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
|
||||
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
|
||||
posterior electrode leaves that feature out of the mean.
|
||||
|
||||
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
|
||||
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
|
||||
20 % of the 30 s centred on it, else N2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
|
||||
@@ -26,29 +27,18 @@ from models.tea.eeg import signals
|
||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
|
||||
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
|
||||
# (state, its word prefixes, its whole words), in the order a note is matched
|
||||
NOTE_WORDS = [
|
||||
("photic", ("fotic", "photic", "flash", "estimulacion luminosa"), ()),
|
||||
("hyperventilation", ("hipervent", "hypervent"), ("hv",)),
|
||||
("eyes_open", ("ojos abiertos", "eyes open", "open eyes", "opens eyes", "abre ojos",
|
||||
"abre los ojos", "abrio ojos", "abrio los ojos", "apertura de ojos",
|
||||
"apertura ocular"), ("oa", "eo")),
|
||||
("eyes_closed", ("ojos cerrados", "eyes closed", "close eyes", "closes eyes", "eyes shut",
|
||||
"cierra ojos", "cierra los ojos", "cerro ojos", "cerro los ojos",
|
||||
"cierre de ojos", "cierre ocular"), ("oc", "ec")),
|
||||
("sleep", ("sueno", "dormido", "dormida", "sleep", "asleep", "somnol", "husos", "spindle"),
|
||||
("fase i", "fase ii", "fase iii", "n1", "n2", "n3")),
|
||||
("awake", ("despierta", "despierto", "arousal", "vigilia"), ()),
|
||||
("crying", ("llanto", "llora", "cry"), ()),
|
||||
("movement", ("movimiento", "movement", "artefacto de movimiento"), ()),
|
||||
("feeding", ("alimenta", "biberon", "lactancia"), ("come", "comer", "comio", "comiendo")),
|
||||
] # fmt: skip
|
||||
END = re.compile(r"\b(off|fin|end|stop)\b")
|
||||
PATTERNS = [
|
||||
(state, re.compile("|".join([*(rf"\b{re.escape(p)}" for p in prefixes),
|
||||
*(rf"\b{re.escape(w)}\b" for w in words)])))
|
||||
for state, prefixes, words in NOTE_WORDS
|
||||
] # fmt: skip
|
||||
NOTE_WORDS = {
|
||||
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"),
|
||||
"hyperventilation": ("hv", "hipervent", "hypervent"),
|
||||
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
|
||||
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
|
||||
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
|
||||
"n1", "n2", "n3"),
|
||||
"awake": ("despierta", "despierto", "arousal", "vigilia"),
|
||||
"crying": ("llanto", "llora", "cry"),
|
||||
"movement": ("movimiento", "movement", "artefacto de movimiento"),
|
||||
"feeding": ("come", "alimenta", "biberon", "lactancia"),
|
||||
} # fmt: skip
|
||||
EXCLUDED = ("crying", "movement", "disconnection")
|
||||
MASKED = (*EXCLUDED, "photic", "hyperventilation")
|
||||
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
|
||||
@@ -56,14 +46,18 @@ BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16)
|
||||
"beta": (16, 30), "high": (20, 40)} # fmt: skip
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
CENTRAL = ("C3", "C4", "Cz")
|
||||
FRONTAL = ("F3", "F4", "Fz")
|
||||
|
||||
|
||||
def note_state(text: str) -> str | None:
|
||||
plain = "".join(c for c in unicodedata.normalize("NFD", str(text or ""))
|
||||
if unicodedata.category(c) != "Mn").lower().strip() # fmt: skip
|
||||
if END.search(plain):
|
||||
return None
|
||||
return next((state for state, pattern in PATTERNS if pattern.search(plain)), None)
|
||||
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
|
||||
plain = "".join(
|
||||
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
|
||||
)
|
||||
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
|
||||
return next(
|
||||
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
|
||||
)
|
||||
|
||||
|
||||
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
|
||||
@@ -128,7 +122,6 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
|
||||
if not starts:
|
||||
return [], {}
|
||||
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
|
||||
power *= fs * (np.hanning(n) ** 2).sum() / 2 # the reference's scale (hk1k_state.json)
|
||||
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
|
||||
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
|
||||
central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names))))
|
||||
@@ -176,3 +169,55 @@ def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
|
||||
by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True))
|
||||
out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts]
|
||||
return out
|
||||
|
||||
|
||||
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
|
||||
"""(onset s, duration s) of the slow waves of one channel."""
|
||||
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
|
||||
sign = np.sign(y)
|
||||
sign[sign == 0] = 1
|
||||
crossings = np.flatnonzero(np.diff(sign) != 0) + 1
|
||||
waves = []
|
||||
for j, c0 in enumerate(crossings):
|
||||
if not y[c0] < 0:
|
||||
continue
|
||||
if j + 2 >= len(crossings):
|
||||
break
|
||||
c1, c2 = crossings[j + 1], crossings[j + 2]
|
||||
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
|
||||
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
|
||||
continue
|
||||
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
|
||||
if 75.0 <= p2p <= 300.0:
|
||||
waves.append((round(c0 / fs, 3), round(total, 3)))
|
||||
return waves
|
||||
|
||||
|
||||
def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
|
||||
if not waves:
|
||||
return np.empty((0, 2))
|
||||
a = np.array([onset for onset, _ in waves])
|
||||
b = a + np.array([length for _, length in waves])
|
||||
order = np.argsort(a)
|
||||
out = [[a[order[0]], b[order[0]]]]
|
||||
for i in order[1:]:
|
||||
if a[i] <= out[-1][1]:
|
||||
out[-1][1] = max(out[-1][1], b[i])
|
||||
else:
|
||||
out.append([a[i], b[i]])
|
||||
return np.array(out)
|
||||
|
||||
|
||||
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
|
||||
"""`N3` or `N2` per sleep window (`` elsewhere)."""
|
||||
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
|
||||
covered = _merged(waves)
|
||||
out = np.full(len(prep.starts), "", dtype=object)
|
||||
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
|
||||
if label != "sleep":
|
||||
continue
|
||||
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
|
||||
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
|
||||
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
|
||||
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
|
||||
return out
|
||||
|
||||
+29
-71
@@ -4,10 +4,7 @@ the clean minutes of sleep.
|
||||
Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an
|
||||
excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz
|
||||
power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is
|
||||
one. Each kept window adds its 2 s to the state of its midpoint; each left out adds its minutes
|
||||
to each reason (gap, state, mixed-states, muscle, frozen). A time takes the state of the grid
|
||||
window holding it or, outside every one, that of the nearest within 30 s (`transition` when
|
||||
the windows on either side differ).
|
||||
one. Each kept window adds its 2 s to the state of its midpoint.
|
||||
|
||||
Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD,
|
||||
20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both
|
||||
@@ -19,9 +16,8 @@ and width. A useful discharge has field and is not a vertex wave (asleep, max on
|
||||
slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on
|
||||
Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair).
|
||||
|
||||
Rate: useful discharges in sleep per sleep minute to 3 decimals, and awake (wake or drowsy) per
|
||||
awake minute; per electrode (its own maxima) and per zone (its electrodes' sum, with how many
|
||||
it has), per minute to 4 decimals.
|
||||
Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode
|
||||
(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
@@ -37,13 +33,12 @@ from models.tea.eeg.spindles import ZONES
|
||||
|
||||
ELECTRODES = tuple(NEIGHBOURS)
|
||||
GATE_S = 2.0
|
||||
INHERIT_S = 30.0
|
||||
VERTEX = ("Cz", "Fz", "Pz")
|
||||
POSTS = ("O1", "O2")
|
||||
OCULAR = ("Fp1", "Fp2", "F7", "F8")
|
||||
POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"}
|
||||
LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4"))
|
||||
ASLEEP = ("sleep",)
|
||||
ASLEEP = ("N2", "N3", "sleep")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -52,31 +47,6 @@ class Spikes:
|
||||
electrodes: dict[str, float]
|
||||
zones: dict[str, float]
|
||||
minutes: float # clean sleep minutes, the rate's exposure
|
||||
rejected: dict[str, float] # minutes the gate left out, by reason
|
||||
awake_rate: float
|
||||
awake_minutes: float
|
||||
zone_electrodes: dict[str, int] # per zone, its electrodes recorded
|
||||
|
||||
|
||||
def _states(labelled, duration_s: float) -> np.ndarray:
|
||||
"""The state every 0.5 s: its window's, or the nearest window's within INHERIT_S."""
|
||||
t = np.arange(0.0, duration_s, 0.5)
|
||||
out = np.full(len(t), "unlabelled", dtype=object)
|
||||
for t0, t1, label in labelled:
|
||||
out[(out == "unlabelled") & (t0 <= t) & (t < t1)] = label
|
||||
direct = np.flatnonzero(out != "unlabelled")
|
||||
if not len(direct):
|
||||
return out
|
||||
missing = np.flatnonzero((out == "unlabelled") & (t >= t[direct[0]]))
|
||||
j = np.searchsorted(direct, missing)
|
||||
before, after = direct[np.maximum(j - 1, 0)], direct[np.minimum(j, len(direct) - 1)]
|
||||
to_before = np.where(j > 0, t[missing] - t[before], np.inf)
|
||||
to_after = np.where(j < len(direct), t[after] - t[missing], np.inf)
|
||||
labels = np.where(to_before <= to_after, out[before], out[after])
|
||||
labels[(j > 0) & (j < len(direct)) & (out[before] != out[after])] = "transition"
|
||||
close = np.minimum(to_before, to_after) <= INHERIT_S
|
||||
out[missing[close]] = labels[close]
|
||||
return out
|
||||
|
||||
|
||||
def _mad(v: np.ndarray) -> float:
|
||||
@@ -86,34 +56,29 @@ def _mad(v: np.ndarray) -> float:
|
||||
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
|
||||
|
||||
|
||||
def _gate(x: np.ndarray, fs: float, intervals) -> tuple[list[tuple[float, float]], dict]:
|
||||
"""(start, end) s of the 2 s windows the detector reads, and the minutes left out by
|
||||
reason."""
|
||||
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
|
||||
"""(start, end) s of the 2 s windows the detector reads."""
|
||||
n = int(GATE_S * fs)
|
||||
top = min(45, fs / 2 * 0.9)
|
||||
lines = signals.fixed_lines(x, fs, f_max=top)
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
taper = np.hanning(n)[:, None]
|
||||
kept, rejected = [], {}
|
||||
kept = []
|
||||
for a in range(0, len(x) - n + 1, n):
|
||||
t0, t1 = a / fs, a / fs + GATE_S
|
||||
state, mixed = window_note(t0, t1, intervals)
|
||||
segment = x[a : a + n]
|
||||
reasons = ["gap"]
|
||||
if np.isfinite(segment).all():
|
||||
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
||||
power = power.mean(axis=1)
|
||||
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
||||
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
||||
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
|
||||
failed = {"state": state in EXCLUDED, "mixed-states": mixed,
|
||||
"muscle": high / max(low, 1e-12) > 1.5, "frozen": frozen > 0.5} # fmt: skip
|
||||
reasons = [reason for reason, fails in failed.items() if fails]
|
||||
if not reasons:
|
||||
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
|
||||
continue
|
||||
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
||||
power = power.mean(axis=1)
|
||||
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
||||
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
||||
muscle = float(high / max(low, 1e-12))
|
||||
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
|
||||
if not (muscle > 1.5 or frozen > 0.5):
|
||||
kept.append((round(t0, 2), round(t1, 2)))
|
||||
for reason in reasons:
|
||||
rejected[reason] = rejected.get(reason, 0.0) + GATE_S / 60.0
|
||||
return kept, {reason: round(minutes, 4) for reason, minutes in rejected.items()}
|
||||
return kept
|
||||
|
||||
|
||||
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
|
||||
@@ -224,23 +189,20 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
||||
if label in ("wake", "drowsy", "sleep")
|
||||
]
|
||||
|
||||
grid = _states(labelled, prep.duration_s)
|
||||
|
||||
def state_at(t: np.ndarray) -> np.ndarray:
|
||||
out = np.full(len(t), "unlabelled", dtype=object)
|
||||
index = np.floor(t / 0.5).astype(int)
|
||||
inside = (t >= 0) & (index < len(grid))
|
||||
out[inside] = grid[index[inside]]
|
||||
"""The state of the first labelled window holding each time."""
|
||||
out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
|
||||
for t0, t1, label in labelled:
|
||||
hit = open_ & (t0 <= t) & (t < t1)
|
||||
out[hit], open_ = label, open_ & ~hit
|
||||
return out
|
||||
|
||||
gate, rejected = _gate(x, fs, intervals)
|
||||
gate = _gate(x, fs, intervals)
|
||||
minutes = {}
|
||||
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
|
||||
for (t0, t1), state in zip(gate, middles, strict=True):
|
||||
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
|
||||
sleep_minutes = float(minutes.get("sleep", 0.0))
|
||||
awake_minutes = float(minutes.get("wake", 0.0) + minutes.get("drowsy", 0.0))
|
||||
awake = 0
|
||||
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
|
||||
counts = dict.fromkeys(channels, 0)
|
||||
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
|
||||
if candidates and gate:
|
||||
@@ -253,22 +215,18 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
||||
if len(c):
|
||||
c = c.assign(field=_field(c), state=state_at(c.t.to_numpy()))
|
||||
found = _merge(c)
|
||||
found = found[found.useful & (found.field > 0)]
|
||||
awake = int(found.state.isin(("wake", "drowsy")).sum())
|
||||
found = found[found.state == "sleep"]
|
||||
found = found[found.useful & (found.field > 0) & (found.state == "sleep")]
|
||||
for channel, n in found.channel.value_counts().items():
|
||||
counts[channel] = int(n)
|
||||
rate = round(sum(counts.values()) / sleep_minutes, 3) if sleep_minutes > 0 else np.nan
|
||||
awake_rate = round(awake / awake_minutes, 3) if awake_minutes > 0 else np.nan
|
||||
rounded = round(sleep_minutes, 2)
|
||||
rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan
|
||||
electrodes = {
|
||||
e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan
|
||||
for e in ELECTRODES
|
||||
}
|
||||
zones, zone_electrodes = {}, {}
|
||||
zones = {}
|
||||
for zone, members in ZONES.items():
|
||||
present = [e for e in members if e in counts]
|
||||
zone_electrodes[zone] = len(present)
|
||||
total = sum(counts[e] for e in present)
|
||||
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
|
||||
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4), rejected, awake_rate,
|
||||
round(awake_minutes, 4), zone_electrodes) # fmt: skip
|
||||
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
|
||||
|
||||
+15
-23
@@ -1,10 +1,10 @@
|
||||
"""Sleep spindles (NREM sleep, unstaged): their density, per zone, and the enhancement of the
|
||||
"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the
|
||||
sigma envelope per electrode.
|
||||
|
||||
Detection runs on the frontal, central and parietal electrodes over the sleep windows (only when
|
||||
they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
|
||||
Detection runs on the frontal, central and parietal electrodes over the windows of the stage
|
||||
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
|
||||
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
|
||||
from the sleep's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
|
||||
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
|
||||
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
|
||||
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
|
||||
envelope peaks 3 x over the median.
|
||||
@@ -12,8 +12,7 @@ envelope peaks 3 x over the median.
|
||||
Density: spindles per minute and searched channel (NaN when none were found); per zone, the
|
||||
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
|
||||
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
|
||||
the episode ± 0.25 s, over the median envelope in sleep. A posterior rhythm within 1.5 Hz of the
|
||||
sigma band (`near_sigma`) is noted: its alpha can pass for spindles.
|
||||
the episode ± 0.25 s, over the median envelope in sleep.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
@@ -26,8 +25,6 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
|
||||
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
|
||||
SIGMA = (11.0, 16.0)
|
||||
RHYTHM_MARGIN_HZ = 1.5
|
||||
MIN_MINUTES = 1
|
||||
ZONES = {
|
||||
"frontal_left": ("Fp1", "F3", "F7"),
|
||||
"frontal_right": ("Fp2", "F4", "F8"),
|
||||
@@ -44,12 +41,7 @@ ZONES = {
|
||||
class Spindles:
|
||||
events: list[tuple[float, float, str]] # (onset s, duration s, channel)
|
||||
minutes: float
|
||||
channels: list[str] # the channels searched (none when under a minute of sleep)
|
||||
rhythm_near_sigma: bool = False
|
||||
|
||||
|
||||
def near_sigma(posterior_rhythm: float) -> bool:
|
||||
return bool(posterior_rhythm > SIGMA[0] - RHYTHM_MARGIN_HZ)
|
||||
channels: list[str] # the channels searched (none when under a minute of the stage)
|
||||
|
||||
|
||||
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
@@ -100,31 +92,31 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
|
||||
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
|
||||
|
||||
|
||||
def detect(prep: Prepared, states: np.ndarray) -> Spindles:
|
||||
"""The spindles in the grid windows in sleep."""
|
||||
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
|
||||
"""The spindles in the grid windows staged `stage`."""
|
||||
fs, n = prep.fs, int(WINDOW_S * prep.fs)
|
||||
asleep = np.zeros(len(prep.x), bool)
|
||||
for start, state in zip(prep.starts, states, strict=True):
|
||||
if state == "sleep":
|
||||
for start, s in zip(prep.starts, staged, strict=True):
|
||||
if s == stage:
|
||||
a = int(round(float(start) * fs))
|
||||
asleep[a : a + n] = True
|
||||
minutes = float(asleep.sum() / fs / 60)
|
||||
names = prep.columns([c for c in prep.names if c in CHANNELS])
|
||||
if minutes < MIN_MINUTES or not names:
|
||||
if minutes < 1 or not names:
|
||||
return Spindles([], minutes, [])
|
||||
x = prep.data(names)
|
||||
y, envelope = _envelope(x, fs)
|
||||
events = []
|
||||
for i, name in enumerate(names):
|
||||
in_sleep = np.where(asleep, envelope[:, i], np.nan)
|
||||
values = in_sleep[np.isfinite(in_sleep)]
|
||||
in_stage = np.where(asleep, envelope[:, i], np.nan)
|
||||
values = in_stage[np.isfinite(in_stage)]
|
||||
if len(values) < fs * 30:
|
||||
continue
|
||||
median = float(np.median(values)) or 1e-9
|
||||
core = max(float(np.percentile(values, 95)), 3 * median)
|
||||
extent = max(float(np.percentile(values, 70)), 1.6 * median)
|
||||
finite = np.isfinite(in_sleep)
|
||||
for a, b in _segments(finite & (in_sleep > core), finite & (in_sleep > extent), fs):
|
||||
finite = np.isfinite(in_stage)
|
||||
for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs):
|
||||
if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3:
|
||||
events.append((round(a / fs, 3), round((b - a) / fs, 3), name))
|
||||
return Spindles(events, minutes, names)
|
||||
|
||||
+23
-27
@@ -5,7 +5,6 @@ analysed EEG against the child's age. The math is the old platform's, proved on
|
||||
cohort by models/tests/test_eeg.py."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
@@ -27,8 +26,8 @@ GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_r
|
||||
|
||||
|
||||
class Baseline(mlflow.pyfunc.PythonModel):
|
||||
"""An age curve as MLflow serves it: (value, age_months, exposure, electrodes) rows in,
|
||||
their z, outside, p5, median, p95 and reason out, for one of its features."""
|
||||
"""An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z,
|
||||
outside, p5, median and p95 out, for one of its features."""
|
||||
|
||||
def __init__(self, scenario: str, baseline: dict):
|
||||
self.scenario, self.baseline = scenario, baseline
|
||||
@@ -37,8 +36,7 @@ class Baseline(mlflow.pyfunc.PythonModel):
|
||||
feature = (params or {}).get("feature", "value")
|
||||
rows = model_input.to_dict("records")
|
||||
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
|
||||
r.get("age_months"), r.get("exposure"),
|
||||
r.get("electrodes"))
|
||||
r.get("age_months"), r.get("exposure"))
|
||||
for r in rows]) # fmt: skip
|
||||
|
||||
|
||||
@@ -123,8 +121,9 @@ def _score_curve(name: str) -> int | None:
|
||||
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
|
||||
if metric is None:
|
||||
continue
|
||||
features = one["features"].get(name) or {}
|
||||
exposure = features.get(curves.EXPOSURE) if scenario.counts else None
|
||||
exposure = (
|
||||
(one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None
|
||||
)
|
||||
for part in scenario.parts:
|
||||
sites = {"": metric["value"]} if part == "value" else metric[part]
|
||||
prefix = "" if part == "value" else curves.PREFIX[part]
|
||||
@@ -132,8 +131,7 @@ def _score_curve(name: str) -> int | None:
|
||||
feature = "value" if part == "value" else prefix + site
|
||||
if feature not in baseline:
|
||||
continue
|
||||
electrodes = features.get(f"zone_electrodes_{site}") if part == "zones" else None
|
||||
s = curves.score(baseline[feature], value, one["age_months"], exposure, electrodes)
|
||||
s = curves.score(baseline[feature], value, one["age_months"], exposure)
|
||||
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
|
||||
"scenario": name, "model": label, "metric": scenario.metric,
|
||||
"part": part, "site": site or None, **s}) # fmt: skip
|
||||
@@ -153,8 +151,8 @@ class Association(mlflow.pyfunc.PythonModel):
|
||||
|
||||
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, the z of each biomarker and whether it shows spikes; fitted on each
|
||||
child's first EEG with any, every EEG scored (her own refitted without her)."""
|
||||
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):
|
||||
@@ -165,20 +163,18 @@ def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.Data
|
||||
css = None
|
||||
if evaluated and r["birth_date"]:
|
||||
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
|
||||
scored = ados2.score(row, date.fromisoformat(r["birth_date"]))
|
||||
css = scored and scored.css
|
||||
spikes = json.loads(r["features"] or "{}").get("eeg-spikes", {})
|
||||
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_")},
|
||||
**association.spikes_any(spikes)}) # fmt: skip
|
||||
**{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_", "spikes_any_"))]
|
||||
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()
|
||||
return scored[with_z].drop_duplicates("person").reset_index(drop=True), scored
|
||||
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:
|
||||
@@ -191,10 +187,8 @@ def _train_association(as_of: date | None = None) -> int:
|
||||
pairs = association.associations(fitted)
|
||||
estimated = [p for p in pairs if p["odds_ratio"] is not None]
|
||||
technical = {
|
||||
"model": ASSOCIATION, "version": relation.VERSION,
|
||||
"method": "Firth logistic (items) / cumulative logit (CSS, and composites with few "
|
||||
"events), adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg "
|
||||
"q within each biomarker; each child scored leave-one-out",
|
||||
"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),
|
||||
@@ -224,11 +218,13 @@ def _score_association() -> int | None:
|
||||
"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, how many of a
|
||||
if not scored.empty: # composite's items are altered, or the CSS
|
||||
for r in fitted["rows"]:
|
||||
level = association.outcome(scored, r)[1].tolist()
|
||||
observed[relation.outcome_code(r)] = dict(zip(scored["key"], level, strict=True))
|
||||
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"])
|
||||
|
||||
@@ -1,287 +0,0 @@
|
||||
"""The two models the EEG–ADOS-2 association fits (models.tea.association), adjusted for
|
||||
age and module (core.tea.association.ADJUST):
|
||||
|
||||
- Firth's penalised logistic regression of an event (its odds ratio, a 95 % profile-
|
||||
likelihood interval and a likelihood-ratio p); its probabilities with the FLIC intercept, so
|
||||
they average to the observed rate;
|
||||
- the cumulative logit of a level, P(level >= high) its probability.
|
||||
Each fit keeps a scoring `state`: what `probability` needs, for any child and the reference
|
||||
child (z = 0, the cohort's mean age, the commonest module)."""
|
||||
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import optimize, stats
|
||||
from scipy.special import expit
|
||||
|
||||
from core.tea.association import ADJUST
|
||||
|
||||
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
|
||||
MIN_ROWS = 8
|
||||
TOO_FEW = "too few data or no variation"
|
||||
SEPARATION = "does not converge (separation)"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Design:
|
||||
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
|
||||
the cohort's mean and each categorical one against its commonest level."""
|
||||
|
||||
predictor: str
|
||||
numeric: dict[str, float] = field(default_factory=dict)
|
||||
categorical: dict[str, list[str]] = field(default_factory=dict)
|
||||
reference: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
|
||||
d = cls(predictor)
|
||||
for a in (a for a in ADJUST if a in t):
|
||||
v = t[a]
|
||||
if pd.api.types.is_numeric_dtype(v):
|
||||
if v.astype(float).std() > 0:
|
||||
d.numeric[a] = float(v.astype(float).mean())
|
||||
continue
|
||||
commonest = v.value_counts().index[0]
|
||||
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
|
||||
if levels:
|
||||
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
|
||||
return d
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return [
|
||||
"intercept",
|
||||
self.predictor,
|
||||
*self.numeric,
|
||||
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
|
||||
]
|
||||
|
||||
def matrix(self, t: pd.DataFrame) -> np.ndarray:
|
||||
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
|
||||
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()]
|
||||
known = np.ones(len(t), bool)
|
||||
for a, levels in self.categorical.items():
|
||||
v = t[a].astype(str)
|
||||
cols += [(v == x).to_numpy(float) for x in levels]
|
||||
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy()
|
||||
X = np.column_stack(cols)
|
||||
X[~known] = np.nan
|
||||
return X
|
||||
|
||||
def state(self) -> dict:
|
||||
return {
|
||||
"predictor": self.predictor,
|
||||
"numeric": self.numeric,
|
||||
"categorical": self.categorical,
|
||||
"reference": self.reference,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_state(cls, s: dict) -> "Design":
|
||||
return cls(
|
||||
s["predictor"],
|
||||
dict(s["numeric"]),
|
||||
{k: list(v) for k, v in s["categorical"].items()},
|
||||
dict(s["reference"]),
|
||||
)
|
||||
|
||||
|
||||
# Firth: the log-likelihood penalised by half the log-determinant of the information.
|
||||
def _penalised(b, X, y) -> float:
|
||||
eta = X @ b
|
||||
w = expit(eta) * (1 - expit(eta))
|
||||
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
|
||||
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
|
||||
|
||||
|
||||
def _gradient(b, X, y):
|
||||
"""The penalised score and the information at `b`."""
|
||||
p = expit(X @ b)
|
||||
w = p * (1 - p)
|
||||
info = X.T @ (X * w[:, None])
|
||||
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||
return X.T @ (y - p + leverage * (0.5 - p)), info
|
||||
|
||||
|
||||
def _newton(X, y, max_iter=200, tol=1e-10):
|
||||
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
|
||||
b = np.zeros(X.shape[1])
|
||||
best = _penalised(b, X, y)
|
||||
for _ in range(max_iter):
|
||||
score, info = _gradient(b, X, y)
|
||||
step, t = np.linalg.solve(info, score), 1.0
|
||||
while t > 1e-8:
|
||||
trial = _penalised(b + t * step, X, y)
|
||||
if trial >= best - 1e-12:
|
||||
break
|
||||
t /= 2
|
||||
b, best = b + t * step, trial
|
||||
if np.max(np.abs(t * step)) < tol:
|
||||
break
|
||||
return b, best
|
||||
|
||||
|
||||
def _firth_profile(value, j, X, y, start) -> float:
|
||||
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
|
||||
free = [k for k in range(X.shape[1]) if k != j]
|
||||
|
||||
def negative(bf):
|
||||
b = np.empty(X.shape[1])
|
||||
b[free], b[j] = bf, value
|
||||
v = _penalised(b, X, y)
|
||||
if not np.isfinite(v):
|
||||
return 1e10, np.zeros(len(free))
|
||||
return -v, -_gradient(b, X, y)[0][free]
|
||||
|
||||
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
||||
|
||||
|
||||
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
||||
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
|
||||
each side of `centre`, searched in steps of `scale` (infinite if never)."""
|
||||
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
||||
limits = []
|
||||
for sign in (-1, 1):
|
||||
previous, limit = centre, sign * np.inf
|
||||
for k in range(1, 80):
|
||||
v = centre + sign * scale * k
|
||||
if drop(v) > 0:
|
||||
limit = optimize.brentq(drop, min(previous, v), max(previous, v))
|
||||
break
|
||||
previous = v
|
||||
limits.append(limit)
|
||||
return limits[0], limits[1]
|
||||
|
||||
|
||||
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
|
||||
return {
|
||||
"model": model,
|
||||
"n": n,
|
||||
"coef": round(float(coef), 4),
|
||||
"odds_ratio": round(float(np.exp(coef)), 4),
|
||||
"ci_low": round(float(np.exp(low)), 4),
|
||||
"ci_high": round(float(np.exp(high)), 4),
|
||||
"p": round(p, 5),
|
||||
"adjusted_for": ", ".join(design.names[2:]),
|
||||
"reason": "",
|
||||
**extra,
|
||||
"state": {"design": design.state(), **state},
|
||||
}
|
||||
|
||||
|
||||
def rows(t: pd.DataFrame, outcome: str, predictor: str) -> pd.DataFrame:
|
||||
return t[[outcome, predictor, *(a for a in ADJUST if a in t)]].dropna()
|
||||
|
||||
|
||||
def firth_fit(d: pd.DataFrame, outcome: str, predictor: str):
|
||||
"""Firth's fit on complete rows `d`: the design, its matrix, the coefficients, the
|
||||
penalised maximum and the scoring state (FLIC: the intercept refitted so the
|
||||
probabilities add up to the events); None when it can't be fitted."""
|
||||
y = d[outcome].to_numpy(float)
|
||||
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
|
||||
return None
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)
|
||||
b, top = _newton(X, y)
|
||||
eta = X[:, 1:] @ b[1:]
|
||||
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
state = {"design": design.state(), "beta": [float(v) for v in b[1:]],
|
||||
"intercept": float(intercept)} # fmt: skip
|
||||
return design, X, y, b, top, state
|
||||
|
||||
|
||||
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
|
||||
d = rows(t, outcome, predictor)
|
||||
out = {"model": "firth", "n": len(d), "events": int(d[outcome].sum())}
|
||||
if (fitted := firth_fit(d, outcome, predictor)) is None:
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design, X, y, b, top, state = fitted
|
||||
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))
|
||||
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 _cumulative(X, y, K, fixed=None):
|
||||
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
||||
if fixed is None:
|
||||
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
||||
return r.x, float(r.fun)
|
||||
j, value = fixed
|
||||
free = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
|
||||
def nll(q):
|
||||
par = np.empty(len(start))
|
||||
par[free], par[K - 1 + j] = q, value
|
||||
return _ordinal_nll(par, X, y, K)
|
||||
|
||||
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
|
||||
|
||||
|
||||
def ordinal_fit(d: pd.DataFrame, outcome: str, predictor: str, high: float):
|
||||
"""The cumulative logit's fit on complete rows `d` (None when it can't be fitted, or
|
||||
when it separates): the design, its matrix, levels, the parameters, the minimum and the
|
||||
scoring state (P(level >= high))."""
|
||||
levels = np.sort(d[outcome].unique())
|
||||
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
|
||||
return None
|
||||
design = Design.of(d, predictor)
|
||||
X, K = design.matrix(d)[:, 1:], len(levels)
|
||||
y = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
par, nll = _cumulative(X, y, K)
|
||||
if abs(par[K - 1]) > 20:
|
||||
return "separation"
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
k = int(np.searchsorted(levels, high))
|
||||
inside = 0 < k < K
|
||||
state = {"design": design.state(), "beta": [float(v) for v in par[K - 1 :]],
|
||||
"threshold": float(theta[k - 1]) if inside else None,
|
||||
"always": None if inside else float(k == 0)} # fmt: skip
|
||||
return design, X, y, K, par, nll, state
|
||||
|
||||
|
||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
||||
d = rows(t, outcome, predictor)
|
||||
out = {"model": "ordinal", "n": len(d), "levels": int(d[outcome].nunique())}
|
||||
fitted = ordinal_fit(d, outcome, predictor, high)
|
||||
if fitted is None or fitted == "separation":
|
||||
return {**out, "reason": TOO_FEW if fitted is None else SEPARATION}
|
||||
design, X, y, K, par, nll, state = fitted
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
profile = lambda v: -_cumulative(X, y, K, fixed=(0, v))[1] # noqa: E731
|
||||
low, high_ = _interval(profile, par[K - 1], -nll, 0.1)
|
||||
if not (np.isfinite(low) and np.isfinite(high_)):
|
||||
return {**out, "reason": SEPARATION}
|
||||
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
||||
return _summary("ordinal", len(d), par[K - 1], low, high_, p, design, state, levels=K)
|
||||
|
||||
|
||||
def probability(model: str, state: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||
"""Each child's probability of the outcome under a fitted state, and the reference
|
||||
child's (z = 0, the cohort's mean age, the commonest module)."""
|
||||
X = Design.from_state(state["design"]).matrix(t)
|
||||
if model == "firth":
|
||||
return (expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"])),
|
||||
float(expit(state["intercept"]))) # fmt: skip
|
||||
if state["threshold"] is None:
|
||||
always = state["always"]
|
||||
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, always), always
|
||||
return (1 - expit(state["threshold"] - X[:, 1:] @ np.asarray(state["beta"])),
|
||||
float(1 - expit(state["threshold"]))) # fmt: skip
|
||||
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"dagster",
|
||||
"dagster-webserver",
|
||||
"mlflow-skinny",
|
||||
"openai>=3.59.0",
|
||||
"splink>=5.0.0",
|
||||
"duckdb>=2.0.1",
|
||||
"markitdown[docx,xlsx]>=0.1.9",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu import reports
|
||||
|
||||
|
||||
def test_a_candidate_with_two_reasons_is_excluded_once():
|
||||
"""Pins the totals, the pending rule, the people without a candidate and the as-of cut."""
|
||||
rows = pd.DataFrame(
|
||||
[
|
||||
("eligible", "2025-01-01", None, None),
|
||||
("two", "2025-01-01", None, "hysterectomy"),
|
||||
("two", "2025-01-01", None, "under_18"),
|
||||
("waiting", "2025-01-01", None, "no_index_result"),
|
||||
("waiting_and_out", "2025-01-01", None, "no_index_result"),
|
||||
("waiting_and_out", "2025-01-01", None, "prior_outcome"),
|
||||
("after", "2025-07-01", None, "hysterectomy"),
|
||||
],
|
||||
columns=["person_id", "index_date", "index_sample_id", "criterion"],
|
||||
)
|
||||
|
||||
found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30))
|
||||
|
||||
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
|
||||
assert (found["pending"], found["without_candidate"]) == (1, 6)
|
||||
assert found["by_reason"] == {
|
||||
"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1,
|
||||
} # fmt: skip
|
||||
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
|
||||
assert found["stage_by_reason"]["no_index_result"] == "index"
|
||||
assert found["stage_counts_overlap"] is True
|
||||
@@ -0,0 +1,114 @@
|
||||
import pytest
|
||||
import numpy as np
|
||||
from scipy.stats import norm
|
||||
|
||||
from models.cacu.bayes_development import prevalence_gibbs as PG
|
||||
|
||||
|
||||
def test_normal_posterior_is_least_squares_under_a_flat_prior():
|
||||
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no information."""
|
||||
rng = np.random.default_rng(1)
|
||||
X = np.column_stack([np.ones(200), rng.normal(size=200)])
|
||||
z = X @ [0.5, -1.0] + rng.normal(size=200)
|
||||
m, L = PG.normal_posterior(X, z, np.zeros(2), np.eye(2) * 1e-10)
|
||||
assert np.allclose(m, np.linalg.lstsq(X, z, rcond=None)[0], atol=1e-6)
|
||||
assert np.allclose(L @ L.T, np.linalg.inv(X.T @ X), rtol=1e-6)
|
||||
|
||||
|
||||
def test_latent_sign_follows_g():
|
||||
"""Fails if a truncated latent falls on the wrong side of zero."""
|
||||
rng = np.random.default_rng(2)
|
||||
g = rng.random(1000) < 0.5
|
||||
z = PG.draw_latent(rng.normal(size=1000) * 3, g, rng)
|
||||
assert np.all((z > 0) == g)
|
||||
|
||||
|
||||
def test_prob_g_by_observation():
|
||||
"""Fails if a tested positive is not certainly diseased, an untested woman does not keep her prior, or a tested
|
||||
negative is not discounted by 1 - kappa."""
|
||||
p, k = np.full(3, 0.2), 0.7
|
||||
out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k)
|
||||
assert out[0] == 1.0 and np.isclose(out[1], 0.2)
|
||||
assert np.isclose(out[2], 0.2 * 0.3 / (0.2 * 0.3 + 0.8))
|
||||
|
||||
|
||||
def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
|
||||
"""Fails if, with kappa pinned by a strong prior, the chain misses the true probit coefficients of a simulated
|
||||
cross-sectional sample (60 % tested, one test each)."""
|
||||
rng = np.random.default_rng(3)
|
||||
n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7
|
||||
X = np.column_stack([np.ones(n), rng.random(n) < 0.4])
|
||||
g = rng.random(n) < norm.cdf(X @ beta)
|
||||
r = (rng.random(n) < 0.6).astype(int)
|
||||
y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan)
|
||||
out = PG.gibbs(X, r, y, np.zeros(2), np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=4)
|
||||
assert np.allclose(out["beta"].mean(0), beta, atol=0.12)
|
||||
assert abs(out["kappa"].mean() - 0.7) < 0.02
|
||||
|
||||
|
||||
def test_referral_odds():
|
||||
"""Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) / Phi(eta) for a tested woman
|
||||
and the same with the survival function for an untested one."""
|
||||
eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8
|
||||
out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0]))
|
||||
assert np.isclose(out[0], 1.0)
|
||||
assert np.isclose(out[1], norm.cdf(-0.2) / norm.cdf(-1.0))
|
||||
assert np.isclose(out[2], norm.sf(1.3) / norm.sf(0.5))
|
||||
|
||||
|
||||
def _referral_sample(n=8000, seed=5):
|
||||
"""Two cells: the protocol refers the abnormal one (84 %); the normal one is referred mostly when diseased
|
||||
(3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell: Phi(-1.6) = 5.5 %."""
|
||||
rng = np.random.default_rng(seed)
|
||||
abnormal = (rng.random(n) < 0.2).astype(float)
|
||||
X = np.column_stack([np.ones(n), abnormal])
|
||||
g = rng.random(n) < norm.cdf(X @ [-1.6, 1.2])
|
||||
U = np.column_stack([np.ones(n), abnormal])
|
||||
arc = 1.0 - abnormal
|
||||
r = (rng.random(n) < norm.cdf(U @ [-1.8, 2.8] + 1.5 * arc * g)).astype(int)
|
||||
y = np.where(r == 1, g & (rng.random(n) < 0.7), np.nan)
|
||||
return X, r, y, U, arc
|
||||
|
||||
|
||||
def test_the_arc_removes_the_selection_bias():
|
||||
"""Fails if ignoring who gets referred does not overstate the prevalence of the unreferred cell, or if the arc
|
||||
with an informative prior on gamma_g does not bring it back to the truth (5.5 %)."""
|
||||
X, r, y, U, arc = _referral_sample()
|
||||
common = dict(b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6)
|
||||
without = PG.gibbs(X, r, y, **common)
|
||||
with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common)
|
||||
assert norm.cdf(without["beta"][:, 0]).mean() > 0.2
|
||||
assert abs(norm.cdf(with_arc["beta"][:, 0]).mean() - norm.cdf(-1.6)) < 0.02
|
||||
assert abs(with_arc["delta"][:, -1].mean() - 1.5) < 0.3
|
||||
|
||||
|
||||
def test_split_rhat():
|
||||
"""Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different levels do not exceed 1.1."""
|
||||
rng = np.random.default_rng(7)
|
||||
assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01
|
||||
assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1
|
||||
|
||||
|
||||
def test_patterns_keep_every_woman():
|
||||
"""Fails if collapsing identical women loses anyone or merges different observations."""
|
||||
X, r, y, U, arc = _referral_sample(n=500)
|
||||
d = PG.patterns(X, r, y, U, arc)
|
||||
assert d["n"].sum() == 500
|
||||
assert len(d["n"]) == len(np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0))
|
||||
|
||||
|
||||
def test_summed_likelihood_matches_a_direct_sum():
|
||||
pytest.importorskip("pymc") # optional dependency, not in the production environment
|
||||
"""Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g) woman by woman."""
|
||||
X, r, y, U, arc = _referral_sample(n=400)
|
||||
beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2])
|
||||
model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3))
|
||||
point = model.initial_point()
|
||||
point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta})
|
||||
got = model.compile_logp(vars=model.potentials)(point)
|
||||
p = norm.cdf(X @ beta)
|
||||
pr = lambda shift: np.where(r == 1, norm.cdf(shift), norm.sf(shift))
|
||||
py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0)
|
||||
py0 = np.where((r == 1) & (y == 1), 0.0, 1.0)
|
||||
direct = np.log(p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0).sum()
|
||||
assert np.isclose(got, direct)
|
||||
@@ -1,46 +0,0 @@
|
||||
"""The opt-in development evaluation (models.cacu.development): Firth and its FLIC and FLAC
|
||||
corrections, and the nested selection that never looks outside its training partition."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.development import METHODS, Firth, candidates, evaluate
|
||||
|
||||
|
||||
def data(n=60, seed=0):
|
||||
rng = np.random.default_rng(seed)
|
||||
X = pd.DataFrame({"a": rng.integers(0, 2, n), "b": rng.integers(0, 2, n)}, dtype=float)
|
||||
X.loc[:5, "a"] = np.nan
|
||||
X["not_a"], X["sparse"], X["counts"] = 1 - X["a"], np.nan, rng.integers(0, 5, n)
|
||||
y = (rng.random(n) < 0.15 + 0.5 * X["b"]).astype(int).to_numpy()
|
||||
return X, y
|
||||
|
||||
|
||||
def test_flic_matches_the_outcome_rate_and_flac_stays_near_firth():
|
||||
X, y = data()
|
||||
fitted = {m: Firth(m).fit(X[["b"]], y).predict_proba(X[["b"]])[:, 1] for m in METHODS}
|
||||
assert fitted["flic"].sum() == pytest.approx(y.sum())
|
||||
assert np.abs(fitted["flac"] - fitted["firth"]).max() < 0.05
|
||||
with pytest.raises(ValueError, match="collinear"):
|
||||
Firth().fit(np.column_stack([X["b"], X["b"]]), y)
|
||||
|
||||
|
||||
def test_candidates_are_known_binary_and_distinguishable():
|
||||
X, _ = data()
|
||||
assert candidates(X, 0.7, 5) == ["b", "a"] # not_a is a's complement; the rest aren't 0/1
|
||||
assert candidates(X, 0.95, 5) == ["b"]
|
||||
|
||||
|
||||
def test_nested_selection_reports_every_method_validation_and_attempt():
|
||||
X, y = data()
|
||||
found = evaluate(X, y)
|
||||
assert found["development_only"] and found["max_subsets"] == 16
|
||||
for plan in ("cv", "loocv"):
|
||||
for method in METHODS:
|
||||
result = found["validation"][plan][method]
|
||||
assert result["unscored"] == 0 and set(result["metrics"]) >= {"auc", "brier"}
|
||||
assert all(set(chosen) <= {"a", "b"} for chosen in result["selected"])
|
||||
assert {a["method"] for a in found["attempts"]} == set(METHODS)
|
||||
with pytest.raises(ValueError, match="exceeds"):
|
||||
evaluate(X, y, max_fits=10)
|
||||
@@ -0,0 +1,83 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.development_firth import FirthFamily
|
||||
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method', METHODS)
|
||||
def test_methods_fit_simulated_data(method):
|
||||
X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float)
|
||||
y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0])
|
||||
prediction = FirthFamily(method).fit(X, y).predict_proba(X)[:, 1]
|
||||
assert np.isfinite(prediction).all() and ((prediction > 0) & (prediction < 1)).all()
|
||||
|
||||
|
||||
def test_candidates_and_imputation_use_only_training_rows():
|
||||
train = pd.DataFrame({'a': [0., 1., np.nan, 1.], 'copy': [0., 1., np.nan, 1.],
|
||||
'absent': [np.nan] * 4})
|
||||
assert _candidates(train, 0.7, 5) == ['a']
|
||||
a, b = _matrix(train, pd.DataFrame({'a': [np.nan]}), ['a'])
|
||||
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
|
||||
|
||||
|
||||
def test_nested_cv_and_loocv_record_every_attempt():
|
||||
X = pd.DataFrame({'a': [0, 0, 1, 1, 0, 1, 0, 1],
|
||||
'b': [0, 1, 0, 1, 1, 0, 0, 1]})
|
||||
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
|
||||
report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2)
|
||||
assert report['development_only'] and report['max_subsets'] == 4
|
||||
assert set(report['validation']) == {'cv', 'loocv'}
|
||||
assert {a['method'] for a in report['attempts']} == set(METHODS)
|
||||
assert all('variables' in a and 'error' in a for a in report['attempts'])
|
||||
assert all(len(report['validation']['loocv'][m]['selected']) == len(X) for m in METHODS)
|
||||
|
||||
|
||||
def test_budget_rejects_large_loocv_before_fitting():
|
||||
X = pd.DataFrame({'a': [0, 1] * 10})
|
||||
with pytest.raises(ValueError, match='exceeds configured limit'):
|
||||
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
|
||||
|
||||
|
||||
def test_development_job_is_not_a_production_score():
|
||||
from core.models import DEVELOPMENT
|
||||
from models.definitions import defs
|
||||
|
||||
assert 'cacu.cin2_firth_development' in DEVELOPMENT
|
||||
job = defs.get_job_def('cacu_development_evaluation')
|
||||
assert job.name == 'cacu_development_evaluation'
|
||||
|
||||
|
||||
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
|
||||
import dagster as dg
|
||||
import mlflow
|
||||
from mlflow.tracking._tracking_service import utils as tracking_utils
|
||||
|
||||
from models.cacu import development_selection, encoders, features
|
||||
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
|
||||
from persistance import gold
|
||||
|
||||
monkeypatch.setenv('MLFLOW_TRACKING_URI', (tmp_path / 'mlruns').as_uri())
|
||||
monkeypatch.setenv('MLFLOW_ALLOW_FILE_STORE', 'true')
|
||||
monkeypatch.setattr(tracking_utils, '_tracking_uri', tracking_utils._tracking_uri)
|
||||
mlflow.set_tracking_uri((tmp_path / 'mlruns').as_uri())
|
||||
patients = [str(i) for i in range(8)]
|
||||
events = pd.DataFrame({'person_id': patients, 'date': ['2025-01-01'] * 8,
|
||||
'index_date': ['2025-01-01'] * 8})
|
||||
encoded = pd.DataFrame({'person_id': patients, 'index_date': ['2025-01-01'] * 8,
|
||||
'factor': [0, 0, 1, 1, 0, 1, 0, 1]})
|
||||
outcomes = pd.DataFrame({'person_id': patients, 'known': [True] * 8,
|
||||
'y': [0, 1, 0, 1, 0, 1, 1, 0]})
|
||||
monkeypatch.setattr(gold, 'evidence_timelines', lambda *a: events)
|
||||
monkeypatch.setattr(gold, 'cervical_forms', lambda *a: pd.DataFrame())
|
||||
monkeypatch.setattr(encoders, 'encode', lambda *a: encoded)
|
||||
monkeypatch.setattr(features, 'windowed_outcome', lambda *a: outcomes)
|
||||
real = development_selection.evaluate
|
||||
monkeypatch.setattr(development_selection, 'evaluate',
|
||||
lambda X, y, **kw: real(X, y, candidate_limit=1, subset_limit=1,
|
||||
outer_folds=2, inner_folds=2, **kw))
|
||||
with dg.build_op_context() as context:
|
||||
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of='2026-01-01'))
|
||||
artifacts = mlflow.MlflowClient().list_artifacts(run_id, 'reports')
|
||||
assert [a.path for a in artifacts] == ['reports/development_evaluation.json']
|
||||
+95
-79
@@ -1,5 +1,5 @@
|
||||
"""The development encoders (models.cacu.encoders) read only what was available at the index
|
||||
and never turn an absent value into 0."""
|
||||
"""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
|
||||
@@ -8,106 +8,122 @@ import pytest
|
||||
from models.cacu.encoders import FINDINGS, encode
|
||||
|
||||
INDEX = "2025-06-10"
|
||||
SAMPLE = "2025-01-10"
|
||||
|
||||
|
||||
def ev(date, kind, code=None, *, person="p1", table="cervical_cytology", source=None,
|
||||
clinical=None, available=None) -> dict: # fmt: skip
|
||||
return {"person_id": person, "index_date": INDEX, "date": date, "type": kind,
|
||||
"value_code": code, "value_num": np.nan, "source_table": table,
|
||||
"source_id": source or date, "evidence_date": clinical,
|
||||
"source_available_at": available} # fmt: skip
|
||||
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 encoded(events, forms=None, person="p1") -> pd.Series:
|
||||
blank = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
|
||||
forms = None if forms is None else pd.DataFrame([blank | f for f in forms])
|
||||
found = encode(pd.DataFrame(events), forms).set_index("person_id")
|
||||
return found.loc[person].drop("index_date").astype(float)
|
||||
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 test_an_unknown_value_is_missing_never_zero():
|
||||
assert encoded([ev(INDEX, "cytology", "satisfactory")]).isna().all()
|
||||
found = encoded([
|
||||
ev("1980-06-11", "birth", table="person"),
|
||||
*(ev("2025-01-15", k, c, source=SAMPLE) for k, c in (
|
||||
("bethesda", "LSIL"), ("hpv", "positive"), ("hpv_16", "negative"))),
|
||||
ev(INDEX, "cervix_appearance", "lesion"), ev(INDEX, "presenting_symptom", "other?"),
|
||||
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"], found["age__45-54"]) == (1, 0)
|
||||
assert (found["bethesda__LSIL"], found["bethesda__HSIL"]) == (1, 0)
|
||||
assert (found["cytology_ascus_plus"], found["cytology_hsil_plus"]) == (1, 0)
|
||||
assert (found["hpv_positive"], found["hpv_16_positive"]) == (1, 0)
|
||||
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"])
|
||||
assert np.isnan(found["hpv_16_or_18_positive"]) # one negative, the other unreported
|
||||
assert (found["cervix_appearance__lesion"], found["cervix_appearance__healthy"]) == (1, 0)
|
||||
assert found.filter(like="presenting_symptom").isna().all() # not one of its codes
|
||||
# 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("hpv_16, hpv_18, expected", [
|
||||
("positive", None, 1.0), ("negative", "negative", 0.0),
|
||||
("negative", "positive", 1.0)]) # fmt: skip
|
||||
def test_genotypes_of_one_sample(hpv_16, hpv_18, expected):
|
||||
events = [ev("2025-01-15", "hpv_16", hpv_16)]
|
||||
events += [ev("2025-01-15", "hpv_18", hpv_18)] if hpv_18 else []
|
||||
assert encoded(events)["hpv_16_or_18_positive"] == expected
|
||||
@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_what_was_not_available_at_the_index_is_not_read():
|
||||
base = [ev(INDEX, "cytology", "satisfactory")]
|
||||
def test_nothing_later_than_the_index_is_read():
|
||||
base = [event(INDEX, "cytology", "satisfactory")]
|
||||
later = [
|
||||
ev("2025-06-20", "bethesda", "HSIL", source=INDEX), # the index sample's report
|
||||
ev("2025-06-20", "hpv", "positive", source=INDEX),
|
||||
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
|
||||
ev("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
|
||||
# the index day's procedures may be the outcome
|
||||
ev(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
|
||||
ev(INDEX, "colposcopy", table="clinical_note"),
|
||||
ev(INDEX, "treatment", table="clinical_note"),
|
||||
ev("2025-08-01", "history", table="clinical_note"),
|
||||
# standalone evidence with no availability: its onset says nothing of when it was known
|
||||
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence"),
|
||||
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 = [{"person_id": "p1", "sample_date": INDEX, "report_date": "2025-06-20",
|
||||
"adequacy": "unsatisfactory", "finding_atrophy": True}] # fmt: skip
|
||||
pd.testing.assert_series_equal(encoded(base + later, forms), encoded(base))
|
||||
found = encoded([
|
||||
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
|
||||
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence", available="2024-01-01"),
|
||||
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"], found["history_hysterectomy"]) == (1, 1)
|
||||
assert found["cytology_hsil_plus"] == 1 and found["history_hysterectomy"] == 1
|
||||
|
||||
|
||||
def test_prior_procedures_and_the_referral_grade():
|
||||
found = encoded([
|
||||
ev("2025-01-15", "bethesda", "HSIL", source=SAMPLE),
|
||||
ev("2025-03-01", "colposcopy", table="clinical_note"),
|
||||
ev("2025-03-01", "biopsy_order", table="cervical_biopsy"),
|
||||
ev("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
|
||||
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"], found["prior_biopsy_order"]) == (1, 1)
|
||||
assert (found["prior_biopsy_lsil_plus"], found["prior_biopsy_hsil_plus"]) == (1, 0)
|
||||
assert found["referral_high_grade"] == 1 and np.isnan(found["prior_treatment"])
|
||||
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_the_form_is_read_from_its_latest_report_whole():
|
||||
def test_form_fields_come_from_the_latest_report():
|
||||
forms = [
|
||||
{"person_id": "p1", "sample_date": "2024-01-10", "report_date": "2024-01-20",
|
||||
"screening_history": "never", "finding_atrophy": True},
|
||||
{"person_id": "p1", "sample_date": SAMPLE, "report_date": "2025-01-20",
|
||||
"adequacy": "satisfactory", "finding_candida": 1},
|
||||
] # fmt: skip
|
||||
found = encoded([ev(INDEX, "cytology")], 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"], found["finding_candida"]) == (0, 1)
|
||||
assert found["sample_unsatisfactory"] == 0 and found["finding_candida"] == 1
|
||||
assert np.isnan(found["finding_atrophy"])
|
||||
|
||||
|
||||
def test_members_apart_and_a_timeline_without_availability_refused():
|
||||
events = [ev("2025-01-15", "hpv", "positive"), ev(INDEX, "cytology", person="p2")]
|
||||
assert np.isnan(encoded(events, person="p2")["hpv_positive"])
|
||||
with pytest.raises(KeyError, match="source_available_at"):
|
||||
encode(pd.DataFrame([ev(INDEX, "cytology")]).drop(columns="source_available_at"))
|
||||
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,13 @@
|
||||
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"])) == {"negative": 0.0, "positive": 1.0}
|
||||
+43
-16
@@ -5,9 +5,6 @@ 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.
|
||||
- A patient without an HPV result at the index is not evaluated; the current models read it
|
||||
as negative, so a result that is not positive stands in for it here.
|
||||
- An interval whose covariance can't be estimated is unknown, not the current platform's.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -16,8 +13,11 @@ 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
|
||||
|
||||
@@ -60,13 +60,15 @@ def timelines(cohort: str) -> pd.DataFrame:
|
||||
return found
|
||||
|
||||
|
||||
def assumed_hpv(events: pd.DataFrame) -> pd.DataFrame:
|
||||
"""A not-positive HPV result (nor a negative one) at the index of whoever has none."""
|
||||
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
|
||||
tested = events.loc[(events["type"] == "hpv") & near.to_numpy(), "person_id"]
|
||||
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()
|
||||
missing = index[~index["person_id"].isin(tested)]
|
||||
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed")
|
||||
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)
|
||||
|
||||
|
||||
@@ -76,7 +78,7 @@ def test_predictions_match_the_current_models(name):
|
||||
spec = MODELS[name]
|
||||
events = timelines(COHORTS[spec.cohort])
|
||||
if spec.method != "logistic regression":
|
||||
events = assumed_hpv(events)
|
||||
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")
|
||||
@@ -95,14 +97,16 @@ def test_predictions_match_the_current_models(name):
|
||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
if theirs in both:
|
||||
kept = both[ours].notna() | (ours == "probability") # estimable intervals
|
||||
np.testing.assert_allclose(both.loc[kept, ours], both.loc[kept, theirs], rtol=RTOL,
|
||||
atol=0) # fmt: skip
|
||||
# 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_with_its_index_fixed():
|
||||
def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monkeypatch):
|
||||
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
|
||||
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."""
|
||||
@@ -118,13 +122,13 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
||||
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
|
||||
events = events.merge(index, left_on="person_id", right_index=True)
|
||||
|
||||
model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
||||
model, metrics, data = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
||||
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
||||
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(v)) == set(spec.features) for v in found["input_values"])
|
||||
assert all(set(json.loads(value)) == set(spec.features) for value in found['input_values'])
|
||||
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
||||
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
||||
@@ -133,6 +137,29 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
||||
("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
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.specs import _rows
|
||||
|
||||
|
||||
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
|
||||
members = pd.DataFrame([
|
||||
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
||||
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
||||
])
|
||||
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5),
|
||||
("cytology", "hpv"))
|
||||
assert [json.loads(v) for v in result.input_values] == [
|
||||
{"cytology": "NILM", "hpv": 0}, {"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "HSIL", "hpv": 1}, {"cytology": "HSIL", "hpv": 1}]
|
||||
@@ -1,75 +0,0 @@
|
||||
"""What CaCu training keeps besides the models: who each cohort lost and why; that a patient
|
||||
without HPV is not evaluated; and that the mixture never makes up a risk or an interval it
|
||||
can't estimate (unseen levels, improper covariances, frozen parameters)."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import features, reports
|
||||
from models.cacu.pim import Fit, ISpline, Mixture
|
||||
|
||||
BASELINE = ISpline((0.0, 1.0, 2.0), 2)
|
||||
PARAMS = np.zeros(1 + BASELINE.n_params)
|
||||
X1, Z0 = np.ones((1, 1)), np.empty((1, 0))
|
||||
|
||||
|
||||
def fit(covariance) -> Fit:
|
||||
return Fit(1, 0, BASELINE, PARAMS, covariance, 0.0, True)
|
||||
|
||||
|
||||
def test_a_candidate_out_for_two_reasons_is_excluded_once():
|
||||
rows = pd.DataFrame([
|
||||
("eligible", "2025-01-01", None), ("two", "2025-01-01", "hysterectomy"),
|
||||
("two", "2025-01-01", "under_18"), ("waiting", "2025-01-01", "no_index_result"),
|
||||
("both", "2025-01-01", "no_index_result"), ("both", "2025-01-01", "prior_outcome"),
|
||||
("after", "2025-07-01", "hysterectomy"),
|
||||
], columns=["person_id", "index_date", "criterion"]).assign(index_sample_id=None) # fmt: skip
|
||||
found = reports.attrition("cacu_cohort_surveillance", "surveillance", rows, 10,
|
||||
date(2025, 6, 30)) # fmt: skip
|
||||
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"
|
||||
|
||||
|
||||
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 = features.index_results(events, cacu.KPNC)
|
||||
assert dict(zip(found["person_id"], found["hpv_positive"], strict=True)) == {
|
||||
"negative": 0.0, "positive": 1.0} # fmt: skip
|
||||
|
||||
|
||||
def test_rows_only_at_unseen_levels_get_no_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()
|
||||
|
||||
|
||||
def test_an_improper_covariance_gives_no_interval_never_a_zero_width_one():
|
||||
assert np.isfinite(fit(np.eye(len(PARAMS))).risk_with_variance(X1, Z0, [0, 1])[1]).all()
|
||||
n = len(PARAMS)
|
||||
for covariance in (np.full((n, n), np.nan), -np.eye(n), np.zeros((n, n))):
|
||||
assert np.isnan(fit(covariance).risk_with_variance(X1, Z0, [0, 1])[1]).all()
|
||||
frozen = np.eye(n)
|
||||
frozen[1, :] = frozen[:, 1] = np.nan # a frozen parameter moves only some horizons
|
||||
variance = fit(frozen).risk_with_variance(X1, Z0, [0, 1])[1]
|
||||
assert np.isfinite(variance[0, 0]) and np.isnan(variance[0, 1])
|
||||
|
||||
|
||||
def test_diagnostics_count_the_rows_without_an_interval():
|
||||
model = Mixture((0, 1), (), (), {})
|
||||
model.fits_, model.seen_ = {(): fit(-np.eye(len(PARAMS)))}, {(): {}}
|
||||
(stratum,) = model.variance_diagnostics(pd.DataFrame(index=range(2)))["strata"]
|
||||
assert stratum["rows_without_interval"] == 2 and stratum["negative_variances"]
|
||||
assert stratum["status"] == "not_estimable"
|
||||
@@ -1,77 +0,0 @@
|
||||
"""What Automático checks without asking the model: documents grouped by the words their
|
||||
layout prints, a proposed pattern kept only when it captures what the model read, a
|
||||
column's date format, and the site's codes as a ConceptMap the platform accepts."""
|
||||
|
||||
from core import concept_map
|
||||
from core.drafting import codes_schema, layout_schema, table_schema
|
||||
from models.draft import fields
|
||||
from models.draft.layouts import layouts
|
||||
|
||||
FORM = (
|
||||
"SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: {date}\n"
|
||||
"Calidad de la muestra: SATISFACTORIO\nResultado: {result}\nObservaciones: ninguna"
|
||||
)
|
||||
MAMMOGRAM = (
|
||||
"REPORTE DE MASTOGRAFÍA BILATERAL\nPaciente: {name}\nFecha del estudio: {date}\n"
|
||||
"Hallazgos: densidad mamaria tipo B, sin masas\nBI-RADS: 2"
|
||||
)
|
||||
|
||||
|
||||
def test_documents_of_one_layout_group_together_whoever_they_are_about():
|
||||
texts = [
|
||||
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
||||
MAMMOGRAM.format(name="LUISA ORTIZ MENA", date="11/04/2025"),
|
||||
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
||||
MAMMOGRAM.format(name="MARTA SOLÍS GIL", date="01/07/2025"),
|
||||
FORM.format(name="EVA RUIZ CANO", date="20/08/2025", result="ASC-US"),
|
||||
]
|
||||
found = layouts(texts)
|
||||
assert found[0] == found[2] == found[4] != found[1] == found[3]
|
||||
|
||||
|
||||
def test_a_pattern_is_kept_only_if_it_captures_the_values_read():
|
||||
texts = [
|
||||
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
||||
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
||||
]
|
||||
read = [
|
||||
(texts[0], {"sample_date": "2025-03-02", "result": "NILM"}),
|
||||
(texts[1], {"sample_date": "2025-06-15", "result": "LSIL"}),
|
||||
]
|
||||
codes = fields.Codes("sitio")
|
||||
entity = "cervical_cytology"
|
||||
date = r"recepci[oó]n:\s*(\d{2}/\d{2}/\d{4})"
|
||||
assert fields.checks(entity, "sample_date", date, "%d/%m/%Y", read, codes)
|
||||
assert not fields.checks(entity, "sample_date", date, "%m/%d/%Y", read, codes) # 15th month
|
||||
assert not fields.checks(entity, "sample_date", r"(\d{2}/\d{2})", None, read, codes)
|
||||
assert not fields.checks(entity, "sample_date", r"recepci[oó]n:", None, read, codes) # no group
|
||||
assert not fields.checks(entity, "result", r"resultado:(\s*)", None, read, codes) # nothing
|
||||
# A coded field: what the site writes becomes its ConceptMap, unless it is the code.
|
||||
assert fields.checks(entity, "result", r"resultado:\s*(\S+)", None, read, codes)
|
||||
assert codes.table() == {(entity, "result"): {"negativo": "NILM"}}
|
||||
# A pattern taking text that means two things is the wrong text.
|
||||
assert not fields.checks(entity, "result", r"(calidad)", None, read, fields.Codes("x"))
|
||||
found = codes.concept_map()
|
||||
assert concept_map.problems(found) == []
|
||||
assert concept_map.table([found], "result") == {"negativo": "NILM"}
|
||||
|
||||
|
||||
def test_a_columns_dates_get_the_format_every_value_parses_with():
|
||||
assert fields.date_format(["02/03/2025", "15/06/2025"]) == "%d/%m/%Y"
|
||||
assert fields.date_format(["2025-03-02", None]) == "%Y-%m-%d"
|
||||
assert fields.date_format(["mañana"]) is None
|
||||
|
||||
|
||||
def test_answers_are_held_to_the_platforms_terms():
|
||||
layout = layout_schema(3)["$defs"]["Study"]["properties"]
|
||||
assert (
|
||||
"cervical_cytology" in layout["entity"]["enum"]
|
||||
and "identity" not in layout["entity"]["enum"]
|
||||
)
|
||||
assert layout["documents"]["items"]["enum"] == [1, 2, 3]
|
||||
codes = codes_schema(["NEGATIVO", "BAJO GRADO"], ["NILM", "LSIL"])
|
||||
one = codes["$defs"]["Code"]["properties"]
|
||||
assert one["raw"]["enum"] == ["NEGATIVO", "BAJO GRADO"]
|
||||
assert {"enum": ["NILM", "LSIL"], "type": "string"} in one["code"]["anyOf"]
|
||||
table = table_schema(["num", "nombre"])
|
||||
assert table["$defs"]["Who"]["properties"]["column"]["enum"] == ["num", "nombre"]
|
||||
@@ -1,48 +0,0 @@
|
||||
"""Automático's judgements that need no model: a layout whose title the text layer
|
||||
garbles is still marked by a line it prints, and a report that leaves its sample's date to
|
||||
the order it answers is paired with that order by the column both carry."""
|
||||
|
||||
from core.pipeline import Join, Route
|
||||
from models.draft.joins import Kind, apart_from, joined, partner
|
||||
from models.draft.layouts import printed_line
|
||||
|
||||
HPV = (
|
||||
"No.Proceso {n}\nPaciente {name}\nDDDDEEEETTTTEEEECCCCCCCCIIIIOOOONNNN\n"
|
||||
"ESPECIMEN: CEPILLADO CERVICOVAGINAL\nVVVVPPPPHHHH . . . . . NNNNEEEEGGGG"
|
||||
)
|
||||
FORM = "SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: 0{n}/03/2025"
|
||||
|
||||
|
||||
def row(record: str, text: str, order) -> dict:
|
||||
return {"_record": record, "_file": f"{record:0>64}", "text": text, "format": "pdf",
|
||||
"orden_servicio_id": order, "tipo": "resultado"} # fmt: skip
|
||||
|
||||
|
||||
def test_a_layout_is_marked_by_a_line_only_it_prints():
|
||||
hpv = [row(f"h{n}", HPV.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
||||
forms = [row(f"c{n}", FORM.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
||||
assert printed_line(hpv, forms) == "ESPECIMEN: CEPILLADO CERVICOVAGINAL"
|
||||
assert printed_line(forms, forms[:1] + hpv) is None # what it prints, another prints too
|
||||
|
||||
|
||||
def test_a_report_is_read_with_the_order_the_same_column_pairs_it_with():
|
||||
reports = Kind("cervical_cytology", "VPH", "cervicovaginal", [],
|
||||
[row(f"h{n}", HPV.format(n=n, name="X"), n) for n in range(4)]) # fmt: skip
|
||||
orders = Kind("cervical_cytology", "Citología", "citología", [],
|
||||
[row(f"c{n}", FORM.format(n=n, name="X"), n) for n in range(1, 6)]) # fmt: skip
|
||||
# `tipo` and `format` pair every document with every other: they pair nothing.
|
||||
assert partner(reports, [reports, orders]) == (orders, "orden_servicio_id")
|
||||
orders.route = Route(id="citologia", label="Citología", inputs=["texto"])
|
||||
node = Join(id="vph_con_citologia", inputs=["vph", "citologia"],
|
||||
on=[("orden_servicio_id", "orden_servicio_id")], how="left") # fmt: skip
|
||||
found = dict((r["_record"], t) for t, r in joined(node, reports.everyone, orders))
|
||||
assert found["h1"].startswith("SOLICITUD DE CITOLOGÍA") and "Proceso 1" in found["h1"]
|
||||
assert found["h0"].startswith("No.Proceso 0") # no order: its own text alone
|
||||
assert apart_from(next(r for _, r in joined(node, reports.everyone, orders)
|
||||
if r["_record"] == "h1"), orders) # fmt: skip
|
||||
both = row("c1", FORM.format(n=1, name="X") + "\n" + HPV.format(n=1, name="X"), 1)
|
||||
(_, itself), = joined(node, [both], Kind("cervical_cytology", "", "", [], [both],
|
||||
orders.route)) # fmt: skip
|
||||
assert not apart_from(itself, orders) # one file, order and report: paired with itself
|
||||
lone = Kind("cervical_cytology", "VPH", "x", [], reports.everyone[:1])
|
||||
assert partner(lone, [lone, orders]) is None
|
||||
@@ -1,72 +0,0 @@
|
||||
"""One layout, several studies: the model is shown a layout's documents as unlike each
|
||||
other as they come (so the one note that records a death is among them), and a study only
|
||||
some of them report is kept only with a phrase that marks those and none of the others."""
|
||||
|
||||
from models.draft.documents import apart
|
||||
from models.draft.layouts import diverse, marks
|
||||
|
||||
NOTE = "INFORME MÉDICO\nNOMBRE: {name}\nMOTIVO DE LA CONSULTA: {why}\nPLAN: {plan}"
|
||||
ROUTINE = [
|
||||
NOTE.format(name=f"PACIENTE {n}", why="control anual", plan="cita en un año") for n in range(20)
|
||||
]
|
||||
DEATH = NOTE.format(name="PACIENTE 99", why="NOTA DE DEFUNCIÓN: falleció en urgencias",
|
||||
plan="certificado de defunción, causa: choque séptico") # fmt: skip
|
||||
PATHOLOGY = "ESTUDIO PATOLÓGICO\nNOMBRE: {name}\nÓRGANO: {organ}\nDIAGNÓSTICO: {dx}"
|
||||
|
||||
|
||||
def docs(texts: list[str]) -> list[dict]:
|
||||
return [{"_record": str(i), "text": t} for i, t in enumerate(texts)]
|
||||
|
||||
|
||||
def test_the_one_unlike_note_is_among_those_shown():
|
||||
notes = docs(ROUTINE[:10] + [DEATH] + ROUTINE[10:])
|
||||
assert any("DEFUNCIÓN" in r["text"] for r in diverse(notes, 3))
|
||||
assert len(diverse(notes, 30)) == len(notes)
|
||||
|
||||
|
||||
def test_a_study_some_documents_report_is_kept_with_what_marks_them():
|
||||
shown = docs([PATHOLOGY.format(name="A", organ="CÉRVIX", dx="NIC 2"),
|
||||
PATHOLOGY.format(name="B", organ="MAMA", dx="CARCINOMA DUCTAL"),
|
||||
PATHOLOGY.format(name="C", organ="CÉRVIX", dx="NIC 1")]) # fmt: skip
|
||||
log = []
|
||||
cervix = {"label": "Biopsia cervical", "documents": [1, 3], "marker": "ÓRGANO: CÉRVIX"}
|
||||
assert apart(cervix, shown, {2}, log.append) == "ÓRGANO: CÉRVIX"
|
||||
# The model's phrase marks the wrong documents: a printed line that does is taken.
|
||||
breast = {"label": "Biopsia de mama", "documents": [2], "marker": "DIAGNÓSTICO"}
|
||||
assert apart(breast, shown, {1, 3}, log.append) == "ÓRGANO: MAMA"
|
||||
# A study the model gives all but one, the one no other study claims: all of them.
|
||||
assert apart({**cervix, "documents": [1, 3]}, shown, set(), log.append) is None
|
||||
every = {"label": "Patología", "documents": [1, 2, 3], "marker": "ESTUDIO"}
|
||||
assert apart(every, shown, set(), log.append) is None # all of them: the layout's own route
|
||||
assert apart({**every, "documents": []}, shown, set(), log.append) is False
|
||||
alike = {"label": "x", "documents": [1], "marker": None} # nothing sets A apart from C
|
||||
assert apart(alike, shown, {3}, log.append) is False and log
|
||||
|
||||
|
||||
def test_a_phrase_the_model_tidied_still_finds_what_the_document_writes():
|
||||
organs = ["CÉRVIX", "MAMA DERECHA", "CERVIX", "MAMA IZQUIERDA"]
|
||||
shown = docs([PATHOLOGY.format(name=n, organ=f"{o}, BIOPSIA:", dx="X")
|
||||
for n, o in zip("ABCD", organs, strict=True)]) # fmt: skip
|
||||
breast = {"label": "Biopsia de mama", "documents": [2, 4], "marker": "MAMA, BIOPSIA"}
|
||||
found = apart(breast, shown, {1, 3}, print)
|
||||
assert [marks(found, r["text"]) for r in shown] == [False, True, False, True]
|
||||
cervix = {"label": "Biopsia cervical", "documents": [1, 3], "marker": "CÉRVIX, BIOPSIA"}
|
||||
found = apart(cervix, shown, {2, 4}, print) # written without its accent in C
|
||||
assert [marks(found, r["text"]) for r in shown] == [True, False, True, False]
|
||||
|
||||
|
||||
def test_a_study_no_line_marks_is_marked_by_the_words_its_documents_share():
|
||||
"""Each side writes its own specimen line (MAMA DERECHA, MAMA IZQUIERDA) and the model
|
||||
names the documents without a phrase: the word they all write marks them."""
|
||||
cervix = "ESTUDIO PATOLOGICO\nNOMBRE: {n}\n1 - BIOPSIA DIRIGIDA POR COLPOSCOPIA DE {c}"
|
||||
breast = "ESTUDIO PATOLOGICO\nNOMBRE: {n}\nDx: {dx}\n1 - BIOPSIA CON AGUJA DE CORTE DE {s}"
|
||||
shown = docs([cervix.format(n="A", c="CÉRVIX"), cervix.format(n="B", c="CERVIX"),
|
||||
breast.format(n="C", dx="CA DE MAMA", s="MAMA DERECHA"),
|
||||
breast.format(n="D", dx="NÓDULO MAMARIO", s="MAMA IZQUIERDA")]) # fmt: skip
|
||||
mama = {"label": "Biopsia de mama", "documents": [3, 4], "marker": None}
|
||||
found = apart(mama, shown, {1, 2}, print)
|
||||
assert [marks(found, r["text"]) for r in shown] == [False, False, True, True]
|
||||
assert "M" in found and "AGUJA" not in found # the study's own word, before any other
|
||||
cervical = {"label": "Biopsia cervical", "documents": [1, 2], "marker": None}
|
||||
found = apart(cervical, shown, {3, 4}, print) # CÉRVIX and CERVIX alike
|
||||
assert [marks(found, r["text"]) for r in shown] == [True, True, False, False]
|
||||
@@ -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,40 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.pim import Fit, ISpline, Mixture
|
||||
|
||||
|
||||
def test_unestimable_covariances_never_produce_zero_width_intervals():
|
||||
baseline = ISpline((0.0, 1.0, 2.0), 2)
|
||||
params = np.zeros(1 + baseline.n_params)
|
||||
X, Z = np.ones((1, 1)), np.empty((1, 0))
|
||||
good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True)
|
||||
assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||
for covariance in (np.full((len(params), len(params)), np.nan),
|
||||
-np.eye(len(params)), np.zeros((len(params), len(params)))):
|
||||
broken = Fit(1, 0, baseline, params, covariance, 0, True)
|
||||
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||
|
||||
|
||||
def test_frozen_parameter_only_invalidates_horizons_it_affects():
|
||||
baseline = ISpline((0.0, 1.0, 2.0), 2)
|
||||
params = np.zeros(1 + baseline.n_params)
|
||||
covariance = np.eye(len(params))
|
||||
covariance[1, :] = np.nan
|
||||
covariance[:, 1] = np.nan
|
||||
fitted = Fit(1, 0, baseline, params, covariance, 0, True)
|
||||
variance = fitted.risk_with_variance(np.ones((1, 1)), np.empty((1, 0)), [0, 1])[1]
|
||||
assert np.isfinite(variance[0, 0])
|
||||
assert np.isnan(variance[0, 1])
|
||||
|
||||
|
||||
def test_diagnostics_count_rows_without_intervals():
|
||||
baseline = ISpline((0.0, 1.0, 2.0), 2)
|
||||
params = np.zeros(1 + baseline.n_params)
|
||||
model = Mixture((0, 1), (), (), {})
|
||||
model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)}
|
||||
model.seen_ = {(): {}}
|
||||
report = model.variance_diagnostics(pd.DataFrame(index=range(2)))
|
||||
assert report['strata'][0]['rows_without_interval'] == 2
|
||||
assert report['strata'][0]['negative_variances']
|
||||
assert report['strata'][0]['status'] == 'not_estimable'
|
||||
Reference in New Issue
Block a user