Compare commits

..

30 Commits

Author SHA1 Message Date
alberto 0b4f7593e5 TEA hospital test follows the sensor flow; re-analysis by id in local mode; first_n
Update tests/test_tea_job.py. Use the synthetic TEA builder with the existing pipeline and concept map, ingest via the platform fixture without a daemon, and run first_n synchronously in process.

Use SQLite and its temporary platform environment, count an absent analysis table as zero, and clear the cached engine around the in-process calls.
2026-11-29 01:25:29 -06:00
alberto c6c55e0ffe Merge P3.7 into P3.5 for one combined gate 2026-11-28 16:31:56 -06:00
alberto 3950b3c1f5 tea_preview job: one file previewed, result as run output: preview analyses one staged EDF (and an ADOS-2 PDF) against the champions, writes nothing 2026-11-28 13:37:27 -06:00
alberto b7eaf7055d Training config: reference name and mains frequency: train takes a named reference cohort and its mains frequency; legacy TEA_REFERENCE_DIR stays the default 2026-11-28 13:26:18 -06:00
alberto 9ed686e87a Merge tea/parity into P3.6 2026-11-28 10:31:00 -06:00
alberto dce0e0c690 EDF reader node in the ingestion DSL: run_edf keeps each row and adds the header facts or the file's error; read.header parses the fixed EDF header without edfio 2026-11-28 10:30:48 -06:00
alberto d954faa28e Generic model bundles: export and import: the import_bundle job 2026-11-28 09:24:36 -06:00
alberto cc95054a96 The tea_eeg job: analyse, score the age curves, relate ADOS-2, rebuild gold; a sensor starts it after an ingest
Analysis and the reference cohort's measuring run on execution.map; relate is the
Phase 2 seam. A LocalCluster starts inside a multiprocess Dagster step (checked on a
real run), so the ops keep the default executor.
2026-11-27 18:02:28 -06:00
alberto 9220b8c52c execution.map runs a heavy op's items in this process, on local workers or on a Dask scheduler, and reports progress on the run 2026-11-27 17:19:55 -06:00
Roberto Treviño 3546269eaf Review queues a scan read only in part, and an undated name one typo from a person 2026-11-27 14:02:08 -06:00
Roberto Treviño 7b9ae69de2 CaCu models record the outcomes each split holds 2026-11-27 11:05:28 -06:00
Roberto Treviño 4ff4a3a7d8 A person nothing names is held for review; a scan may misread one valid code as another 2026-11-27 08:46:05 -06:00
Roberto Treviño 999f0fb926 A model whose cohort is empty at a site is skipped, not a failed train run 2026-11-27 05:07:54 -06:00
Roberto Treviño 02aab07a67 Extract reads several columns as one document; reviewers' corrections of study fields applied at the target; the site gates on ISSSTELEON's test source 2026-11-27 01:45:16 -06:00
Roberto Treviño 44cb0dc894 CaMa survival with stage and first-course treatment, clinical scenario report, measured against the SEER-trained original 2026-11-26 19:03:38 -06:00
Roberto Treviño 76eb8cc8af Files read by hash; fractional Weibull solved and fitted to convergence; recurrence reads its reference cohorts from the platform 2026-11-26 14:25:53 -06:00
Roberto Treviño f305cdd044 TEA EEG analysis and age curves, TEA jobs; CaMa recurrence on METABRIC and SCAN-B; reference-data models and routine runs 2026-11-26 07:06:52 -06:00
Roberto Treviño e2f7e95e83 Shared interval survival for CaMa and CaCu, one jobs module for every domain, Dagster train and score by domain 2026-11-25 23:20:52 -06:00
Roberto Treviño d3d9cc3950 Link node keeps names as written; compares them normalised 2026-11-25 17:39:32 -06:00
Roberto Treviño 8c0ec5106c Long silver from targets, stable person ids, ConceptMap translation, the fhir node 2026-11-25 16:17:23 -06:00
Roberto Treviño b6857dab2a CaCu training and scoring jobs on gold, MLflow versions with their reports 2026-11-25 01:16:45 -06:00
Roberto Treviño bea3e4cd2d CaCu models: prevalence-incidence mixture and logistic, equal to the current predictions 2026-11-25 00:28:42 -06:00
Roberto Treviño 77fc039586 Link: reviewer decisions and corrections, orphan candidates by typo-near identifiers; OCR sidecar text 2026-11-24 22:35:13 -06:00
Roberto Treviño 0c4706658b Share the platform fixture from the root conftest 2026-11-24 21:00:52 -06:00
Roberto Treviño 61721a8005 Run every node kind: route, map, join, extract (LLM or patterns), link (Splink), target 2026-11-24 20:05:29 -06:00
Roberto Treviño 8d874736db Run pipeline graphs: one ingest job, Source and Read nodes 2026-11-24 18:20:26 -06:00
Roberto Treviño 79a55a7a62 Collect and unpack jobs; ingestion gate on SQLite and PostgreSQL 2026-11-24 17:48:18 -06:00
rockdrigo f1370d2776 Move DbtProject to its own module so its manifest can be prepared before load
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:50:45 -06:00
rockdrigo 639bbcda19 Sample job test: run each Dagster run in its own process, on SQLite and PostgreSQL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:42:07 -06:00
rockdrigo 3558e24a46 Rebuild: Dagster code location with the sample dlt and dbt assets
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:18:08 -06:00
74 changed files with 9109 additions and 1581 deletions
-12
View File
@@ -1,14 +1,2 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
# MLflow's own default local stores, used only when MLFLOW_TRACKING_URI
# isn't set (dev/tests point it elsewhere, e.g. a tmp_path file store).
mlflow.db
mlruns/
mlartifacts/
-26
View File
@@ -1,26 +0,0 @@
# models
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
versiones en MLflow con requisitos de promoción, registro de predicciones y
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
armados del kit de indicadores (`cohorte_armado`, en la base de cada
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
WebApi.
| Módulo | Qué hace |
|---|---|
| `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. |
| `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. |
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). |
| `registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
| `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`).
`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos
guardan sus artefactos.
```bash
uv run pytest -q
```
-41
View File
@@ -1,41 +0,0 @@
import importlib
from abc import ABC, abstractmethod
from typing import Any, ClassVar, Iterator
from persistance.repository import Repository
def resolve_repository(domain: str, entity: str) -> Repository:
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
class ScreeningModel(ABC):
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
Data is read through the same `persistance.<domain>.<entity>_repository`
objects WebApi writes with, so anything loaded through the import flow
is visible here. `train` may also be given rows fetched by the caller.
"""
domain: ClassVar[str]
def repository(self, entity: str) -> Repository:
return resolve_repository(self.domain, entity)
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
"""Every row of `entity` as plain dicts, read in batches."""
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
@abstractmethod
def train(self, data: Any = None) -> None:
"""Fit the model, optionally on `data` passed in by the caller."""
@abstractmethod
def predict(self, data: Any) -> Any:
"""Score `data` and return predictions."""
-21
View File
@@ -1,21 +0,0 @@
from typing import Any
from models.base import ScreeningModel
class CaCuModel(ScreeningModel):
"""Scaffold for the CaCu (cervical cancer) screening model.
Can pull its own training data straight from `persistance.cacu`'s
repositories (`paciente_repository`, `citologia_cervical_repository`,
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
No real model yet; this is interface scaffolding only.
"""
domain = "cacu"
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaCu training is not implemented yet.")
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaCu prediction is not implemented yet.")
View File
+164
View File
@@ -0,0 +1,164 @@
"""What the CaCu models read from a patient's timeline (gold `cacu_events`): one row per
event, with the patient's cohort index date. Columns: person_id, index_date, date, type,
value_code, value_num, source_table, source_id."""
import numpy as np
import pandas as pd
from core import cacu
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over
MISSING = "(none)"
def prepared(events: pd.DataFrame) -> pd.DataFrame:
return events.assign(
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
)
def days(events: pd.DataFrame) -> pd.Series:
return (events["date"] - events["index_date"]).dt.days
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per patient (the index of `codes`), her most severe result as its cytology category."""
rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
names = list(cytology)
worst = codes.map(rank).groupby(level=0).max()
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
when `history` asks for it."""
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"
)
members = events.groupby("person_id", as_index=False)["index_date"].first()
wide = wide.reindex(index=members["person_id"], columns=list(RESULTS))
codes = wide[["bethesda", "glandular"]].stack()
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
if history:
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
return members
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
"""Days at which she was seen free of the outcome: a biopsy below `grades`, or a
negative co-test (the later day of its two results)."""
timed = events.assign(days=d.astype(float))[d >= 0]
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
visits = None
for kind, values in cacu.KNOWN_NEGATIVE.items():
found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)]
found = found[["person_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
left_on="days", right_on=kind, by="person_id", direction="nearest",
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
).dropna(subset=[kind]) # fmt: skip
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
history: dict | None = None) -> pd.DataFrame: # fmt: skip
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
the prevalent window), free at the index (a negative before any outcome), or unknown;
and the years between her last negative and her outcome biopsy."""
d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
negatives = _negatives(events, d, grades)
before = ~(negatives["days"] >= negatives["person_id"].map(first))
last_negative = negatives[before].groupby("person_id")["days"].max()
coded = index_results(events, cytology, history)
window = cacu.PREVALENT_WINDOW_DAYS
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
prevalent = event_days <= window
free = free_until.notna() & ~prevalent
later = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0,
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
return coded
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
"""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
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))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()]
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete.index)].reset_index()
latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last()
return latest["date"]
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test."""
ordered = members.sort_values(["index_date", "person_id"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut], ordered.iloc[cut:]
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
"""Per patient: each predictor's result on her index sample, MISSING when none."""
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members = members[["person_id", "index_date"]]
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first()
results = events.merge(sample, on=["person_id", "source_table", "source_id"])
genotype = results["type"] == "hpv_16_18"
results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map(
{1.0: "positive", 0.0: "negative"}
)
wide = results[results["type"].isin(predictors)].pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
)
wide = wide.reindex(columns=list(predictors)).astype(object)
found = members.merge(wide, left_on="person_id", right_index=True, how="left")
return found.fillna(dict.fromkeys(predictors, MISSING))
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window)
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int)
followed = (follow_up_end - members["index_date"]).dt.days
members["known"] = (members["y"] == 1) | (followed >= window)
return members[["person_id", "y", "known"]]
+8
View File
@@ -0,0 +1,8 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
from models.cacu import reports
from models.cacu.specs import MODELS
from models.jobs import Jobs
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
train, score = JOBS.train, JOBS.score
+265
View File
@@ -0,0 +1,265 @@
"""Prevalence-incidence mixture for interval-censored outcomes (PIMixture, Cheung et al.).
A patient either has the outcome at the index visit (prevalence, a logistic model) or may
develop it later (incidence, a proportional-hazards model with an I-spline baseline). Each
patient is coded `c` = 1 (prevalent), 0 (known free at the index), or UNKNOWN, with the
interval (l, r] in years where an incident outcome happened. No library fits this model, so
the likelihood is written here; everything else is scipy.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
from scipy.stats import norm
from sklearn.base import BaseEstimator
UNKNOWN = -999
TINY = 1e-12 # floor inside every log
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated
HESSIAN_STEP = 1e-4
def ispline_basis(t, degree: int, knots) -> np.ndarray:
"""Integrated B-splines: monotone from 0 at the first knot to 1 at the last."""
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)]
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
basis[t >= knots[-1]] = 1.0
basis[t <= knots[0]] = 0.0
return basis
@dataclass(frozen=True)
class ISpline:
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
knots: tuple[float, ...]
degree: int
@classmethod
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
times = np.unique(np.r_[l, r[np.isfinite(r)]])
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
@property
def n_params(self) -> int:
return len(self.knots) + self.degree - 2
def cumulative_hazard(self, t, params) -> np.ndarray:
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
def start(self, c, l, r) -> np.ndarray:
"""Every coefficient equal, so the hazard is the crude event rate."""
at_risk, finite = c != 1, np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum()
# exp(-log(...)), not a plain division: on a flat likelihood BFGS follows the start's
# last bit, and this is the start the current models were fitted from.
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
t = np.asarray(t, dtype=float)
with np.errstate(over="ignore", invalid="ignore"):
found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta))
found = np.where(t <= 0, 1.0, found)
return np.where(np.isinf(t), 0.0, found)
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
n_x, n_z = X.shape[1], Z.shape[1]
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
pi = expit(X @ theta)
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
interval = np.maximum(interval, TINY)
row = np.zeros(len(c))
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
row[prevalent] = np.log(pi[prevalent] + TINY)
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
return -np.sum(w * row)
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
"""Central-difference Hessian of f at x."""
p = len(x)
out = np.zeros((p, p))
for i in range(p):
for j in range(i, p):
ei, ej = np.zeros(p), np.zeros(p)
ei[i], ej[j] = step, step
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
4 * step * step
)
out[i, j] = out[j, i] = value
return out
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
"""Prevalence coefficients from the patients whose index status is known."""
known = c != UNKNOWN
if not known.any():
return np.zeros(X.shape[1])
y, Xk = (c[known] == 1).astype(float), X[known]
def loss(theta):
eta = Xk @ theta
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
@dataclass(frozen=True)
class Fit:
n_x: int
n_z: int
baseline: ISpline
params: np.ndarray
covariance: np.ndarray # NaN where a parameter is frozen
neg_loglik: float
converged: bool
def risk(self, X, Z, years, params=None) -> np.ndarray:
"""Cumulative risk at each horizon: prevalent, or incident by then."""
p = self.params if params is None else params
theta, beta, rest = (
p[: self.n_x],
p[self.n_x : self.n_x + self.n_z],
p[self.n_x + self.n_z :],
)
pi = expit(X @ theta)
return np.column_stack([
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
for t in years
]) # fmt: skip
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
"""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))
up, down = self.params.copy(), self.params.copy()
up[k] += step
down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
covariance = np.nan_to_num(self.covariance, nan=0.0)
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
return self.risk(X, Z, years), np.maximum(variance, 0.0)
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
"""Maximum likelihood from two starts (BFGS); covariance from the numerical Hessian."""
n_x, n_z = X.shape[1], Z.shape[1]
start = baseline.start(c, l, r)
starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
args = (c, l, r, X, Z, baseline, w)
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
free = np.abs(best.x) < FROZEN
covariance = np.full((len(best.x), len(best.x)), np.nan)
h = hessian(lambda p: neg_loglik(p, *args), best.x)
try:
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
except np.linalg.LinAlgError:
pass
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
class Mixture(BaseEstimator):
"""One mixture per stratum. Categorical features get one dummy per level after the first
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
interval_level=0.95): # fmt: skip
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.levels = levels
self.knots = knots
self.degree = degree
self.interval_level = interval_level
def _seen(self, X: pd.DataFrame) -> dict:
return {
f: [v for v in values if (X[f] == v).any()]
for f, values in self.levels.items()
if f in X.columns and f not in self.strata
}
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
if not seen:
return np.ones(len(X), dtype=bool)
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0)
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
columns = []
for f in features:
if f in self.strata:
continue
if f in seen:
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
else:
columns.append(X[f].to_numpy(dtype=float))
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
return prevalence, self._columns(X, self.incidence_features, seen)
def _groups(self, X: pd.DataFrame):
if not self.strata:
return [((), np.arange(len(X)))]
groups = X.groupby(list(self.strata), sort=True).indices.items()
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
"""X: the features; y: c, l, r. Identical rows are fitted once, weighted."""
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
axis=1).assign(w=1.0) # fmt: skip
self.fits_, self.seen_ = {}, {}
for key, index in self._groups(X):
group = rows.iloc[index]
seen = self._seen(group)
group = group[self._placed(group, seen)]
group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
prevalence, incidence = self._design(group[X.columns], seen)
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
self.seen_[key] = seen
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
self.converged_ = all(f.converged for f in self.fits_.values())
return self
def predict(self, X: pd.DataFrame) -> np.ndarray:
"""Per row and horizon: (risk, low, high) as three blocks of columns; NaN where the
row's stratum or level was never seen."""
h = len(self.horizons_years)
out = np.full((len(X), 3 * h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2)
for key, index in self._groups(X):
if key not in self.fits_:
continue
members = X.iloc[index]
placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key])
design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True)
n_x = prevalence.shape[1]
point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], self.horizons_years
)
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
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
+172
View File
@@ -0,0 +1,172 @@
"""The two reports training writes for each model version (the third, the clinical
validation, is a document the clinical team adds). Both are data the governance page draws.
- technical validation: how the version was trained and tested, and its held-out metrics;
- interpretability: what drives its predictions. For the mixture, observed against
predicted risk per combination of its features: the Turnbull estimate (the
nonparametric cumulative risk under interval censoring) with a bootstrap band, the
model's curve with its delta-method band, and expected over observed at each horizon.
For the logistic regression, its coefficients and calibration by risk decile.
"""
import numpy as np
import pandas as pd
from scipy.stats import norm
from sklearn.metrics import brier_score_loss
from models import survival
from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim
GRID_STEP = 0.1 # years between points of a curve
BOOTSTRAP = 200
SEED = 20261122
Z = norm.ppf(0.975)
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
if isinstance(spec, survival.Spec):
return survival.technical_validation(spec, metrics, data)
members = data.get("coded", data.get("labelled"))
return {
"model": spec.name,
"method": spec.method,
"cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min()), str(members["index_date"].max())],
"metrics": metrics,
}
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
"""Turnbull's EM: support points and cumulative risk at each. A prevalent case's event
is at 0; a patient free at the index has hers in (l, r]; an unknown one in [0, r]."""
finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
patterns, counts = np.unique(inside, axis=0, return_counts=True)
p = np.full(len(support), 1 / len(support))
for _ in range(iters):
weighted = patterns * p
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
done = np.max(np.abs(new - p)) < tol
p = new
if done:
break
return support, np.cumsum(p)
def _at(support, cumulative, t) -> np.ndarray:
i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)])
def _label(feature: str, value) -> str:
if value is None or (isinstance(value, float) and np.isnan(value)):
return "NA"
if feature == "hpv_positive":
return "positive" if float(value) == 1.0 else "negative"
return str(value)
def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all():
return None
prevalence, incidence = mixture._design(row, mixture.seen_[key])
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
return point[0], variance[0]
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
if isinstance(spec, survival.Spec):
return survival.interpretability(spec, model, data)
if isinstance(spec, Logistic):
return _logistic(model, data["test"])
coded = data["coded"]
full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
members = coded.reset_index(drop=True)
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
horizons = np.asarray(spec.horizons, dtype=float)
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
rng = np.random.default_rng(SEED)
groups = []
for _, combination in labels.drop_duplicates().iterrows():
mask = (labels == combination).all(axis=1).to_numpy()
group = members[mask]
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
support, cumulative = turnbull(c, l, r)
boot_grid, boot_h = [], []
for _ in range(BOOTSTRAP):
pick = rng.integers(0, len(group), len(group))
s, cum = turnbull(c[pick], l[pick], r[pick])
boot_grid.append(_at(s, cum, grid))
boot_h.append(_at(s, cum, horizons))
observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
entry = {
"combination": combination.to_dict(),
"n": int(mask.sum()),
"prevalent": int((c == 1).sum()),
"incident": int(((c != 1) & np.isfinite(r)).sum()),
"observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
"high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
"predicted": None,
"expected_over_observed": [],
} # fmt: skip
probe = group.iloc[[0]][spec.features]
at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
if at_grid is not None:
low, high = _band(*at_grid)
entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
"low": low, "high": high} # fmt: skip
for k, h in enumerate(horizons):
e = None if at_h is None else float(at_h[0][k])
ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
"ratio": None, "low": None, "high": None} # fmt: skip
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
value = e / observed[k]
ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
"high": value * np.exp(Z * se)} # fmt: skip
entry["expected_over_observed"].append(ratio)
groups.append(entry)
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
"groups": groups} # fmt: skip
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
names = encoder.get_feature_names_out()
p = test["p"]
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
observed=("y", "mean")) # fmt: skip
return {
"model": "logistic regression",
"kind": "coefficients",
"intercept": float(classifier.intercept_[0]),
"coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)),
"calibration": {
"brier": float(brier_score_loss(test["y"], p)),
"bins": [
{
"range": str(k),
"n": int(v.n),
"predicted": float(v.predicted),
"observed": float(v.observed),
}
for k, v in table.iterrows()
],
}, # fmt: skip
}
+205
View File
@@ -0,0 +1,205 @@
"""The CaCu models: each is a spec (what it reads and how it is set) over one of two methods,
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
patient timelines of the spec's cohort (see features)."""
from dataclasses import dataclass, field
from typing import Literal
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
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
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"]
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> 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]
n = len(members)
frame = pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h),
"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(),
}) # 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]
@dataclass(frozen=True)
class Pim:
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
name: str
cohort: str
grades: list[str]
cytology: dict[str, list[str]]
strata: tuple[str, ...]
incidence_features: tuple[str, ...]
history: dict | None = None # a feature from before the index (the referral grade)
predict_at: Literal["index", "last_screening_cytology"] = "index"
horizons: tuple[float, ...] = HORIZONS
method: str = field(default="prevalence-incidence mixture", init=False)
@property
def features(self) -> list[str]:
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
def _history(self) -> dict | None:
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
members it learned from (for the reports)."""
events = f.prepared(events)
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
train, test = f.split(coded, TRAIN_FRACTION)
levels = {"cytology": list(self.cytology)}
if self.history:
levels[self.history["feature"]] = list(self.history["levels"])
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
mixture.fit(train[self.features], train[["c", "l", "r"]])
return mixture, self.metrics(mixture, train, test), {"coded": coded}
def metrics(self, mixture: Mixture, train, test) -> dict:
found = {
"n_train": len(train),
"n_test": len(test),
# outcomes, prevalent or incident, each split learned from or was judged on
"events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()),
"events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()),
"neg_loglik": mixture.neg_loglik_,
"converged": float(mixture.converged_),
}
risks = mixture.predict(test[self.features])
for column, horizon in enumerate(self.horizons):
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
if known.any():
found[f"observed_{tag}"] = float(y.mean())
found[f"expected_{tag}"] = float(p.mean())
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
if len(np.unique(y)) == 2:
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
return found
def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame:
events = f.prepared(events)
if self.predict_at == "last_screening_cytology":
chosen = f.last_screening_cytology(events)
events = events[events["person_id"].isin(chosen.index)]
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)
@dataclass(frozen=True)
class Logistic:
"""Probability of the outcome within one year of the index sample."""
name: str
cohort: str
grades: list[str]
predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18")
years: float = 1.0
method: str = field(default="logistic regression", init=False)
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
"""Patients whose outcome is unknown (followed less than a year, no outcome) are left
out. Follow-up ends at `follow_up_end`: the date the data are known to."""
events = f.prepared(events)
found = f.index_sample(events, list(self.predictors))
outcome = f.windowed_outcome(events, self.grades, self.years,
pd.Timestamp(follow_up_end)) # fmt: skip
labelled = found.merge(outcome, on="person_id")
labelled = labelled[labelled["known"]].reset_index(drop=True)
train, test = f.split(labelled, TRAIN_FRACTION)
X = list(self.predictors)
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
model.fit(train[X], train["y"])
p = model.predict_proba(test[X])[:, 1]
metrics = {
"n_train": len(train),
"n_test": len(test),
"events_train": float(train["y"].sum()),
"events_test": float(test["y"].sum()),
"auc": float(roc_auc_score(test["y"], p)),
"brier": float(brier_score_loss(test["y"], p)),
"positive_rate_train": float(train["y"].mean()),
"positive_rate_test": float(test["y"].mean()),
"mean_probability_test": float(p.mean()),
}
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
members = f.index_sample(f.prepared(events), list(self.predictors))
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
p = model.predict_proba(members[list(self.predictors)])[:, 1]
return _rows(members, p[:, None], (self.years,))
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's most recent observations up to her index (that day included): her age
group, the KPNC category of her latest cytology result and her latest HPV result."""
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (35, 45, 55))
prior = events[events["date"] <= events["index_date"]]
names = list(cacu.KPNC)
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
results = prior[(prior["type"] == "bethesda") & prior["value_code"].notna()]
latest = results[results["date"] == results.groupby("person_id")["date"].transform("max")]
ranks = latest["value_code"].map(severity).groupby(latest["person_id"]).max()
found["cytology"] = ranks.map(lambda r: None if pd.isna(r) else names[int(r)])
hpv = prior[(prior["type"] == "hpv") & prior["value_code"].notna()]
hpv = hpv.sort_values(["date", "source_id"])
found["hpv"] = hpv.groupby("person_id")["value_code"].last()
return found.astype(object)
_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 = {
m.name: m
for m in [
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=("referral_grade",),
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")),
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
interval_level=0.95),
]
} # fmt: skip
-21
View File
@@ -1,21 +0,0 @@
from typing import Any
from models.base import ScreeningModel
class CaMaModel(ScreeningModel):
"""Scaffold for the CaMa (breast cancer) screening model.
Can pull its own training data straight from `persistance.cama`'s
repositories (`paciente_repository`, `mastografia_repository`,
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
No real model yet; this is interface scaffolding only.
"""
domain = "cama"
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaMa training is not implemented yet.")
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaMa prediction is not implemented yet.")
View File
+8
View File
@@ -0,0 +1,8 @@
"""CaMa's training and scoring jobs (models.jobs) over its models and their reports."""
from models import survival
from models.cama.specs import MODELS
from models.jobs import Jobs
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
train, score = JOBS.train, JOBS.score
+93
View File
@@ -0,0 +1,93 @@
"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by
four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's,
refitted on each whole horizon cohort."""
from dataclasses import dataclass
import joblib
import numpy as np
import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
SOURCES = ("metabric", "scanb")
HORIZONS = modeling.HORIZONS # months
SAVED = "metabric"
def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
"""The source's cohort table, from its dataset's rows: fixed columns, then its
covariates as categories."""
return cohorts.prepare(source, rows).frame
@dataclass
class Recurrence:
"""Per horizon: the LR (intercept and coefficients of its terms) and the HBN (CPT over
its parents, keyed by their categories); the recurrence probability is their mean, and an
unseen parent configuration takes the horizon's recurrence rate."""
cohort: str
horizons: tuple[int, ...]
covariates: list[str]
tables: dict[int, dict]
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
"""The probability of recurrence by each horizon (`recurrence_{H}m`) for each row
of `X`, whose covariates are categories as in `cohort()` (missing: UNKNOWN)."""
found = X[self.covariates].astype(object)
found = found.where(found.notna(), cohorts.UNKNOWN).astype(str)
dummies = pd.get_dummies(found).astype(float)
out = {}
for h in self.horizons:
t = self.tables[h]
p_lr = np.full(len(found), t["lr_prior"])
if t["lr_terms"]:
x = dummies.reindex(columns=t["lr_terms"], fill_value=0.0).to_numpy()
logit = t["lr_constant"] + x @ np.asarray(t["lr_coefficients"])
p_lr = 1 / (1 + np.exp(-logit))
p_hbn = np.full(len(found), t["hbn_prior"])
if t["hbn_parents"]:
keys = map(tuple, found[t["hbn_parents"]].to_numpy())
p_hbn = np.array([t["hbn_cpt"].get(k, t["hbn_prior"]) for k in keys])
out[f"recurrence_{h}m"] = (p_lr + p_hbn) / 2
return pd.DataFrame(out, index=X.index)
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""Both cohorts' models, validation, calculator and risk factors, from their datasets'
rows.
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
stability criterion, are then missing)."""
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
try:
fits = modeling.fit(found, n_bootstrap)
drawn = {s: calculator.calculator(fits[s]) for s in SOURCES}
finally:
joblib.externals.loky.get_reusable_executor().shutdown(wait=True)
table = pd.concat([factors.risk_factors(fits[s]) for s in SOURCES], ignore_index=True)
summary = [row for s in SOURCES for row in factors.scenario_summary(fits[s], table)]
auc = [row for s in SOURCES for row in reports.auc_rows(fits[s])]
points = [row for s in SOURCES for row in drawn[s][1]]
saved = fits[SAVED]
model = Recurrence(SAVED, HORIZONS, saved.cohort.covariates, modeling.tables(saved))
technical = {
"model": "recurrence",
"cohort": "metabric+scanb",
"method": "stepwise logistic regression + Bayesian network (BDeu), averaged",
"rutinas": reports.routines(found, n_bootstrap),
"recurrencia_desarrollo": reports.development(auc, table, points, summary),
}
interpretability = {
"model": "recurrence",
"kind": "scenarios",
"recurrencia": reports.figures([r for s in SOURCES for r in drawn[s][0]]),
}
reports_ = {"technical_validation": technical, "interpretability": interpretability}
return model, reports.metrics(auc), reports_
+211
View File
@@ -0,0 +1,211 @@
"""The recurrence calculator: for clinical scenarios of each cohort, the mean recurrence-free
probability the LR + HBN average gives its patients at each horizon, with a 95 % interval from
refits on resamples of the whole cohort, next to the scenario's observed survival (Kaplan-Meier)
and its classic and fractional Weibull curves.
The models are refitted on the whole cohort (and on each resample) with the terms and parents
the split chose; the HBN's pseudo-count counts every level of the cohort, seen in the
(re)sample or not."""
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
RESAMPLES = 200
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
CAP_MONTHS = 72 # the Weibull curves' extent
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
# Each scenario: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
} # fmt: skip
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
return {
name: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in cond.items()])
for name, cond in scenarios.items()
}
@dataclass
class Risk:
"""The cohort coded once: dummies for the LR, integer codes for the HBN."""
fitted: CohortFit
def __post_init__(self):
frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates
self.n = len(frame)
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()}
self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()
def _key(self, chosen, rows) -> np.ndarray:
key = np.zeros(len(rows), dtype=np.int64)
for p in chosen:
key = key * self.levels[p] + self.codes[p][rows]
return key
def _combined(self, rows, horizon) -> np.ndarray | None:
"""Every patient's (LR + HBN) / 2, fitted on `rows`; None when the LR fails."""
t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon)
known = recurred | (t > horizon)
train, y = rows[known], recurred[known].astype(int)
split = self.fitted.horizons[horizon].split
p_lr = p_hbn = np.full(self.n, y.mean())
if split.terms:
m = logit(y, self.X.iloc[train][split.terms].reset_index(drop=True), "add")
if m is None:
return None
p_lr = m.predict(sm.add_constant(self.X[split.terms], has_constant="add")).to_numpy()
if split.parents:
q = int(np.prod([self.levels[p] for p in split.parents]))
a = ESS / (2 * q)
key = self._key(split.parents, train)
table = (pd.Series(y, index=key).groupby(level=0).sum() + a) / (
pd.Series(1, index=key).groupby(level=0).sum() + 2 * a
)
everyone = self._key(split.parents, np.arange(self.n))
p_hbn = table.reindex(everyone).fillna(y.mean()).to_numpy()
return (p_lr + p_hbn) / 2
def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None:
"""Per scenario, the mean risk at each horizon over its patients in `rows` (repeats
counted); None when a refit fails."""
out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks}
for j, h in enumerate(HORIZONS):
combined = self._combined(rows, h)
if combined is None:
return None
for name, mask in scenario_masks.items():
inside = mask[rows]
if inside.any():
out[name][j] = combined[rows][inside].mean()
return out
def _curves(months, event, observed):
d, c, _ = curves.life_table(months, event)
k, lam = curves.fit_weibull(d, c)
fractional = curves.fit_fractional(d, c, k, lam)
grid = np.linspace(0, CAP_MONTHS, GRID_POINTS)
return {
"km": dict(
zip(("S", "low", "high"), curves.kaplan_meier(months, event, observed), strict=True)
),
"weibull": curves.weibull(grid, k, lam),
"weibull_fractional": curves.fractional(grid, k, *fractional),
"grid": grid,
}
def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]:
"""The figure record of each scenario with enough recurrences, and its table rows."""
source = fitted.cohort.source
scenarios = SCENARIOS[source] if scenarios is None else scenarios
risk = Risk(fitted)
found = masks(fitted.cohort.frame, scenarios)
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)]
months = np.floor(risk.time).astype(int)
event = risk.event == 1
drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS}
jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()]
jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples] # the long ones first
done = Parallel(n_jobs=-1)(jobs)
fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :]
replicas = [r for r in resampled if r is not None]
records, rows = [], []
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
free = 1 - point[name]
risks = np.array([r[name] for r in replicas])
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0)
observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum())
km, grid = drawn_curves["km"], drawn_curves["grid"].tolist()
records.append(
{
"cohorte": source,
"cohorte_nombre": LABELS[source],
"escenario": name,
"condiciones": scenarios[name],
"n": n,
"recaidas": events,
"horizons_months": list(HORIZONS),
"observado_hasta": observed,
"months_max": CAP_MONTHS,
"km": {
"months": list(range(observed + 1)),
**{k: v.tolist() for k, v in km.items()},
},
"weibull": {"t": grid, "S": drawn_curves["weibull"].tolist()},
"weibull_fractional": {"t": grid, "S": drawn_curves["weibull_fractional"].tolist()},
"points": {
"COMB": {
"S": free.tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist(),
}
},
"bootstrap_replicas": len(replicas),
}
)
for j, h in enumerate(HORIZONS):
rows.append(
{
"cohorte": source,
"subgrupo": name,
"n": n,
"recaidas": events,
"horizonte_meses": h,
"S_libre_LR_HBN": free[j],
"IC95_inf": low[j],
"IC95_sup": high[j],
"riesgo_recurrencia": 1 - free[j],
"S_libre_KM": km["S"][min(h, observed)] if h <= observed else np.nan,
"replicas_bootstrap": len(replicas),
}
)
return records, rows
+171
View File
@@ -0,0 +1,171 @@
"""Each reference cohort as one table of categories, from its dataset as the platform loaded
it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
`line` the order the file is published in): the patients with a known recurrence time and
status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN);
nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's
V >= V_MAX), the one with more unknowns is dropped."""
from dataclasses import dataclass
import pandas as pd
from scipy.stats.contingency import association
UNKNOWN = "Desconocido"
V_MAX = 0.80
DAYS_PER_MONTH = 30.4375
# Bands, closed on the left: [a, b).
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
GRADES = {"1": "1", "2": "2", "3": "3"}
FIXED = {
"metabric": ["paciente", "tiempo_meses", "evento"],
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
}
TREATMENT = {
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
}
# Covariates taken as they come (our name: the dataset's column).
PASSTHROUGH = {
"metabric": {
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
"Estado_menopausico": "inferred_menopausal_state",
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
},
"scanb": {
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
},
} # fmt: skip
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
def _number(s: pd.Series) -> pd.Series:
return pd.to_numeric(s, errors="coerce")
def _text(s: pd.Series) -> pd.Series:
"""As text; missing values are UNKNOWN."""
return s.astype(object).where(s.notna(), UNKNOWN).astype(str)
def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
return rows.sort_values("line", kind="stable").reset_index(drop=True)
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
d = d.reset_index(drop=True)
out = pd.DataFrame({"paciente": d["patient_id"]})
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
load = _number(d["mutation_count"])
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
for name, column in PASSTHROUGH["metabric"].items():
out[name] = _text(d[column])
return out
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows)
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
out = pd.DataFrame({"paciente": d["patient_name"]})
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
out["evento"] = rfi.astype(int)
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
for name, column in PASSTHROUGH["scanb"].items():
out[name] = _text(d[column])
return out
def cramers_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b).to_numpy()
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]:
"""The covariates to drop: pairs by decreasing V (ties: by decreasing names); of each pair
with V >= v_max and neither already dropped, the one with the larger share of unknowns
(on a tie, the first of the pair)."""
pairs = sorted(
(
(cramers_v(frame[a], frame[b]), a, b)
for i, a in enumerate(candidates)
for b in candidates[i + 1 :]
),
reverse=True,
)
unknown = {c: (frame[c] == UNKNOWN).mean() for c in candidates}
dropped = []
for v, a, b in pairs:
if v < v_max:
break
if a not in dropped and b not in dropped:
dropped.append(a if unknown[a] >= unknown[b] else b)
return dropped
@dataclass(frozen=True)
class Cohort:
"""A source's cohort table and what its covariates are."""
source: str
frame: pd.DataFrame # fixed columns, then the kept covariates
covariates: list[str]
treatment: list[str]
eliminated: list[str]
@property
def intrinsic(self) -> list[str]:
return [c for c in self.covariates if c not in self.treatment]
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
fixed, treatment = FIXED[source], TREATMENT[source]
covariates = [c for c in full.columns if c not in fixed]
dropped = collinear(full, [c for c in covariates if c not in treatment])
kept = [c for c in covariates if c not in dropped]
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped)
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
"""The patients whose status at `horizon` months is known (a recurrence by then, or
followed past it), with `y` = recurred by then."""
t, event = frame["tiempo_meses"], frame["evento"] == 1
found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True)
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
return found
def unknown_shares(cohort: Cohort) -> dict[str, float]:
return {c: float((cohort.frame[c] == UNKNOWN).mean()) for c in cohort.covariates}
+262
View File
@@ -0,0 +1,262 @@
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has.
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
most frequent category by four criteria: (1) its adjusted odds ratio's 95 % CI excludes 1 and
its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least FREQ_MIN of
the time; (3) its covariate is a parent of the HBN; (4) its Kaplan-Meier recurrence-free
survival at the horizon differs from the reference's (95 % CI) in the odds ratio's direction.
"Robusto" needs (1) and three criteria, "sugerente" two. Treatments get their odds ratios,
adjusted for the intrinsic covariates, but no class: they are associations, not effects."""
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import false_discovery_control
from models.cama.recurrence.calculator import SCENARIOS, masks
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
from models.cama.recurrence.modeling import CohortFit, variable_of
from models.curves import life_table
ALPHA = 0.05
FREQ_MIN = 0.80
Z = 1.96
ORDER = {
"riesgo robusto": 0,
"protector robusto": 1,
"riesgo sugerente": 2,
"protector sugerente": 3,
"no concluyente": 4,
}
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
COLUMNS = [
"cohorte",
"horizonte_meses",
"tipo",
"variable",
"categoria",
"referencia",
"n_categoria",
"OR_recurrencia",
"IC95_inf",
"IC95_sup",
"p",
"p_ajustado_BH",
"freq_seleccion_bootstrap",
"en_manta_markov",
"S_libre_categoria",
"S_libre_referencia",
"delta_S",
"delta_IC95_inf",
"delta_IC95_sup",
"c1_or",
"c2_estabilidad",
"c3_manta_markov",
"c4_supervivencia",
"criterios_cumplidos",
"clasificacion",
]
# Scenario presence: the share of the scenario's patients in the category.
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria")
def km_at(months, event, horizon) -> tuple[float, float]:
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
d, _, n = life_table(months, event)
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
last = min(horizon, len(d) - 1) + 1
S = float(np.prod(q[:last]))
return S, S * float(np.sqrt(np.sum(v[:last])))
def _odds_ratios(data: pd.DataFrame, y, variables, reference) -> pd.DataFrame:
"""Logistic GLM on every category but each covariate's reference (constant and
duplicated dummies dropped): odds ratios with Wald 95 % CI and p."""
X = pd.get_dummies(data[variables]).astype(float)
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = np.exp(m.conf_int().loc[X.columns])
return pd.DataFrame(
{
"termino": X.columns,
"OR_recurrencia": np.exp(m.params[X.columns].to_numpy()),
"IC95_inf": ci[0].to_numpy(),
"IC95_sup": ci[1].to_numpy(),
"p": m.pvalues[X.columns].to_numpy(),
}
)
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
cohort = fitted.cohort
frame = at_horizon(cohort.frame, horizon)
data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy()
reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates}
t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]
months = np.floor(np.minimum(t, horizon + 1)).astype(int)
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
def complete(table, variables):
"""Each term's covariate, category, BH p and survival difference to its reference."""
table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
]
table["referencia"] = table["variable"].map(reference)
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
rows = []
for v, cat, ref in zip(
table["variable"], table["categoria"], table["referencia"], strict=True
):
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == ref).to_numpy()
(sa, ea), (sb, eb) = (
km_at(months[a], event[a], horizon),
km_at(months[b], event[b], horizon),
)
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
rows.append(
{
"n_categoria": int(a.sum()),
"S_libre_categoria": sa,
"S_libre_referencia": sb,
"delta_S": delta,
"delta_IC95_inf": delta - Z * se,
"delta_IC95_sup": delta + Z * se,
}
)
return pd.concat([table, pd.DataFrame(rows)], axis=1)
intrinsic, treatment = cohort.intrinsic, cohort.treatment
tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic)
risk = tab["OR_recurrencia"] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab["delta_S"]) == np.where(risk, -1, 1))
hz = fitted.horizons[horizon]
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
lambda v: np.nan if selection is None else selection.get(v, 0.0)
)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
tab["clasificacion"] = [
"no aplica (categoria desconocida)"
if cat == UNKNOWN
else f"{d} robusto"
if c1 and k >= 3
else f"{d} sugerente"
if k >= 2
else "no concluyente"
for cat, d, c1, k in zip(
tab["categoria"],
tab["direccion"],
tab["c1_or"],
tab["criterios_cumplidos"],
strict=True,
)
]
tab["tipo"] = "factor de riesgo"
if treatment:
both = intrinsic + treatment
tr = _odds_ratios(data, y, both, reference)
of = tr["termino"].map(lambda x: variable_of(x, both))
tr = complete(
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
)
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon
return tab
def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame:
"""Every horizon's table: by horizon, factors before treatments, by class, by odds ratio
(decreasing); rounded to 4 places. `selection` (per horizon, the share of bootstrap LRs
each covariate entered) defaults to the fit's own bootstrap."""
if selection is None:
covariates = fitted.cohort.covariates
selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()}
with warnings.catch_warnings(), np.errstate(over="ignore"):
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons]
tab = pd.concat(found, ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
keys = ["horizonte_meses", "_kind", "_order", "OR_recurrencia"]
tab = tab.sort_values(keys, ascending=[True, True, True, False])
return tab[COLUMNS].round(4)
def _presence(share: float) -> str:
if share >= DEFINING:
return "definitoria"
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
def _listing(part: pd.DataFrame) -> str:
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
`asociacion`."""
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join(
f"{v}={c} ({s}, {p:.0%})"
for v, c, s, p in zip(
part["variable"], part["categoria"], strength, part["share"], strict=True
)
)
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
"""Per scenario and horizon, the classified factors and treatments nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
frame, source = fitted.cohort.frame, fitted.cohort.source
scenarios = SCENARIOS[source]
found = factors[
(factors["cohorte"] == source)
& factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")
]
kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
)
found = found.assign(tipo_efecto=kind)
rows = []
for name, mask in masks(frame, scenarios).items():
if not mask.any() or found.empty:
continue
share = [
float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True)
]
detail = found.assign(share=share, presence=[_presence(s) for s in share])
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
for h in fitted.horizons:
d = detail[detail["horizonte_meses"] == h]
row = {
"cohorte": source,
"escenario": name,
"definicion": definition,
"n_escenario": int(mask.sum()),
"horizonte_meses": h,
}
for k in ("riesgo", "protector", "tratamiento"):
for level, label in (
("definitoria", "definitorios"),
("mayoritaria", "mayoritarios"),
):
row[f"{k}_{label}"] = _listing(
d[(d["tipo_efecto"] == k) & (d["presence"] == level)]
)
included = (d["tipo_efecto"] == "riesgo") & d["presence"].isin(DESCRIBING)
row["n_factores_riesgo_incluidos"] = int(included.sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
rows.append(row)
return rows
+299
View File
@@ -0,0 +1,299 @@
"""Per horizon, two models of recurrence by then: a logistic regression (LR) on the dummies a
stepwise selection keeps, and a Bayesian network (HBN) whose outcome's parents a greedy BDeu
search picks, predicting by its conditional probability table. Each is validated on a
stratified 70/30 split of the horizon's cohort (AUC) and on bootstrap resamples of it (each
replicate its own 70/30 split); a penalized Cox model's C-index rates the whole follow-up.
Resamples are drawn in order from one seeded generator and fitted in parallel, so every
replicate is the same however many workers run them."""
import warnings
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.structure_score import BDeu
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.recurrence.cohorts import Cohort, at_horizon
HORIZONS = (12, 36, 60) # months
SEED = 42
TEST_SIZE = 0.3
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
MAX_PARENTS = 6
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
MAX_STEPS = 200
COX_PENALIZER = 0.05
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
N_BOOTSTRAP = {"metabric": 100, "scanb": 40}
# ---------------------------------------------------------------- logistic regression
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
"""Dummies (each covariate's alphabetically first level is the reference), the
non-constant ones; a term is `{covariate}_{level}`."""
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
"""Maximum-likelihood logistic regression with an intercept, or None when it fails."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
X = sm.add_constant(X, has_constant=has_constant)
return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def stepwise(X: pd.DataFrame, y) -> list[str]:
"""Forward (the smallest Wald p < ALPHA_IN enters) then backward (the largest p >
ALPHA_OUT leaves) until nothing changes; the terms in the order they entered."""
included = []
for _ in range(MAX_STEPS):
changed, best, best_p = False, None, ALPHA_IN
for c in X.columns:
if c in included:
continue
m = logit(y, X[included + [c]])
if m is not None and m.pvalues[c] < best_p:
best, best_p = c, m.pvalues[c]
if best is not None:
included.append(best)
changed = True
if included and (m := logit(y, X[included])) is not None:
p = m.pvalues.drop("const")
if p.max() > ALPHA_OUT:
included.remove(p.idxmax())
changed = True
if not changed:
break
return included
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
"""The terms selected on `train` (univariate prefilter, then stepwise) and the test
rows' predicted probabilities (the training rate when no term is selected)."""
X = encode(pd.concat([train, test]), covariates)
X_train = X.loc[train.index]
X_train = X_train.loc[:, X_train.nunique() > 1]
y = train["y"]
candidates = [
c
for c in X_train.columns
if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER
]
terms = stepwise(X_train[candidates], y) if candidates else []
if not terms:
return [], np.full(len(test), y.mean())
m = logit(y, X_train[terms])
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
return terms, m.predict(X_test).to_numpy()
# ---------------------------------------------------------------- Bayesian network
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
table = frame[covariates].astype(str)
table["outcome"] = frame["y"].astype(int).astype(str)
return table
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
"""Greedy: the covariate whose addition most raises the outcome's BDeu score, while
any does (up to MAX_PARENTS); the parents in the order chosen."""
score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS:
best, gain = None, 0.0
for c in [c for c in covariates if c not in chosen]:
g = score.local_score("outcome", (*chosen, c)) - current
if g > gain:
best, gain = c, g
if best is None:
break
chosen.append(best)
current += gain
return chosen
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
"""P(recurrence | parents) for each configuration seen, smoothed by ESS / (2 q) per cell;
`q`, the number of configurations, defaults to the levels seen in `table`."""
q = q or int(np.prod([table[p].nunique() for p in chosen]))
a = ESS / (2 * q)
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
return {
(k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
for k, r in counts.iterrows()
}
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
"""The test rows' probabilities by the CPT of `train`; unseen configurations (or no
parents) get the training rate."""
rate = (train["outcome"] == "1").mean()
if not chosen:
return np.full(len(test), rate)
table = cpt(train, chosen)
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
# ---------------------------------------------------------------- one split, one cohort
@dataclass(frozen=True)
class Split:
"""The two models' selection and AUC on one 70/30 split."""
terms: list[str]
parents: list[str]
auc_lr: float
auc_hbn: float
def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split:
train, test = train_test_split(
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
)
terms, p_lr = lr(train, test, covariates)
bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
chosen = parents(bn_train, covariates)
p_hbn = hbn(bn_train, bn_test, chosen)
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
def _replicate(frame, covariates, rows, b) -> Split | None:
"""Bootstrap replicate `b`: the split (seed SEED + b) of the resample `rows`; None when
any fit fails (the replicate is then not counted)."""
try:
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
except Exception:
return None
def c_index(cohort: Cohort) -> float:
"""Harrell's C of a ridge-penalized Cox model on the whole follow-up, by a 70/30 split
stratified by event; dummies with fewer than COX_MIN_COUNT patients on a side are left out."""
time_event = ["tiempo_meses", "evento"]
X = pd.get_dummies(
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
).astype(float)
X = X.loc[:, X.nunique() > 1]
train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"])
n = len(train)
keep = [
c
for c in X.columns
if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT
]
cox = CoxPHFitter(penalizer=COX_PENALIZER)
cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5})
risk = cox.predict_partial_hazard(test[keep])
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
def variable_of(term: str, covariates: list[str]) -> str:
"""The covariate a dummy belongs to (the longest name it starts with)."""
found = [c for c in covariates if term.startswith(c + "_")]
return max(found, key=len) if found else term
@dataclass
class Horizon:
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
covariate entered the LR and the HBN)."""
n: int
events: int
split: Split
replicates: list[Split] = field(default_factory=list)
@property
def aucs(self) -> np.ndarray:
return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2)
def selection(self, covariates: list[str]) -> dict[str, float] | None:
"""Share of the replicates whose final LR has a term of each covariate."""
if not self.replicates:
return None
counts = {}
for r in self.replicates:
for v in {variable_of(t, covariates) for t in r.terms}:
counts[v] = counts.get(v, 0) + 1
return {v: k / len(self.replicates) for v, k in counts.items()}
@dataclass
class CohortFit:
cohort: Cohort
c_index: float
horizons: dict[int, Horizon]
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
"""Every cohort's split fits, bootstrap replicates and C-index, in one pool of workers.
Each horizon's resamples come from a fresh generator seeded SEED."""
frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS}
tasks = []
for (s, h), frame in frames.items():
rng = np.random.default_rng(SEED)
rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))]
tasks += [
((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b))
for b, r in enumerate(rows)
]
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks))
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
out = {}
for s, cohort in cohorts.items():
horizons = {}
for h in HORIZONS:
frame = frames[(s, h)]
reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
horizons[h] = Horizon(
len(frame),
int(frame["y"].sum()),
results[(s, h, "split")],
[r for r in reps if r is not None],
)
out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
return out
def tables(fitted: CohortFit) -> dict[int, dict]:
"""What the saved model keeps per horizon: the split's LR terms refitted on the whole
horizon cohort, and the split's HBN parents with their CPT on it."""
found = {}
for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h)
covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
prior = float(frame["y"].mean())
entry = {
"lr_prior": prior,
"lr_terms": terms,
"lr_constant": 0.0,
"lr_coefficients": [],
"hbn_parents": chosen,
"hbn_prior": prior,
"hbn_cpt": {},
}
if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None:
entry["lr_constant"] = float(m.params["const"])
entry["lr_coefficients"] = [float(m.params[t]) for t in terms]
if chosen:
entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen)
found[h] = entry
return found
+163
View File
@@ -0,0 +1,163 @@
"""What the governance page draws, as JSON: the development tables (AUC, risk factors,
calculator points, scenario summaries) and the scenarios' figures, as v1 published them in
`analisis/recurrencia_desarrollo.json` and `analisis/recurrencia.json`, and the five routine
records (`rutinas/`)."""
import numpy as np
import pandas as pd
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
from models.cama.recurrence.modeling import (
ALPHA_IN,
ALPHA_OUT,
COX_PENALIZER,
ESS,
HORIZONS,
MAX_PARENTS,
N_BOOTSTRAP,
CohortFit,
)
VERSION = 1
AUC_COLUMNS = [
"cohorte",
"horizonte_meses",
"modelo",
"n_modelo",
"recurrencias",
"AUC_validacion_interna",
"AUC_bootstrap_medio",
"AUC_bootstrap_IC95_inf",
"AUC_bootstrap_IC95_sup",
"replicas_bootstrap",
]
def table(rows, columns=None) -> dict:
"""Columns and records; NaN and infinities are null."""
frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object)
return {
"columnas": [str(c) for c in frame.columns],
"filas": frame.where(frame.notna(), None).to_dict("records"),
}
def auc_rows(fitted: CohortFit) -> list[dict]:
"""Per horizon and model, the AUC on the internal split and over the bootstrap
replicates (mean, 2.5 and 97.5 percentiles); then the Cox model's C-index."""
source, rows = fitted.cohort.source, []
for h, hz in fitted.horizons.items():
for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))):
aucs = hz.aucs[:, j]
boot = (
[np.nanmean(aucs), *np.nanpercentile(aucs, [2.5, 97.5])]
if len(aucs)
else [None] * 3
)
rows.append(
{
"cohorte": source,
"horizonte_meses": h,
"modelo": name,
"n_modelo": hz.n,
"recurrencias": hz.events,
"AUC_validacion_interna": internal,
**dict(zip(AUC_COLUMNS[6:9], boot, strict=True)),
"replicas_bootstrap": len(aucs) if len(aucs) else None,
}
)
frame = fitted.cohort.frame
rows.append(
{
"cohorte": source,
"horizonte_meses": "completo",
"modelo": "Cox penalizado (C-index)",
"n_modelo": len(frame),
"recurrencias": int(frame["evento"].sum()),
"AUC_validacion_interna": fitted.c_index,
}
)
return [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in rows]
def metrics(auc: list[dict]) -> dict[str, float]:
"""v1's metric names: `{cohort}.auc_{LR|HBN}_{H}m` (internal split), with `_bootstrap`
(the replicates' mean), and `{cohort}.c_index_cox`."""
found = {}
for r in auc:
if r["horizonte_meses"] == "completo":
found[f"{r['cohorte']}.c_index_cox"] = float(r["AUC_validacion_interna"])
continue
tag = f"{r['cohorte']}.auc_{r['modelo']}_{r['horizonte_meses']}m"
found[tag] = float(r["AUC_validacion_interna"])
if r.get("AUC_bootstrap_medio") is not None:
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
return found
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"""The five routine records a promotion reads."""
return {
"MUESTREO": {
"cohortes": {
s: {
"pacientes": len(c.frame),
"recaidas": int(c.frame["evento"].sum()),
"covariables": len(c.covariates),
"eliminadas_por_colinealidad": c.eliminated,
}
for s, c in cohorts.items()
},
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
"origen": "METABRIC y SCAN-B (externas)",
},
"DATOS_FALTANTES": {
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
"no se imputa ni se descarta",
"desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
},
"METODO_ANALITICO": {
"modelos": "regresión logística con selección stepwise y red bayesiana con padres "
"del desenlace por BDeu, uno por horizonte",
"horizontes_meses": list(HORIZONS),
"alfa_entrada": ALPHA_IN,
"alfa_salida": ALPHA_OUT,
"ess_bdeu": ESS,
"maximo_de_padres": MAX_PARENTS,
"cox_penalizado": COX_PENALIZER,
"combinacion": "promedio de la LR y la HBN",
},
"BALANCE_CLASES": {
"aplica": False,
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres "
"de ella después; no se rebalancea",
},
"CONFIANZA_SALIDA": {
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
"bootstrap",
"replicas": {
**{s: n_bootstrap.get(s, 0) for s in N_BOOTSTRAP},
"calculadora": RESAMPLES,
},
"eventos_minimos_por_escenario": MIN_EVENTS,
},
}
def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict:
"""`recurrencia_desarrollo`: the tables behind the figures."""
return {
"version": VERSION,
"tablas": {
"auc": table(auc, AUC_COLUMNS),
"factores_riesgo": table(factors),
"calculadora": table(pd.DataFrame(points).round(4)),
"escenarios_resumen": table(summary),
},
}
def figures(records: list[dict]) -> dict:
"""`recurrencia`: each scenario's curves and calculator points."""
return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records}
+157
View File
@@ -0,0 +1,157 @@
"""The CaMa models.
- Survival: mortality at 6, 12 and 18 months from the first invasive biopsy report, by
interval survival (models.survival) over the age at the index, that report's results
(stage among them) and the first course of treatment. The first course follows SEER's
convention: what the patient received in the TREATMENT_DAYS after the index, taken as
known at it. A patient who dies before her treatment counts as untreated (immortal-time
bias), which the technical report states.
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on two public reference
cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the
`cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a
quarter of an hour), so it trains only when asked for by name."""
from dataclasses import dataclass, field
import pandas as pd
from models.survival import DAYS_PER_YEAR, Spec, age_group, band
from persistance import nodes
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
RESULT_DAYS = 30
TREATMENT_DAYS = 365
# Stage groups (AJCC): 0, I, II, III, IV, as the clinical scenarios name them.
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
SURGERY = ("breast_conserving_surgery", "mastectomy") # the most extensive one counts
# The clinical scenarios the survival report draws (as the SEER-trained original named them).
STAGE_0_II, STAGE_III_IV = ("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV"))
HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative")
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
CONSERVING = ("surgery", "==", "breast_conserving_surgery")
def _younger(years):
return ("age", "<", years)
def _older(years):
return ("age", ">=", years)
SCENARIOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": (HER2_POS, _older(60), STAGE_III_IV),
"HER2+ · <60 años · estadio 0–II (Bajo)": (HER2_POS, _younger(60), STAGE_0_II),
"Estadio IV": (("stage", "in", ("IV",)),),
"Estadio I": (("stage", "in", ("I",)),),
"≥ 75 años": (_older(75),),
"< 45 años": (_younger(45),),
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
_younger(45), HER2_NEG, STAGE_0_II, CONSERVING),
"HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING),
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING),
"Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II),
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
_older(65), HER2_NEG, STAGE_0_II, CONSERVING),
} # fmt: skip
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's age group at the index and her index report's results, in bands where
they are numbers (Ki-67 %, tumour size in mm)."""
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (45, 60, 75))
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
found["age"] = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
days = (events["date"] - events["index_date"]).dt.days
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
for kind in RESULTS:
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
for name, kind, cuts in (("ki67_group", "ki67_pct", (14, 20)),
("size_group", "size_mm", (20, 50))): # fmt: skip
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
found[name] = band(value.reindex(found.index), list(cuts))
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
found["stage"] = stage.reindex(found.index).map(STAGE_GROUP)
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
given = course.groupby("person_id")["value_code"].agg(set).reindex(found.index)
given = given.apply(lambda g: g if isinstance(g, set) else set())
found["surgery"] = given.apply(lambda g: next((s for s in reversed(SURGERY) if s in g), "none"))
for name in ("chemotherapy", "radiotherapy"):
found[name] = given.apply(lambda g, n=name: "yes" if n in g else "no")
return found
@dataclass(frozen=True)
class ReferenceRecurrence:
"""The recurrence model over the reference cohorts the `pipeline` loaded: one source node
per cohort, named as the cohort."""
name: str
pipeline: str = "cama_reference"
cohort: None = None # trains on no gold cohort, and scores no patient
slow: bool = True
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
def train(self, events, as_of=None) -> tuple:
from models.cama import recurrence
model, metrics, reports = recurrence.train(self.datasets())
return model, metrics, reports
def datasets(self) -> dict[str, pd.DataFrame]:
"""Each reference cohort's rows, as the pipeline loaded them."""
from models.cama import recurrence
found = {s: pd.DataFrame(nodes.rows(self.pipeline, s)) for s in recurrence.SOURCES}
if any(r.empty for r in found.values()):
raise LookupError(f"load the reference cohorts first (pipeline {self.pipeline})")
return found
def predict(self, model, events) -> pd.DataFrame:
return model.predict(events)
MODELS = {
"survival": Spec(
name="survival",
cohort="cama_cohort_survival",
features=(
"age_group",
*RESULTS,
"ki67_group",
"size_group",
"stage",
"surgery",
"chemotherapy",
"radiotherapy",
),
covariates=covariates,
# As the SEER-trained original: stage, histologic type and the first course, and age.
parents=(
"stage",
"histologic_type",
"surgery",
"chemotherapy",
"radiotherapy",
"age_group",
),
borders=(0, 6, 12, 18),
cap_months=24,
scenarios=SCENARIOS,
scenario_columns=("age",),
notes=(
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
"antes de su tratamiento cuenta como no tratada (sesgo de tiempo inmortal): el "
"efecto protector del tratamiento aparece mayor de lo que es.",
),
),
"recurrence": ReferenceRecurrence("recurrence"),
}
+181
View File
@@ -0,0 +1,181 @@
"""Survival curves of a group (free of death, or of recurrence), from whole months of
follow-up: Kaplan-Meier with its Greenwood band (log-log scale), and a classic and a
fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of
events and censorings (an event in month m falls between S(m) and S(m+1); a censoring there
survives to m + 1/2). Fits start from several points and run each to the optimizer's
convergence; one that doesn't converge is an error, not a curve."""
import numpy as np
from scipy.optimize import minimize, minimize_scalar
from scipy.special import beta as beta_function
from scipy.special import betainc, gammaln
Z = 1.96
INVALID = 1e12 # the likelihood outside a model's parameter region
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
"""Per month: recurrences, censorings, and patients at risk at its start."""
months, event = np.asarray(months, int), np.asarray(event, bool)
length = max(length, int(months.max()) + 2)
d = np.bincount(months[event], minlength=length)
c = np.bincount(months[~event], minlength=length)
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
return d, c, at_risk
def kaplan_meier(months, event, until: int):
"""S, low, high at the start of months 0..until."""
d, _, n = life_table(months, event, until + 1)
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[: until + 1]
se = np.sqrt(np.concatenate([[0.0], np.cumsum(v)])[: until + 1]) / np.abs(np.log(S))
inside = (S > 0) & (S < 1)
return (
S,
np.where(inside, S ** np.exp(Z * se), S),
np.where(inside, S ** np.exp(-Z * se), S),
)
def _nll(survival, d, c) -> float:
T = len(d)
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
S, mid = both[: T + 1], both[T + 1 :]
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
return INVALID
p = np.clip(S[:-1] - S[1:], 1e-300, None)
return -(np.sum(d * np.log(p)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def weibull(t, k, lam):
return np.exp(-((np.asarray(t, float) / lam) ** k))
def fit_weibull(d, c) -> tuple[float, float]:
"""(k, lambda) of the classic Weibull, best of a 3 x 3 grid of Nelder-Mead starts."""
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50.0, 200.0, 1000.0):
r = minimize(
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
[np.log(k0), np.log(l0)],
method="Nelder-Mead",
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000},
)
r = _converged(r, "Weibull")
best = r if best is None or r.fun < best.fun else best
k, lam = np.exp(best.x)
return float(k), float(lam)
# ---------------------------------------------------------------- fractional Weibull
STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here)
class NotConverged(RuntimeError):
pass
def _converged(r, what: str):
if not r.success:
raise NotConverged(f"{what}: {r.message}")
return r
def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
"""S(t) with S(0) = 1 and Caputo derivative D^rho S(t) = -c t^s S(t) (0 < rho <= 1,
s + rho > 0): the Kilbas-Saigo function E_{rho, 1+s/rho, s/rho}(-c t^(rho+s)).
Solved as its Volterra equation, S(t) = 1 - c/G(rho) int_0^t (t-u)^(rho-1) u^s S(u) du,
by product integration in w = t^(rho+s), where S is a power series in z = c w and so
smooth: S is linear in w on each step, and the kernel's integrals against u^s and
u^(s+rho+s) are exact (incomplete beta functions). The steps are even in log(1 + z):
fine where S starts to fall, wide over its slow tail. No series, no extended precision."""
t = np.atleast_1d(np.asarray(t, float))
e = rho + s
top = float(t.max()) if t.size else 0.0
if top <= 0:
return np.ones_like(t)
w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c
w[-1] = top**e
grid = w ** (1 / e)
y = np.ones(STEPS + 1)
kappa = c / np.exp(gammaln(rho))
b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
dw = np.diff(w)
for n in range(1, STEPS + 1):
x = grid[: n + 1] / grid[n]
i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x))
ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
slope = (ie - w[:n] * i0) / dw[:n]
own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j
known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1])
return np.interp(t**e, w, y)
def fractional(t, k, alpha, beta, lam) -> np.ndarray:
"""The fractional Weibull's survival (Kilbas-Saigo, with the classic Weibull as its
alpha = beta = 1 case); NaN outside its parameter region."""
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full(t.shape, np.nan)
c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2)
return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0)
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]:
"""(rho, s, scale): the fractional Weibull is S(t) = g(z), z = scale (t/lambda)^(rho+s),
with g the Kilbas-Saigo survival of order rho and power s at c = 1."""
return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)))
def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
"""(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, by
maximum likelihood profiled over lambda: for each (alpha, beta), g is solved once over
every z the allowed lambdas (1 to 1e7) reach, and lambda is then fitted exactly on it.
(alpha, beta) is the best of a start at the classic fit (alpha = beta = 1, so it is
never worse) and a grid of others, each to Nelder-Mead's convergence."""
floor = max(0.0, 1.0 - k) + 1e-6
top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month)
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5])
lambdas = (0.0, np.log(1e7))
def unpack(p):
return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))
def profile(p) -> tuple[float, float]:
a, b = unpack(p)
if k + a <= 1 or k + a + b <= 2:
return INVALID, np.nan
rho, s, scale = _shape(k, a, b)
e = rho + s
z_top = scale * top**e # lambda = 1 reaches the farthest
z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1))
g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0)
def nll(log_lam: float) -> float:
found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g)
return _nll(lambda t: found, d, c)
coarse = np.linspace(*lambdas, 141)
i = int(np.argmin([nll(x) for x in coarse]))
r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
method="bounded", options={"xatol": 1e-9}) # fmt: skip
return float(r.fun), float(r.x)
starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0]]
starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)]
best = None
for p0 in starts:
options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000}
r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
r = _converged(r, "fractional Weibull")
best = r if best is None or r.fun < best.fun else best
a, b = unpack(best.x)
return float(a), float(b), float(np.exp(profile(best.x)[1]))
+304
View File
@@ -0,0 +1,304 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
import hashlib
import importlib
import inspect
import io
import json
import zipfile
from collections.abc import Callable
from datetime import date
import dagster as dg
from core.domains import Domain
from models import execution, graph
from models.jobs import EmptyCohort
from models.tea import jobs as tea_jobs
from models.tea import preview as tea_preview_analysis
from persistance import bundle, cluster, config_log, eeg, previews, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
class ExecutionConfig(dg.Config):
"""Where a heavy op's work runs: the fields of `persistance.cluster.Execution`."""
mode: str | None = None # Dagster's config has no Literal: `model()` checks it
scheduler: str | None = None
def model(self) -> cluster.Execution:
return cluster.Execution(**self.model_dump())
class ScopeConfig(dg.Config):
"""Which EEGs an analysis takes: the fields of `persistance.eeg.Scope`."""
mode: str = "pending" # Dagster's config has no Literal: `model()` checks it
n: int | None = None
ids: list[str] = []
def model(self) -> eeg.Scope:
return eeg.Scope(**self.model_dump()) # validates
class PipelineRun(dg.Config):
pipeline: str
version: int | None = None # default: the latest saved
@dg.op
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
"""Every node of the pipeline graph, inputs first. Returns the config version run."""
version, pipeline = config_log.get(config.pipeline, config.version)
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
graph.run(config.pipeline, pipeline, log=context.log.info)
return version
@dg.job(tags=WRITES)
def ingest():
run_pipeline()
def _jobs(domain: str):
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
try:
return importlib.import_module(f"models.{domain}.jobs")
except ModuleNotFoundError as e:
raise ValueError(f"{domain} has no models") from e
class ReferenceConfig(dg.Config):
name: str
line_hz: int = 50
def model(self) -> cluster.Reference:
return cluster.Reference(**self.model_dump())
class Training(dg.Config):
domain: str
models: list[str] = [] # default: every model of the domain but the slow ones
as_of: str | None = None # the date the data are taken up to (default: today)
execution: ExecutionConfig = ExecutionConfig()
reference: ReferenceConfig | None = None
@dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports."""
jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None
options = {}
if config.reference is not None:
if "reference" not in inspect.signature(jobs.train).parameters:
raise ValueError(f"{config.domain} models take no reference cohort")
options["reference"] = config.reference.model()
found = {}
with execution.running(context, config.execution.model()):
for name in config.models or jobs.JOBS.routine():
try:
found[name] = jobs.train(name, as_of, **options)
except EmptyCohort as e: # the site has no such patients; the others still train
found[name] = None
context.log.warning(f"{e}: not trained")
continue
context.log.info(f"{config.domain}.{name}: version {found[name]}")
return found
@dg.job
def train():
train_models()
class Scoring(dg.Config):
domain: str
models: list[str] = [] # default: every model of the domain
@dg.op
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()}
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") + "+"])
return found
@dg.job(tags=WRITES)
def score():
score_models()
class Analysis(dg.Config):
domain: str
execution: ExecutionConfig = ExecutionConfig()
@dg.op
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
with execution.running(context, config.execution.model()):
found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed")
return found
@dg.job(tags=WRITES)
def analyze():
analyze_studies()
class TeaAnalysis(dg.Config):
scope: ScopeConfig = ScopeConfig()
execution: ExecutionConfig = ExecutionConfig()
@dg.op
def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict:
"""The EEGs in scope, analysed in the chosen execution. Bronze is written after the last
study, so a cancel during the analysis leaves it as it was."""
with execution.running(context, config.execution.model()):
found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False)
context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})")
return {"analysed": found}
@dg.op
def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
"""Each age curve's champion scores every analysed EEG."""
found = tea_jobs.score_curves()
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
return {"scored": found}
@dg.op
def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
"""The ADOS-2 association champion scores the EEGs (a seam: nothing until Phase 2)."""
version = tea_jobs.relate()
context.log.info("ados2_association: " + (f"version {version}" if version else "no champion"))
return {"ados2_association": version}
@dg.op
def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict:
"""Gold's TEA tables rebuilt from bronze. A cancel here stops dbt between models, so gold
may be partly rebuilt until the next successful run (dbt replaces each model whole)."""
silver.build(tea_jobs.GOLD_SELECT)
context.log.info("gold rebuilt")
return {"built": tea_jobs.GOLD_SELECT}
class Preview(dg.Config):
edf: str
ados2: str | None = None
birth_date: str | None = None
pipeline: str = "tea"
@dg.op
def preview_study(context: dg.OpExecutionContext, config: Preview) -> dict:
try:
previews.sweep()
result = tea_preview_analysis.preview(
previews.get(config.edf),
previews.get(config.ados2) if config.ados2 else None,
date.fromisoformat(config.birth_date) if config.birth_date else None,
config.pipeline,
)
context.add_output_metadata(
{"result": dg.MetadataValue.json(json.loads(result.model_dump_json()))}
)
for warning in result.warnings:
context.log.warning(warning)
return {"valid": result.eeg.valid, "warnings": len(result.warnings)}
finally:
previews.discard([config.edf, config.ados2])
@dg.job(tags={"domain": "tea"})
def tea_preview():
preview_study()
@dg.job(tags={**WRITES, "domain": "tea"})
def tea_eeg():
"""Analyse the EEGs in scope, score the age curves, relate ADOS-2, rebuild gold."""
tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies())))
def pending_eegs() -> bool:
return bool(eeg.pending())
def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason:
"""A `tea_eeg` run for an ingest that left EEGs to analyse; otherwise a skip."""
if not has_pending():
return dg.SkipReason("the ingest brought no EEG to analyse")
return dg.RunRequest(
run_key=f"after-ingest-{run_id}",
run_config={"ops": {"tea_analyze_studies": {"config": {"scope": {"mode": "pending"}}}}},
tags={"domain": "tea", "triggered_by": run_id},
)
@dg.run_status_sensor(
name="tea_eeg_after_ingest",
run_status=dg.DagsterRunStatus.SUCCESS,
monitored_jobs=[ingest],
request_job=tea_eeg,
minimum_interval_seconds=10,
default_status=dg.DefaultSensorStatus.RUNNING,
)
def tea_eeg_after_ingest(context: dg.RunStatusSensorContext):
return after_ingest(context.dagster_run.run_id, pending_eegs)
class BundleImport(dg.Config):
domain: str
sha256: str
@dg.op
def import_bundle_files(context: dg.OpExecutionContext, config: BundleImport) -> dict:
path = bundle.staged(config.sha256)
try:
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != config.sha256:
raise bundle.BundleError("the staged file's SHA-256 does not match the run config")
result = bundle.import_(Domain(config.domain), data)
finally:
path.unlink(missing_ok=True)
with zipfile.ZipFile(io.BytesIO(data)) as archive:
manifest = json.loads(archive.read(bundle.MANIFEST))
skipped = set(result.skipped)
sources = sorted(
(item["name"], item["version"])
for item in manifest["versions"]
if (item["name"], item["version"]) not in skipped
)
for (_, source), (name, version) in zip(sources, result.imported, strict=True):
context.log.info(f"{name}: source v{source} -> version {version}")
for name, version in result.skipped:
context.log.warning(f"{name} v{version}: already registered, skipped")
return {
"imported": [list(item) for item in result.imported],
"skipped": [list(item) for item in result.skipped],
}
@dg.job
def import_bundle():
import_bundle_files()
defs = dg.Definitions(
jobs=[ingest, train, score, analyze, tea_eeg, tea_preview, import_bundle],
sensors=[tea_eeg_after_ingest],
)
+404
View File
@@ -0,0 +1,404 @@
"""The one way a heavy op spreads work over cores or machines: `map(fn, items)` returns the
results in input order whatever the mode (in this process, on local worker processes, on a
remote Dask scheduler). While it runs, a monitor thread reports progress: a JSON run tag the
API reads at once (Dagster shows op metadata only when the op returns, so the tag is the live
channel) and one throttled log line per tenth of the work. Ops never touch Dask themselves.
`with running(context, execution):` makes a Dagster op's context the ambient one, so that
`map` calls inside the block report on that run, share one cluster, and leave a summary in the
op's output metadata."""
import contextvars
import threading
import time
from collections.abc import Callable, Iterable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from itertools import islice
import dagster as dg
import psutil
from persistance import cluster
from persistance.cluster import (
PROGRESS_TAG,
ClusterVersionError,
Execution,
ExecutionError,
Health,
Options,
Progress,
Resolved,
Tasks,
Worker,
health,
options,
resolve,
)
__all__ = [
"ClusterVersionError",
"Execution",
"ExecutionError",
"Health",
"Options",
"Progress",
"Resolved",
"health",
"map",
"options",
"resolve",
"running",
]
SAMPLE_S = 2.0
_SINGLE_THREAD = {
"OMP_NUM_THREADS": "1",
"OPENBLAS_NUM_THREADS": "1",
"MKL_NUM_THREADS": "1",
}
class Eta:
"""Seconds left, from an exponentially smoothed rate of items per second."""
def __init__(self, alpha: float = 0.3, min_done: int = 3):
self.alpha, self.min_done = alpha, min_done
self.rate: float | None = None
self._last: tuple[float, int] | None = None
def update(self, elapsed_s: float, done: int) -> None:
last, self._last = self._last, (elapsed_s, done)
if last is None or elapsed_s <= last[0]:
return
rate = (done - last[1]) / (elapsed_s - last[0])
self.rate = rate if self.rate is None else self.alpha * rate + (1 - self.alpha) * self.rate
def eta_s(self, total: int) -> float | None:
done = self._last[1] if self._last else 0
if done < self.min_done or not self.rate or self.rate <= 0:
return None
return max(0, total - done) / self.rate
class _Ambient:
"""What `running` shares with the `map` calls in its block."""
def __init__(self, context, execution: Execution | None):
self.context, self.execution = context, execution
self.client = None
self.cluster = None
self.phases: list[dict] = []
self.peak_cpu_pct = 0.0
self.peak_memory_bytes = 0
def close(self) -> None:
_close(self.client, self.cluster)
self.client = self.cluster = None
_ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
"execution_ambient", default=None
)
def _close(client, local_cluster) -> None:
"""Close what this module opened; a remote scheduler is only disconnected from."""
for closable in (client, local_cluster):
if closable is not None:
try:
closable.close()
except Exception:
pass
def _counts(dask_scheduler) -> dict:
"""Run on the scheduler: how many tasks are in each state."""
counts: dict = {}
for task in dask_scheduler.tasks.values():
counts[task.state] = counts.get(task.state, 0) + 1
return counts
def _connect(resolved: Resolved, workers: int | None):
"""A client on the chosen Dask cluster and the local cluster it started, if any."""
from distributed import Client, LocalCluster
if resolved.mode == "local":
local = LocalCluster(
n_workers=cluster.local_workers(workers),
threads_per_worker=1,
processes=True,
memory_limit=cluster.memory_per_worker(),
dashboard_address=None,
env=_SINGLE_THREAD,
)
try:
return Client(local), local
except BaseException:
_close(None, local)
raise
try:
client = Client(resolved.scheduler, timeout=10)
except Exception as e:
raise ExecutionError(f"cannot reach the Dask scheduler {resolved.scheduler}: {e}") from e
detail = cluster.versions_error(client)
if detail is not None:
_close(client, None)
raise ClusterVersionError(
f"Dask workers differ from this server: {detail}. "
"Rebuild the worker image from the same commit."
)
return client, None
class _Monitor:
"""Samples one `map` every `SAMPLE_S` seconds and reports it."""
def __init__(self, ambient, resolved, phase, total, log, client):
self.ambient, self.resolved, self.phase = ambient, resolved, phase
self.total, self.log, self.client = total, log, client
self.done = 0
self.started = time.monotonic()
self.eta = Eta()
self.tasks: Tasks | None = None
self.last_tenth = 0
self.peak_cpu = 0.0
self.peak_memory = 0
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread = threading.Thread(target=self._loop, daemon=True)
self._process = psutil.Process()
def item_done(self) -> None:
with self._lock:
self.done += 1
def start(self) -> None:
self.report(force_log=True)
self._thread.start()
def stop(self, *, final: bool) -> None:
self._stop.set()
self._thread.join()
if final:
self.report(force_log=True)
def _loop(self) -> None:
while not self._stop.wait(SAMPLE_S):
self.report()
def _cluster_state(self) -> list[Worker]:
if self.client is None:
cpu = self._process.cpu_percent()
self.peak_cpu = max(self.peak_cpu, cpu)
self.peak_memory = max(self.peak_memory, self._process.memory_info().rss)
return []
workers = []
try:
info = self.client.scheduler_info()["workers"]
for w in info.values():
m = w.get("metrics", {})
workers.append(
Worker(
name=str(w.get("name", "")),
cpu_pct=float(m.get("cpu", 0.0)),
memory_bytes=int(m.get("memory", 0)),
memory_limit=w.get("memory_limit"),
executing=int(m.get("executing", 0)),
threads=int(w.get("nthreads", 1)),
)
)
except Exception:
return []
try:
counts = self.client.run_on_scheduler(_counts)
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
except Exception:
pass # a failed sample keeps the previous one
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
return workers
def report(self, *, force_log: bool = False) -> None:
workers = self._cluster_state()
with self._lock:
done = self.done
elapsed = time.monotonic() - self.started
self.eta.update(elapsed, done)
progress = Progress(
phase=self.phase,
done=done,
total=self.total,
elapsed_s=round(elapsed, 1),
eta_s=self.eta.eta_s(self.total),
mode=self.resolved.mode,
scheduler=self.resolved.scheduler,
workers=workers,
tasks=self.tasks,
updated_at=datetime.now(UTC).isoformat(timespec="seconds"),
)
tenth = done * 10 // self.total
if force_log or tenth > self.last_tenth:
self.last_tenth = tenth
self.log(f"{self.phase}: {done}/{self.total}")
context = self.ambient.context if self.ambient else None
if context is not None:
context.instance.add_run_tags(
context.run_id, {PROGRESS_TAG: progress.model_dump_json()}
)
def _default_log(ambient) -> Callable[[str], None]:
return ambient.context.log.info if ambient and ambient.context else print
def _run_sync(fn, iterator, monitor, on_error):
results = []
for item in iterator:
try:
results.append(fn(item))
except Exception as e:
if on_error is None:
raise
results.append(on_error(item, e))
monitor.item_done()
return results
def _run_dask(fn, iterator, client, monitor, on_error):
from distributed import as_completed
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
limit = max(4, 2 * threads)
results: dict[int, object] = {}
pending: dict = {} # future -> (index, item)
completed = as_completed([])
numbered = enumerate(iterator)
try:
while True:
for index, item in islice(numbered, max(0, limit - len(pending))):
future = client.submit(fn, item, pure=False, retries=1)
pending[future] = (index, item)
completed.add(future)
if not pending:
break
future = next(completed)
index, item = pending.pop(future)
try:
results[index] = future.result()
except Exception as e:
if on_error is None:
raise
results[index] = on_error(item, e)
monitor.item_done()
except BaseException:
try:
client.cancel(list(pending), force=True)
except Exception:
pass
raise
return [results[i] for i in range(len(results))]
def map[T, R]( # noqa: A001 - the module's public name, as in `execution.map`
fn: Callable[[T], R],
items: Iterable[T],
*,
execution: Execution | None = None,
log: Callable[[str], None] | None = None,
phase: str = "working",
total: int | None = None,
workers: int | None = None,
on_error: Callable[[T, Exception], R] | None = None,
) -> list[R]:
"""Apply `fn` to every item and return the results in input order.
`fn` is a module-level function of one item returning something picklable, and must give
the same result for the same item: then every mode returns equal lists. `items` may be a
lazy generator; at most `max(4, 2 * threads)` items are loaded and unfinished at once.
`total` is needed only when `items` has no length. `phase` is the lowercase code the
WebApp shows. `workers` overrides the local worker count (a cluster shared inside
`running` keeps the count it started with). A failed item takes `on_error(item, error)`
as its result, or, without it, the error propagates after the rest is cancelled."""
ambient = _ambient.get()
if execution is None and ambient is not None:
execution = ambient.execution
resolved = resolve(execution)
log = log or _default_log(ambient)
if total is None:
try:
total = len(items) # type: ignore[arg-type]
except TypeError:
raise ValueError("total is needed when items has no length") from None
iterator = iter(items)
if total == 0:
return []
monitor = None
client, local = (ambient.client, None) if ambient else (None, None)
opened_here = False
ok = False
try:
if resolved.mode != "sync" and client is None:
client, local = _connect(resolved, workers)
if ambient is not None:
ambient.client, ambient.cluster = client, local
else:
opened_here = True
monitor = _Monitor(ambient, resolved, phase, total, log, client)
monitor.start()
if resolved.mode == "sync":
results = _run_sync(fn, iterator, monitor, on_error)
else:
results = _run_dask(fn, iterator, client, monitor, on_error)
ok = True
return results
finally:
if monitor is not None:
monitor.stop(final=ok)
if ambient is not None:
ambient.phases.append(
{
"phase": phase,
"done": monitor.done,
"total": total,
"elapsed_s": round(time.monotonic() - monitor.started, 1),
}
)
ambient.peak_cpu_pct = max(ambient.peak_cpu_pct, monitor.peak_cpu)
ambient.peak_memory_bytes = max(ambient.peak_memory_bytes, monitor.peak_memory)
if opened_here:
_close(client, local)
@contextmanager
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
"""Make `context` and `execution` the ambient ones for the `map` calls in the block; on
exit close the shared cluster and leave the run's figures in the op's output metadata."""
ambient = _Ambient(context, execution)
token = _ambient.set(ambient)
failed = True
try:
yield
failed = False
finally:
_ambient.reset(token)
ambient.close()
try:
resolved = resolve(execution)
context.add_output_metadata(
{
"mode": dg.MetadataValue.text(resolved.mode),
"scheduler": (
dg.MetadataValue.text(resolved.scheduler)
if resolved.scheduler
else dg.MetadataValue.null()
),
"phases": dg.MetadataValue.json(ambient.phases),
"peak_cpu_pct": dg.MetadataValue.float(ambient.peak_cpu_pct),
"peak_memory_bytes": dg.MetadataValue.int(ambient.peak_memory_bytes),
}
)
except Exception:
if not failed:
raise
-34
View File
@@ -1,34 +0,0 @@
"""ONNX checkpoint inspection (ML-01b, MLD-03).
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
which hands it to MLflow directly — nothing here manages storage paths.
`onnx` is an optional dependency (`models[export]`); without it
`inspect_onnx_metadata` returns `{"available": False}`.
"""
from pathlib import Path
from typing import Any
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
`{"available": False}` when the optional `onnx` package isn't installed;
`ValueError` when it is and the file isn't a valid ONNX model."""
try:
import onnx
except ImportError:
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
try:
model = onnx.load(str(path))
onnx.checker.check_model(model)
except Exception as exc:
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
return {
"available": True,
"ir_version": model.ir_version,
"producer_name": model.producer_name,
"producer_version": model.producer_version,
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
"graph_inputs": [i.name for i in model.graph.input],
"graph_outputs": [o.name for o in model.graph.output],
}
+485
View File
@@ -0,0 +1,485 @@
"""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
from functools import cache
import ocrmypdf
import pandas as pd
import pdfplumber
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.pipeline import (
HELD,
IDENTIFIERS,
QUOTES,
RECORD,
Edf,
Extract,
Fhir,
Join,
Link,
Map,
Pipeline,
Read,
Route,
Target,
answer_schema,
apply_patterns,
ground,
join,
map_row,
matches,
validate,
)
from models.tea.eeg import read
from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
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},
}
EDF_COLUMNS = {f"edf_{name}": {"data_type": kind, "nullable": True} for name, kind in (
("patient_code", "text"), ("sex", "text"), ("birth_date", "text"), ("study_date", "text"),
("record_code", "text"), ("duration_s", "double"), ("channels", "bigint"), ("error", "text"),
)} # fmt: skip
@cache
def _reader() -> MarkItDown:
return MarkItDown()
def _lines(text: str) -> str:
"""Non-empty lines, with the spacing inside each collapsed."""
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str:
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each
(spacing within a line collapsed); every other format through MarkItDown."""
if content.startswith(b"%PDF"):
with pdfplumber.open(io.BytesIO(content)) as pdf:
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
return _reader().convert_stream(io.BytesIO(content)).text_content
def read_file(content: bytes) -> dict:
"""Text of one file, and whether OCR was needed. An unreadable file keeps its error."""
try:
found = _text(content)
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
text = io.BytesIO()
ocrmypdf.ocr(
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True,
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
sidecar=text,
) # fmt: skip
found = _lines(text.getvalue().decode())
return {"text": found, "ocr": ocr, "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read):
"""The input's rows with the file column replaced by its text; each file read once."""
rows = list(nodes.rows(p, node.inputs[0]))
for row in rows: # the source kept the file; the row carries its hash
row["key"] = row.pop(node.column) or None
keys = {r["key"] for r in rows} - {None}
found = nodes.cached("read_cache", keys)
new = {k: files.content(k) for k in keys - set(found)}
with ProcessPoolExecutor() as pool:
read = dict(zip(new, pool.map(read_file, new.values()), strict=True))
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
found |= read
for row in rows:
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, READ_COLUMNS)
def run_edf(p: str, node: Edf):
"""Keep every input row and add the header facts or the file's error."""
rows = list(nodes.rows(p, node.inputs[0]))
empty = dict.fromkeys(EDF_COLUMNS)
found = {None: {**empty, "edf_error": "empty"}}
for key in {row.get(node.column) for row in rows} - {None}:
content = files.content(key)
if content is None:
found[key] = {**empty, "edf_error": "no file"}
continue
try:
h = read.header(content)
except read.FileNotValid as exc:
found[key] = {**empty, "edf_error": str(exc)}
continue
found[key] = {
"edf_patient_code": h.patient_code,
"edf_sex": h.sex,
"edf_birth_date": h.birthdate.isoformat() if h.birthdate else None,
"edf_study_date": h.start_date.isoformat() if h.start_date else None,
"edf_record_code": h.record_code,
"edf_duration_s": h.duration_s,
"edf_channels": h.channels,
"edf_error": None,
}
for row in rows:
row.update(found[row.get(node.column)])
return nodes.write(p, node.id, rows, EDF_COLUMNS)
def run_route(p: str, node: Route):
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
"""The node's ConceptMap as a translation table per field (none without one)."""
if node.concept_map is None:
return {}
found = config_log.concept_map(node.concept_map)
return {f: concept_map.table([found], f) for f in fields}
def run_map(p: str, node: Map):
codes = _codes(node, node.fields)
rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])]
return nodes.write(p, node.id, rows)
def run_fhir(p: str, node: Fhir):
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
found: dict[str, dict] = {}
for row in nodes.rows(p, node.inputs[0]):
bundle = json.loads(row[node.column])
for r in fhir_in.rows(bundle, node.entity, p, maps):
found[r[RECORD]] = r
return nodes.write(p, node.id, list(found.values()))
def run_join(p: str, node: Join):
left, right = (list(nodes.rows(p, i)) for i in node.inputs)
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
@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"]
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 _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() 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:
found = ground(_ask_llm(node, text), text)
elif node.patterns:
found = apply_patterns(node, text, codes)
else:
found = [({}, {}, ["no LLM answering and no patterns set"])]
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
out.append({**values, RECORD: row[RECORD], "_index": index,
QUOTES: json.dumps(quotes, ensure_ascii=False),
HELD: json.dumps(held) if held else None}) # fmt: skip
return nodes.write(p, node.id, out)
def _comparison(field: str):
if field == "birth_date":
return cl.DateOfBirthComparison(field, input_is_string=True)
if field == "full_name":
return cl.NameComparison(field)
if field in ("record_number", "curp", "nss"):
return cl.LevenshteinAtThresholds(field, [1, 2])
return cl.ExactMatch(field)
def _plain(identifier: str) -> str:
"""An identifier as compared: letters and digits only, upper case."""
return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _name(name: str) -> str:
"""A name as compared: upper case, without accents, single spaces."""
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
return " ".join(plain.upper().split())
def _near(identifier: str) -> list[str]:
"""The identifier and every version of it with one character left out: two identifiers
one typo apart (a wrong, missing, extra or swapped character) share one of these."""
return sorted(
{identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))}
)
def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]:
"""One row per record: its identity fields (first value found, reviewers' corrections
applied, identifiers plain); records rejected for identity are left out. And the input
each record came through (its record number's system), and its name as written."""
skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {}
sources: dict[str, str] = {}
written: dict[str, str] = {} # each record's name as it came (compared normalised)
for i in node.inputs:
for row in nodes.rows(p, i):
if row.get(HELD) or row[RECORD] in skip:
continue
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
sources.setdefault(row[RECORD], i)
for f in node.fields:
if row.get(f) is not None and mine.get(f) is None:
value = str(row[f])
if f == "full_name":
written[row[RECORD]] = " ".join(value.split())
mine[f] = (
_plain(value) if f in IDENTIFIERS
else _name(value) if f == "full_name" else value
) # fmt: skip
frame = pd.DataFrame(list(records.values()))
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
return frame[["unique_id", *present]], sources, written
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
clusters = cluster_pairwise_predictions_at_threshold(
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
)
return clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(records)
def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
don't contradict each other are queued for review, with Splink's probability. A person
with nothing that names her (no name, birth date or record number read) is held too."""
records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"]
rules = [r for r in node.rules or node.default_rules()
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
comparisons = [_comparison(f) for f in fields]
db = DuckDBAPI()
linker = Linker(
db.register(records),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=rules),
log_level=None,
) # fmt: skip
decided = nodes.person_decisions()
sure = linker.inference.deterministic_link().as_pandas_dataframe()
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
known = set(records.unique_id)
edges = pd.DataFrame(
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
)
persons = _persons(records, edges, db)
facts = [f for f in ("birth_date", "sex") if f in fields]
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1)
nameless = set(read[read == 0].index)
why = {c: "records of this person disagree on birth date or sex" for c in torn}
why |= {c: "no name, birth date or record number was read" for c in nameless - torn}
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
linked = [
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
**{f: getattr(r, f) for f in fields},
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
for r in persons.itertuples()
] # fmt: skip
nodes.write(p, node.id, linked, columns)
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person
# One row per person, so random pairs are different people and Splink's u is honest.
ids = [f for f in IDENTIFIERS if f in fields]
whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
for f in ids:
near = (
persons.dropna(subset=[f])
.groupby("cluster_id")[f]
.agg(lambda values: sorted({n for v in values for n in _near(v)}))
)
whole[f"{f}_near"] = near.reindex(whole.index).apply(
lambda v: v if isinstance(v, list) else []
)
whole = whole.reset_index().rename(columns={"cluster_id": "unique_id"})
blocks = [block_on(f"{f}_near", arrays_to_explode=[f"{f}_near"]) for f in ids]
reasons = [f"{f} one typo apart" for f in ids]
if "birth_date" in fields:
blocks.append(block_on("birth_date"))
reasons.append("same birth date")
model = Linker(
db.register(whole),
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
blocking_rules_to_generate_predictions=blocks),
log_level=None,
) # fmt: skip
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
known = [f for f in ("birth_date", "sex") if f in fields]
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
lone = set() # persons whose identifier is carried by one record only
for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
lone |= {person for (person, _), n in carried.items() if n == 1}
def settle(r) -> tuple[str, str] | None:
"""(the person to settle, a possible owner), or None when the pair is implausible:
they contradict each other, or one typo apart is all they share (with sequential
record numbers every patient has such neighbours) unless one side has no
demographics and the other's identifier stands on a single record. Names one typo
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
very same identifier on a record that says nothing else (a scan read only in part)."""
a, b = r.unique_id_l, r.unique_id_r
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in decided or any(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
):
return None
reason = reasons[int(r.match_key)]
if not reason.endswith("typo apart"):
return a, b
field = reason.removesuffix(" one typo apart")
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier
return (a, b) if a in undated or b not in undated else (b, a)
if field == "full_name" and (a in undated) != (b in undated):
return (a, b) if a in undated else (b, a) # names are rarely one typo apart
if a in orphan and b in lone:
return a, b
if b in orphan and a in lone:
return b, a
return None
side = {r.unique_id: r for r in whole.itertuples()}
queue = []
for r in found.itertuples():
if pair := settle(r):
person, owner = pair
queue.append(
{
"person": person,
"candidate": owner,
"probability": r.match_probability,
"reason": reasons[int(r.match_key)],
**{f"person_{f}": getattr(side[person], f) for f in fields},
**{f"candidate_{f}": getattr(side[owner], f) for f in fields},
}
)
return nodes.write(p, f"{node.id}__review", queue)
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
instance (the study's key values); a row a rule held waits for review, whole."""
link = next(i for i in node.inputs if kinds[i] == "link")
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]
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):
for row in nodes.rows(p, i):
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
values |= {f: v for f, v in fixed.get(row[RECORD], {}).items()
if f in model.model_fields} # fmt: skip
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
if row[RECORD] not in person:
held.append("no identity linked to this record")
else:
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
if held:
raw = json.dumps(values, default=str, ensure_ascii=False)
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
continue
clean = model.model_validate(values)
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
for name, field in study.fields.items():
if (value := getattr(clean, name)) is not None:
observations.append({**base, "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)
RUNNERS: dict[str, Callable] = {
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
"join": run_join, "extract": run_extract, "link": run_link, "edf": run_edf, "fhir": run_fhir,
} # fmt: skip
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
kinds = {n.id: n.kind for n in pipeline.nodes}
for node in pipeline.order():
if node.kind == "target":
run_target(pipeline_id, node, kinds)
else:
RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done")
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
log(f"silver and gold, from {', '.join(entities)}")
+83
View File
@@ -0,0 +1,83 @@
"""Training and scoring of a domain's models, what the Dagster jobs run. A domain's module
`models.<domain>.jobs` binds them to its models (`MODELS`) and its reports: `train(name,
as_of)` registers a new version (MLflow) with its two generated reports; `score(name)` writes
the champion's risk batch."""
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
import mlflow.pyfunc
import pandas as pd
from joblib.externals.loky import get_reusable_executor
from persistance import gold, registry
class EmptyCohort(ValueError):
"""The site has nobody in a model's cohort (no colposcopies, say): nothing to learn from."""
class Predictor(mlflow.pyfunc.PythonModel):
"""A fitted model as MLflow serves it: patient timelines in (gold `<domain>_events` rows
with each patient's index date), one row per patient and horizon out."""
def __init__(self, spec, fitted):
self.spec, self.fitted = spec, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return self.spec.predict(self.fitted, model_input)
@dataclass(frozen=True)
class Jobs:
domain: str
models: dict
technical_validation: Callable[..., dict]
interpretability: Callable[..., dict]
@property
def events(self) -> str:
return f"{self.domain}_events"
def routine(self) -> list[str]:
"""The models a train or score run takes when none is named: all but the slow ones."""
return [n for n, s in self.models.items() if not getattr(s, "slow", False)]
def registered(self, name: str) -> str:
return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int:
"""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()
if spec.cohort is None: # trained on reference data: it writes its own reports
fitted, metrics, found = spec.train(None, 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),
}
# 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)
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)
def score(self, name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet."""
if self.models[name].cohort is None: # scores no patient
return None
found = registry.champion(self.registered(name))
if found is None:
return None
version, model = found
risks = model.predict(gold.timelines(self.events, self.models[name].cohort))
gold.save_scores(self.registered(name), version, risks)
return version
-267
View File
@@ -1,267 +0,0 @@
"""Extraction of results from the PDF reports stored with each study
(VAR-01..09, VARM-01..05).
Each `OcrJob` says which table, which stored PDF and which result columns
an extraction fills; `OCR_JOBS` lists them all. Adding a job is adding an
`OcrExtractor` (usually a `ReportOcrExtractor` with its `fields`) and an
entry in `OCR_JOBS`.
Extraction method (VAR-04, VARM-05): the PDF's text layer is read with
pdfplumber; pages without one are recognized with Tesseract 5's LSTM engine
(Smith, R. "An Overview of the Tesseract OCR Engine", ICDAR 2007). Values
are then located by caption matching tolerant to OCR errors, and by
lexicon matching over the narrative with NegEx-style negation handling
(Chapman, W. et al. "A Simple Algorithm for Identifying Negated Findings and
Diseases in Discharge Summaries", J Biomed Inform 34(5), 2001). Every
value carries a 0..1 confidence: caption match quality x parse quality x
Tesseract's word confidence.
"""
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, ClassVar
from sqlalchemy import func, or_
from sqlmodel import select
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
from core.cama.enums import GradoHistologicoMama
from core.ocr import OcrEstatus
from extraction import FieldKind, FieldSpec, read_document
from extraction.nlp import RecordExtractor, SegmentLine
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
from extraction.ocr import TesseractOcr
from models.base import resolve_repository
from persistance.repository import Repository
# Below this confidence a value is stored but flagged for manual review.
REVIEW_THRESHOLD = 0.8
@dataclass
class OcrExtractionResult:
"""VAR-03/VARM-04a: the values plus their confidence and provenance."""
values: dict[str, Any]
confianza: float
estatus: OcrEstatus
requiere_revision: bool
metodo_principal: str
metodo_alternativo: str | None = None
quality_validation: str | None = None
@dataclass
class OcrColumnSpec:
"""The columns of one extraction on its table: the stored PDF, the
five traceability columns, and extractor result key -> result column."""
blob_field: str
confianza_field: str
estatus_field: str
requiere_revision_field: str
metodo_principal_field: str
metodo_alternativo_field: str
result_field_map: dict[str, str] = field(default_factory=dict)
class OcrExtractor(ABC):
@abstractmethod
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
"""Reads `pdf_blob`. A document that can be read but where nothing
is found returns estatus FALLIDO with requiere_revision; an
unreadable one may raise, and the driver records FALLIDO."""
class ReportOcrExtractor(OcrExtractor):
"""Reads a report and looks for `fields` (result key -> FieldSpec)."""
fields: ClassVar[dict[str, FieldSpec]]
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
document = read_document("reporte.pdf", pdf_blob)
lines = [SegmentLine(document.name, page.number, line) for page in document.pages for line in page.lines]
found = RecordExtractor(list(self.fields.values())).extract(lines)
by_key = {key: found[spec.name] for key, spec in self.fields.items() if spec.name in found}
sources = {page.source for page in document.pages}
principal = "pdf-texto" if "text" in sources else TesseractOcr().name
alternativo = TesseractOcr().name if sources == {"text", "ocr"} else None
evidence = {key: value.to_dict() for key, value in by_key.items()}
missing = [key for key in self.fields if key not in by_key]
if missing:
evidence["faltantes"] = missing
if not by_key:
return OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, principal, alternativo, json.dumps(evidence, ensure_ascii=False))
confianza = round(min(value.confidence for value in by_key.values()) * len(by_key) / len(self.fields), 3)
return OcrExtractionResult(
values={key: value.value for key, value in by_key.items()},
confianza=confianza,
estatus=OcrEstatus.REALIZADO,
requiere_revision=bool(missing) or confianza < REVIEW_THRESHOLD,
metodo_principal=principal,
metodo_alternativo=alternativo,
quality_validation=json.dumps(evidence, ensure_ascii=False, default=str),
)
def choice_field(column: str, values: dict[str, Any], **options) -> FieldSpec:
return FieldSpec(column, FieldKind.CHOICE, labels=labels_for(column), choices={**values, **CLINICAL_TERMS.get(column, {})}, **options)
class VphOcrExtractor(ReportOcrExtractor):
"""VAR-01: VPH result and genotypes 16/18 from `cit_vph_pdf_blob`."""
fields = {
"resultado": choice_field("cit_vph_resultado", {m.value: m.value for m in ResultadoVPH}, scan_free_text=True),
"genotipo_16": choice_field("cit_vph_genotipo_16", {}),
"genotipo_18": choice_field("cit_vph_genotipo_18", {}),
}
class CinGradoOcrExtractor(ReportOcrExtractor):
"""VAR-02: CIN grade from the cervical biopsy report `bx_pdf_blob`."""
fields = {"grado": choice_field("bx_cin_grado", {**{m.value: m.value for m in GradoCIN}, **GRADO_CIN_ALIAS}, scan_free_text=True)}
class GradoHistologicoOcrExtractor(ReportOcrExtractor):
"""VARM-03: histological grade from the breast biopsy report `bx_pdf_blob`."""
fields = {
"grado": choice_field(
"bx_grado_histologico",
{m.value.replace("_", " "): m.value for m in GradoHistologicoMama},
scan_free_text=True,
)
}
def _ocr_columns(prefix: str, blob_field: str, results: dict[str, str]) -> OcrColumnSpec:
return OcrColumnSpec(
blob_field=blob_field,
confianza_field=f"{prefix}_ocr_confianza",
estatus_field=f"{prefix}_ocr_estatus",
requiere_revision_field=f"{prefix}_ocr_requiere_revision",
metodo_principal_field=f"{prefix}_ocr_metodo_principal",
metodo_alternativo_field=f"{prefix}_ocr_metodo_alternativo",
result_field_map=results,
)
CIT_VPH_COLUMNS = _ocr_columns(
"cit_vph",
"cit_vph_pdf_blob",
{"resultado": "cit_vph_resultado", "genotipo_16": "cit_vph_genotipo_16", "genotipo_18": "cit_vph_genotipo_18"},
)
BX_CIN_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_cin_grado"})
BX_GRADO_HISTOLOGICO_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_grado_histologico"})
@dataclass(frozen=True)
class OcrJob:
domain: str
entity: str # repository name in persistance.<domain>, without `_repository`
label: str
columns: OcrColumnSpec
extractor: type[OcrExtractor]
@property
def repository(self) -> Repository:
"""Resolved on use, so it follows whatever database URL is active."""
return resolve_repository(self.domain, self.entity)
OCR_JOBS: dict[tuple[str, str], OcrJob] = {
(job.domain, job.entity): job
for job in (
OcrJob("cacu", "citologia_cervical", "CaCu · Resultado de VPH (citología cervical)", CIT_VPH_COLUMNS, VphOcrExtractor),
OcrJob("cacu", "biopsia_cervical", "CaCu · Grado CIN (biopsia cervical)", BX_CIN_COLUMNS, CinGradoOcrExtractor),
OcrJob("cama", "biopsia_mama", "CaMa · Grado histológico (biopsia de mama)", BX_GRADO_HISTOLOGICO_COLUMNS, GradoHistologicoOcrExtractor),
)
}
@dataclass
class OcrRunSummary:
processed: int = 0
skipped_already_done: int = 0
failed: int = 0
needs_review: int = 0
def run_pending_extractions(
repository: Repository,
spec: OcrColumnSpec,
extractor: OcrExtractor,
*,
domain: str,
entity: str,
governance_repository: Repository | None = None,
source_description: str | None = None,
limit: int = 500,
) -> OcrRunSummary:
"""VAR-09: rows whose status is already REALIZADO are skipped, so the
persisted result is what prevents duplicate runs. A failing row is
stored as FALLIDO and the batch continues. With `governance_repository`,
every processed row is logged as an `ExtractionRun` (VAR-07/08)."""
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
summary = OcrRunSummary()
model = repository.model
primary_key = list(model.__table__.primary_key.columns)
estatus = getattr(model, spec.estatus_field)
with_report = getattr(model, spec.blob_field).is_not(None)
done = estatus == OcrEstatus.REALIZADO.value
with repository.open_session() as session:
summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one()
pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit)
for tracked in session.exec(pending).all():
pk_value = getattr(tracked, primary_key[0].name)
started_at = datetime.now(timezone.utc)
try:
result = extractor.extract(getattr(tracked, spec.blob_field))
except NotImplementedError:
raise
except Exception as exc: # noqa: BLE001 -- one unreadable report must not stop the batch
result = OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, type(extractor).__name__, None, f"error: {exc}")
for result_key, column in spec.result_field_map.items():
if result_key in result.values:
setattr(tracked, column, result.values[result_key])
setattr(tracked, spec.confianza_field, result.confianza)
setattr(tracked, spec.estatus_field, OcrEstatus(result.estatus).value)
setattr(tracked, spec.requiere_revision_field, result.requiere_revision)
setattr(tracked, spec.metodo_principal_field, result.metodo_principal)
setattr(tracked, spec.metodo_alternativo_field, result.metodo_alternativo)
session.add(tracked)
if result.estatus == OcrEstatus.FALLIDO:
summary.failed += 1
else:
summary.processed += 1
if result.requiere_revision:
summary.needs_review += 1
if governance_repository is not None:
governance_repository.create(
ExtractionRun(
domain=domain,
entity=entity,
entity_pk=str(pk_value),
column_extracted=",".join(spec.result_field_map.values()),
source_description=source_description,
source_started_at=started_at,
source_ended_at=datetime.now(timezone.utc),
transform_description=f"{type(extractor).__name__}: {result.metodo_principal}"
+ (f" + {result.metodo_alternativo}" if result.metodo_alternativo else ""),
quality_validation=result.quality_validation,
estatus=(
EstatusExtraccion.COMPLETADA if result.estatus == OcrEstatus.REALIZADO else EstatusExtraccion.FALLIDA
).value,
)
)
session.commit()
return summary
-127
View File
@@ -1,127 +0,0 @@
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
produced it. Callers go through `PredictionService` rather than calling
`model.predict(...)` directly.
"""
import hashlib
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from core.governance.models import ModelPrediction
from mlflow import MlflowException
from persistance.governance import model_prediction_repository
from models.base import ScreeningModel
from models.registry import PRODUCTION_ALIAS, registered_name, registry
@dataclass
class Interpretability:
"""MLD-03: the minimum a prediction reports for clinical interpretation.
Each model fills the ones its method has (odds ratio for a logistic
regression, hazard ratio for a survival model)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a `ScreeningModel` and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `aplicable` is given, each row (a dict of fields) is checked with it
(EL-04b). Inapplicable rows are still scored but stored with
`applicability_passed=False`, unless `reject_inapplicable` is set.
"""
def __init__(
self,
model: ScreeningModel,
*,
domain: str,
scenario: str,
aplicable: Callable[[dict], bool] | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.aplicable = aplicable
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged.
"""
applicability_passed = True
if self.aplicable is not None:
if not isinstance(data, dict):
raise TypeError("the applicability check needs the input as a dict of fields")
applicability_passed = self.aplicable(data)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict first, so an unimplemented model raises NotImplementedError
# even when no version is in production.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
"promueva una con models.registry.registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction
-249
View File
@@ -1,249 +0,0 @@
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
about on its own: the promotion checks tied to the cohort a version was
trained on and to the validation-report convention.
Training, versioning, artifact storage and stage live in MLflow itself
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
of its versions, never stored here and read from MLflow on every call.
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
database). A version points to its build with the `kit.armado_id` tag, and
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
"""
import re
import tempfile
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.governance import model_prediction_repository
from sqlmodel import select
from models.export import inspect_onnx_metadata
DOMAINS = ("cacu", "cama", "tea")
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
ARMADO_TAG = "kit.armado_id"
@dataclass(frozen=True)
class PromotionCheck:
code: str
requirement: str
passed: bool
detail: str = ""
class PromotionBlocked(Exception):
def __init__(self, checks: list[PromotionCheck]):
self.checks = checks
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
super().__init__(f"la versión no cumple: {failed}")
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
class ModelRegistry:
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
def __init__(self, client: MlflowClient | None = None):
self._client = client
@property
def client(self) -> MlflowClient:
return self._client or MlflowClient()
def get(self, domain: str, scenario: str, version: str):
try:
return self.client.get_model_version(registered_name(domain, scenario), version)
except MlflowException as exc:
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
"""Every version, newest first. `scenario` needs `domain`; `domain`
alone matches every scenario of that domain (MLflow's own
`search_registered_models` LIKE filter); neither matches everything."""
if domain and domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
if scenario and not re.fullmatch(r"[\w-]+", scenario):
raise ValueError(f"escenario inválido: {scenario!r}")
if domain and scenario:
names = [registered_name(domain, scenario)]
elif domain:
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
else:
return [self._describe(mv) for mv in self.client.search_model_versions()]
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
def _status(self, mv) -> str:
try:
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
if str(production.version) == str(mv.version):
return "produccion"
except MlflowException:
pass
if mv.tags.get("retirada_en"):
return "retirada"
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
def status(self, domain: str, scenario: str, version: str) -> str:
return self._status(self.get(domain, scenario, version))
def register(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""For training code that runs elsewhere and reports over the API.
In-process training uses `models.training.TrainingRun` directly."""
from models.training import TrainingRun
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
"""MLD-01/01b/03 documents are usually written after training."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
name = registered_name(domain, scenario)
for tag, uri in reports.items():
self.client.set_model_version_tag(name, version, tag, uri or "")
def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
"""Logs an artifact file to the run behind an already-registered
version (ML-01a/b), e.g. a checkpoint exported after training.
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
rejected (400) instead of silently stored."""
mv = self.get(domain, scenario, version)
kind_value = kind.value if hasattr(kind, "value") else str(kind)
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / filename
path.write_bytes(data)
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
def _describe(self, mv) -> dict[str, Any]:
run = self.client.get_run(mv.run_id)
return {
"name": mv.name,
"version": str(mv.version),
"run_id": mv.run_id,
"tags": dict(mv.tags),
"metrics": dict(run.data.metrics),
"created_at": _iso(mv.creation_timestamp),
"status": self._status(mv),
}
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
return self._describe(self.get(domain, scenario, version))
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
"""Everything a version came from and produced: its cohort build (with
its attrition), logged artifacts and predictions."""
mv = self.get(domain, scenario, version)
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
return {
"model_version": self.describe(domain, scenario, version),
"cohorte_armado": armado,
"cohorte_exclusiones": exclusiones,
"artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)],
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
}
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
mv = self.get(domain, scenario, version)
run = self.client.get_run(mv.run_id)
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
metrics = run.data.metrics
artifacts = self.client.list_artifacts(mv.run_id)
return [
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
PromotionCheck(
"ML-03",
"enlazada al armado de cohorte con el que se entrenó",
armado is not None,
f"huella {armado['huella'][:12]}" if armado else "sin cohorte",
),
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
]
def promote(self, domain: str, scenario: str, version: str):
"""Makes this the production version of its scenario, tagging the
previous one `retirada_en`. Promotion is always a manual step
(MLD-01/01b)."""
checks = self.checks(domain, scenario, version)
if not all(check.passed for check in checks):
raise PromotionBlocked(checks)
name = registered_name(domain, scenario)
try:
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
if str(previous.version) != str(version):
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
except MlflowException:
pass
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
return self.get(domain, scenario, version)
def retire(self, domain: str, scenario: str, version: str):
"""Withdraws a version from production; its scenario has no active
model until another one is promoted, so predictions stop."""
name = registered_name(domain, scenario)
try:
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
active = None
if active is None or str(active.version) != str(version):
raise ValueError("la versión no está en producción")
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
return self.get(domain, scenario, version)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _iso(epoch_millis: int) -> str:
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
registry = ModelRegistry()
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
"""The kit cohort build a version was trained on, and its attrition steps."""
if not armado_id:
return None, []
cohortes = import_module(f"persistance.{domain}").cohorte_repository
armado = cohortes.get(int(armado_id))
if armado is None:
return None, []
exclusion = cohortes.cohortes.CohorteExclusion
pasos = cohortes.leer(lambda sesion: sesion.exec(
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
"armado_en": armado.armado_en.isoformat()},
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
+499
View File
@@ -0,0 +1,499 @@
"""Interval survival, shared by CaMa and CaCu: the probability of surviving each interval of
follow-up, given alive at its start, by a logistic regression and by a Bayesian network with a
tabular CPT, mixed per interval; survival to a horizon is the product of the intervals' up to it.
Each interval's models fit the patients alive at its start (`months >= start`); one censored
inside the interval counts as half a risk. The mixture weight of an interval is the one that
best predicts patients out of sample (`folds` folds), shrunk toward 50/50 when there are few
deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missing value is a
category of its own (UNKNOWN).
"""
from dataclasses import dataclass, field
from itertools import pairwise
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy.optimize import minimize_scalar
from scipy.special import gammaln
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame:
"""Whole months from each index to her death or, alive, to `end`, and whether she died;
follow-up is cut at `cap_months` (a later death counts as alive)."""
index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
died = (death.notna() & (death <= end)).to_numpy()
last = death.where(died, end)
days = (last - index).dt.days.to_numpy()
months = np.floor(days / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def band(values: pd.Series, cuts: list) -> pd.Series:
"""Values in the bands the cuts make (`<c1`, `c1-(c2-1)`, ..., `≥cn`); empty stays empty."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
@dataclass(frozen=True)
class Constant:
"""An interval where everyone at risk had the same outcome: the same probability for all."""
p: float
def predict_proba(self, X) -> np.ndarray:
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _bdeu(code, y, w, q, ess) -> float:
"""The outcome's weighted BDeu score given parent configurations `code` (of `q`)."""
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj, ajk = ess / q, ess / q / 2
return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
+ np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
def _search(X, levels, y, w, ess, max_parents) -> list[int]:
"""Greedy: the covariate that most improves the outcome's BDeu, until none does."""
parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents:
found = None
for j in range(X.shape[1]):
if j in parents or q * levels[j] > 200_000:
continue
c2 = code * levels[j] + X[:, j]
score = _bdeu(c2, y, w, q * levels[j], ess)
if score > best + 1e-9 and (found is None or score > found[0]):
found = (score, j, c2, q * levels[j])
if found is None:
break
best, j, code, q = found
parents.append(j)
return parents
def _code(X, levels, parents) -> np.ndarray:
code = np.zeros(len(X), int)
for j in parents:
code = code * levels[j] + X[:, j]
return code
class IntervalSurvival(BaseEstimator):
"""Survival by intervals (`borders`, months), LR and HBN stacked per interval.
`fit(X, months, event)` takes the categorical covariates `features`; the HBN's parents
are `parents` (feature names) or, when None, learned per interval by the BDeu score.
"""
def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
folds=5, shrink=20, seed=42): # fmt: skip
self.features = features
self.borders = borders
self.parents = parents
self.ess = ess
self.max_parents = max_parents
self.folds = folds
self.shrink = shrink
self.seed = seed
# -- coding: dummies for the LR (first level alphabetically as reference), integer codes
# (in order of first appearance) for the HBN; an unseen value takes UNKNOWN's code.
def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str)
def _encode(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
frame = self._frame(X)
columns = []
for name in self.features:
known = self.categories_[name]
codes = pd.Categorical(frame[name], categories=known).codes
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
columns.append(np.where(codes < 0, fallback, codes))
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
fitted = []
for a, b in pairwise(self.borders):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
fitted.append((Constant(1.0), ([], np.array([1.0]))))
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) # 1 = survives the interval
w = np.where(~e & (m < b), 0.5, 1.0) # censored inside it: half a risk
if y.min() == y.max():
lr = Constant(float(y[0]))
else:
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[at_risk], y, sample_weight=w)
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
return fitted
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]:
"""The parents and P(survives | parents), smoothed toward the marginal survival."""
if self.parents is None:
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
else:
parents = [list(self.features).index(p) for p in self.parents]
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
minlength=q * 2).reshape(q, 2) # fmt: skip
aj = self.ess / q
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
"""Per interval, the LR's weight in the mixture, from out-of-fold predictions."""
n = len(months)
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds
oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
for k in range(self.folds):
test, train = np.where(fold == k)[0], np.where(fold != k)[0]
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
weights = []
for j, (a, b) in enumerate(pairwise(self.borders)):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
weights.append(0.5)
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0)
p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
def loss(x, p1=p1, p2=p2, y=y, w=w):
p = np.clip(x * p1 + (1 - x) * p2, 1e-9, 1 - 1e-9)
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
shrunk = self.shrink / (self.shrink + int((y == 0).sum()))
weights.append((1 - shrunk) * best + shrunk * 0.5)
return np.array(weights)
def fit(self, X: pd.DataFrame, months, event):
frame = self._frame(X)
self.dummies_ = list(pd.get_dummies(frame, drop_first=True).columns)
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
X_dum, X_int = self._encode(X)
self.levels_ = X_int.max(axis=0) + 1
months, event = np.asarray(months, int), np.asarray(event, bool)
if len(X) >= 2 * self.folds:
self.weights_ = self._weights(X_dum, X_int, months, event)
else:
self.weights_ = np.full(len(self.borders) - 1, 0.5)
self.fitted_ = self._fit_intervals(X_dum, X_int, months, event)
return self
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""Each patient's probability of surviving each interval, by the LR and by the HBN."""
return self._predict(self.fitted_, *self._encode(X))
def survival(self, X: pd.DataFrame) -> np.ndarray:
"""Each patient's survival to the end of each interval."""
lr, hbn = self.components(X)
w = self.weights_[None, :]
return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
# ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test; ties in the order of the
hospital's record numbers, so the split (and every fold after it) is the same on every
platform the same data are loaded into."""
ordered = members.sort_values(["index_date", "record_number"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)
def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
"""Each member's age at her index (from her birth event), in bands."""
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
return band(age, list(cuts))
@dataclass(frozen=True)
class Spec:
"""Mortality by each horizon from the index (1 minus the interval survival), for the
members of a gold cohort, from their timelines (`person_id`, `index_date`, `date`, `type`,
`value_code`, `value_num`, `source_table`, `source_id`, `record_number`).
`covariates(events, members)` gives each member's `features` at her index. With
`interval_level`, each combination of the covariates seen in training gets an interval:
percentiles of the mortality of `replicas` refits on bootstrap resamples (seed `seed`)."""
name: str
cohort: str
features: tuple[str, ...]
covariates: object # Callable[[pd.DataFrame, pd.DataFrame], pd.DataFrame]
parents: tuple[str, ...] | None = None
borders: tuple[int, ...] = (0, 6, 12, 18) # months
cap_months: int = 24
interval_level: float | None = None
replicas: int = 100
seed: int = 0
method: str = "interval survival"
notes: tuple[str, ...] = () # what the technical report states about the method
# Clinical scenarios the report draws: name -> conditions (column, "<" | ">=" | "==" |
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = ()
@property
def horizons(self) -> tuple[float, ...]:
return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member: index date, record number, death date and covariates."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
found = events.groupby("person_id")[["index_date", "record_number"]].first()
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
found["death_date"] = death.reindex(found.index)
kept = [*self.features, *self.scenario_columns]
found = found.join(self.covariates(events, found)[kept])
return found.reset_index()
def _model(self) -> IntervalSurvival:
return IntervalSurvival(list(self.features), self.borders, self.parents)
def _combinations(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str).reset_index(drop=True)
def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = self._combinations(train).drop_duplicates()
frame = combinations.replace(UNKNOWN, None)
rng = np.random.default_rng(self.seed) # resamples drawn in order, refitted in parallel
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
def mortality(rows: np.ndarray) -> np.ndarray:
sample = train.iloc[rows].reset_index(drop=True)
refit = self._model().fit(sample, sample["months"], sample["event"])
return 1.0 - refit.survival(frame)
replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False)
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def train(self, events: pd.DataFrame, as_of) -> tuple:
"""Fitted on the earliest members (followed up to `as_of`), with its metrics and what
the reports draw."""
members = self.members(events)
members = members.join(
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
)
train, test = split(members, TRAIN_FRACTION)
model = self._model().fit(train, train["months"], train["event"])
model.intervals_ = self._intervals(train) if self.interval_level else {}
weights = zip(self.borders[1:], model.weights_, strict=True)
metrics = {
"n_train": float(len(train)), "n_test": float(len(test)),
"events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
} # fmt: skip
return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, and its interval when kept."""
members = self.members(events)
mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h)
ends = [model.intervals_.get(tuple(c), empty)
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
return 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),
"probability": mortality.ravel(),
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
})[OUTPUT] # fmt: skip
# ---------------------------------------------------------------- reports (curves)
BOOTSTRAP = 100
BOOTSTRAP_SEED = 42
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
members = pd.concat([data["train"], data["test"]])
return {
"model": spec.name, "method": spec.method, "cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min().date()),
str(members["index_date"].max().date())],
"horizons_months": list(spec.borders[1:]),
"follow_up_cap_months": spec.cap_months,
"notes": list(spec.notes),
"metrics": metrics,
} # fmt: skip
def _curve(fitter, name: str) -> dict:
table = fitter.confidence_interval_survival_function_
return {
"months": fitter.survival_function_.index.tolist(),
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
"low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
} # fmt: skip
MIN_SCENARIO_EVENTS = 5 # fewer deaths than this: no curves for the scenario
GRID_POINTS = 200
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
"""Which members each scenario takes: all of its conditions hold (an unknown value
holds none)."""
found = {}
for name, conditions in scenarios.items():
mask = np.ones(len(members), bool)
for column, op, value in conditions:
v = members[column]
if op in ("<", ">="):
number = pd.to_numeric(v, errors="coerce")
held = number < value if op == "<" else number >= value
elif op == "in":
held = v.isin(list(value))
elif op == "==":
held = v == value
else:
raise ValueError(f"unknown condition {op!r} in scenario {name!r}")
mask &= held.fillna(False).to_numpy(bool)
found[name] = mask
return found
def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) -> dict:
from models import curves
d, c, _ = curves.life_table(months, event)
k, lam = curves.fit_weibull(d, c)
fractional = curves.fit_fractional(d, c, k, lam)
grid = np.linspace(0, cap_months, GRID_POINTS)
observed = int(months.max())
km = curves.kaplan_meier(months, event, observed)
return {
"observado_hasta": observed,
"km": {"months": list(range(observed + 1)),
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
"weibull": {"t": grid.tolist(), "S": curves.weibull(grid, k, lam).tolist(),
"k": k, "lambda": lam},
"weibull_fractional": {"t": grid.tolist(),
"S": curves.fractional(grid, k, *fractional).tolist(),
"alpha": fractional[0], "beta": fractional[1],
"lambda": fractional[2]},
} # fmt: skip
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
band, the survival of each combination of the covariates, and each clinical scenario's
curves (Kaplan-Meier, Weibull, fractional Weibull) with the model's mean survival over its
members and its band. The model's mixture is its own (the original refitted it per
scenario): the points show the model as it scores."""
from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"]
months, event = train["months"].to_numpy(), train["event"].to_numpy()
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
if event.any() and (months > 0).all():
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
# Scenarios: over every member (training first), the observed curves of those with
# enough deaths, and the model's mean survival over each, with the same bootstrap band.
members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios)
def mean_survival(rows: np.ndarray) -> tuple[np.ndarray, dict]:
sample = train.iloc[rows].reset_index(drop=True)
refit = spec._model().fit(sample, sample["months"], sample["event"])
found = refit.survival(members)
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
return found[: len(train)].mean(axis=0), by
all_months, all_event = members["months"].to_numpy(), members["event"].to_numpy(bool)
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
for m in drawn.values()] # fmt: skip
jobs += [delayed(mean_survival)(rows) for rows in samples]
done = Parallel(n_jobs=-1)(jobs)
drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
band = np.stack([r[0] for r in replicas])
point = model.survival(members)
scenarios = []
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
spread = np.array([r[1][name] for r in replicas])
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
scenarios.append({
"escenario": name,
"condiciones": [list(c) for c in spec.scenarios[name]],
"n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
"horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
**found,
"points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist()}},
"bootstrap_replicas": len(replicas),
}) # fmt: skip
skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
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 {
"model": spec.name,
"kind": "curves",
"curves": curves,
"predicted": {
"months": list(spec.borders[1:]),
"survival": model.survival(train).mean(axis=0).tolist(),
"low": np.percentile(band, 2.5, axis=0).tolist(),
"high": np.percentile(band, 97.5, axis=0).tolist(),
"name": "LR + HBN combinado (IC 95 % bootstrap)",
},
"weights_lr": model.weights_.tolist(),
"parents": [[spec.features[j] for j in parents] for _, (parents, _) in model.fitted_],
"combinations": [
{**row, "survival": survival[i].tolist()}
for i, row in enumerate(combinations.to_dict("records"))
],
"escenarios": scenarios,
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
}
-21
View File
@@ -1,21 +0,0 @@
from typing import Any
from models.base import ScreeningModel
class TeaModel(ScreeningModel):
"""Scaffold for the TEA (autism spectrum disorder) screening model.
Can pull its own training data straight from `persistance.tea`'s
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
...) or be handed already-fetched rows. No real model yet; this is
interface scaffolding only.
"""
domain = "tea"
def train(self, data: Any = None) -> None:
raise NotImplementedError("TEA training is not implemented yet.")
def predict(self, data: Any) -> Any:
raise NotImplementedError("TEA prediction is not implemented yet.")
View File
+2
View File
@@ -0,0 +1,2 @@
"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`,
`curves.py`)."""
+132
View File
@@ -0,0 +1,132 @@
"""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 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
`error` set, keeping the verdict and checks when validation finished before it. Missing values
are None.
"""
import math
import re
from dataclasses import dataclass, field
from datetime import date
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
DAYS_PER_MONTH = 30.4375
MAINS_HZ = 60.0
@dataclass(frozen=True)
class Metric:
code: str
value: float | None
electrodes: dict[str, float] = field(default_factory=dict) # None where not measured
zones: dict[str, float] = field(default_factory=dict)
@dataclass(frozen=True)
class Analysis:
valid: bool | None
level: str
age_months: float | None
clean_fraction: float | None
bad_channels: int | None
channels: int | None
duration_min: float | None
line_noise_db: float | None
sleep: bool | None
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
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
def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None
def _error(exc: Exception) -> str:
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}"
def analyze(
edf: bytes,
birth_date: date | None = None,
*,
age_months: float | None = None,
mains_hz: float = MAINS_HZ,
) -> Analysis:
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`)."""
out = dict(
valid=None,
level=checks.NOT_ANALYZABLE,
age_months=age_months,
clean_fraction=None,
bad_channels=None,
channels=None,
duration_min=None,
line_noise_db=None,
sleep=None,
checks=[],
metrics=[],
features={},
error=None,
)
try:
try:
rec = read.read(edf)
except read.FileNotValid as exc:
verdict = checks.file_not_valid(str(exc))
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)
out["age_months"] = age = header if header is not None else given
else:
age = age_months
verdict = checks.validate(rec, mains_hz)
out.update(
valid=verdict.valid,
level=verdict.level,
clean_fraction=verdict.clean_pct / 100,
bad_channels=len(verdict.bad),
channels=len(rec.names) or None,
duration_min=round(rec.duration_s / 60, 2),
line_noise_db=_number(verdict.line_db),
checks=verdict.checks,
)
if not verdict.valid:
return Analysis(**out)
prep = preprocess.prepare(rec, verdict.bad)
notes = sleep.note_intervals(prep.annotations, prep.duration_s)
states = sleep.states(prep, notes, age)
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)))
+113
View File
@@ -0,0 +1,113 @@
"""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.
Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-4 Hz) power of
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 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.
"""
import numpy as np
from scipy.fft import rfft, rfftfreq
from scipy.signal.windows import hann
from scipy.stats import theilslopes
from models.tea.eeg import signals, spikes, spindles
from models.tea.eeg.preprocess import WINDOW_S, Prepared
from models.tea.eeg.sleep import POSTERIOR
MIN_WINDOWS = 15
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_n2",
"spindles_n3",
"paroxysmal_spikes",
"anteroposterior_gradient",
)
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 a + n <= len(x) and np.isfinite(x[a : a + n]).all():
found.append(x[a : a + n].T)
return found or None
def posterior_rhythm(prep: Prepared, states) -> float:
names = prep.columns(POSTERIOR)
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)) if len(found) >= 2 else np.nan
def delta_gradient(prep: Prepared, states) -> float:
names = [c for c in prep.names if c in FRONT_BACK]
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)
power = np.abs(rfft((stack - stack.mean(axis=-1, keepdims=True)) * hann(n, sym=True))) ** 2
delta = np.median(power[..., (f >= 0.5) & (f < 4)].sum(axis=-1), axis=0)
log_power = np.log10(np.maximum(delta, 1e-30))
y = np.array([FRONT_BACK[c] for c in names])
finite = np.isfinite(log_power)
return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan
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}
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": 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}
return {code: metrics[code] for code in CODES}, features
+349
View File
@@ -0,0 +1,349 @@
"""Whether an EEG can be analysed: channel rules, 4 s window QC, triage level and gates.
Channel rules flag a channel bad (each reason is one check): dead (< 10 finite samples or SD
< 0.5 µV, which skips the rest), frozen, saturated, infinite values, gaps of its own; after the
mains notch and a 0.5-45 Hz band-pass, an amplitude over 4 x the scalp median, intermittent
contact (10 s blocks far below the montage) or bursts (far above it); on 1-40 Hz, a bridge with
a contiguous electrode or an ear that does not follow its neighbours; EOG/ECG out of range.
Window QC splits the kept scalp channels (notch, 0.5-45 Hz) into back-to-back 4 s windows: a
gap, or a window over 800 µV peak to peak, with muscle (30-45 / 4-13 Hz power, fixed lines out,
over 0.6) or common mode over 0.8, is not clean. Triage sets the level from coverage, bad scalp
electrodes and clean minutes; the gates make the EEG not valid when the level is
`not_analyzable`, fewer than 60 % of windows are clean or fewer than 12 scalp electrodes are
usable.
"""
from dataclasses import dataclass, field
import numpy as np
from models.tea.eeg import signals
from models.tea.eeg.read import Recording
NEIGHBOURS = {
"Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"),
"F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"),
"Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"),
"C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"),
"T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"),
"P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"),
"O2": ("T6", "P4", "O1"),
} # fmt: skip
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
MIN_CLEAN_PCT = 60.0
MIN_COVERAGE = 0.90
MAX_BAD_SCALP = 2
MIN_SCALP = 12
MAX_LINE_DB = 45.0
NOT_ANALYZABLE = "not_analyzable"
@dataclass(frozen=True)
class Validation:
valid: bool
level: str
bad: dict[str, list[str]] # channel -> reasons, every kind of channel
clean_pct: float
line_db: float
checks: list[dict] = field(default_factory=list)
@property
def ears_usable(self) -> bool:
return all(ear not in self.bad for ear in ("A1", "A2"))
def check(
code,
*,
electrode=None,
value=None,
text=None,
unit=None,
low=None,
high=None,
decisive=False,
abnormal=False,
) -> dict:
return dict(
code=code,
electrode=electrode,
value=value,
text=text,
unit=unit,
low=low,
high=high,
decisive=decisive,
abnormal=abnormal,
)
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)
def _filtered(x, fs, mains_hz, lo, hi):
return signals.bandpass(signals.notch(x, fs, mains_hz), fs, lo, hi)
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", "dead channel")]
out = []
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
out.append(("frozen", "frozen"))
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
out.append(("saturated", "saturated"))
if np.isinf(v).any():
out.append(("inf-values", "Inf values"))
return out
def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
"""Per channel, the fraction of 10 s blocks silent against the montage and bursting above it
(NaN with fewer than 6 blocks)."""
size = int(10 * fs)
blocks = len(y) // size
low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)
if blocks < 6:
return low, high
sd = np.full((blocks, y.shape[1]), np.nan)
for b in range(blocks):
block = y[b * size : (b + 1) * size]
if np.isfinite(block).all():
sd[b] = block.std(axis=0)
with np.errstate(all="ignore"):
relative = sd / np.maximum(np.nanmedian(sd, axis=1, keepdims=True), 1e-12)
for i in range(y.shape[1]):
v = relative[:, i]
v = v[np.isfinite(v) & (v > 0)]
if len(v) >= 6:
low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35))
high[i] = np.mean(v > 4.0)
return low, high
def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]:
"""Scalp channels correlating over 0.99 with a contiguous electrode and with no far one."""
finite = np.isfinite(y).all(axis=1)
if finite.sum() < 200 or len(scalp) < 2:
return {}
r = np.abs(np.corrcoef(y[finite][:, scalp].T))
index = {names[i]: k for k, i in enumerate(scalp)}
out = {}
for name, k in index.items():
near = [index[n] for n in NEIGHBOURS.get(name, ()) if n in index]
far = [j for j in index.values() if j != k and j not in near]
if not near:
continue
best = max(near, key=lambda j: r[k, j])
if r[k, best] > 0.99 and not (far and max(r[k, j] for j in far) > 0.99):
out[name] = next(n for n, j in index.items() if j == best)
return out
def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]:
"""Per ear: its best |r| with its neighbours, and the neighbours' median |r| between them."""
out = {}
for ear, around in EAR_NEIGHBOURS.items():
present = [n for n in around if n in names]
if ear not in names or len(present) < 2:
continue
cols = [names.index(ear)] + [names.index(n) for n in present]
rows = np.isfinite(y[:, cols]).all(axis=1)
if rows.sum() < fs * 30:
continue
r = np.abs(np.corrcoef(y[rows][:, cols].T))
between = [r[a, b] for a in range(1, len(cols)) for b in range(a + 1, len(cols))]
out[ear] = (float(np.nanmax(r[0, 1:])), float(np.nanmedian(between)))
return out
def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]:
"""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[: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)
scalp = [i for i, name in enumerate(names) if kinds[name] == "eeg"]
rms = np.nanstd(y45, axis=0)
median = float(np.nanmedian(rms[scalp])) if scalp else np.nan
ratio = rms / median if np.isfinite(median) and median > 0 else np.full(len(names), np.nan)
low, burst = _contact(y45, fs)
bridges = _bridges(y40, names, scalp)
ears = _ears(y40, fs, names)
missing = 1 - np.isfinite(x).mean(axis=0)
for i, name in enumerate(names):
found, k = reasons[name], kinds[name]
if missing[i] > missing.min() + 0.02:
excess = 100 * (missing[i] - missing.min())
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"bridge with {bridges[name]}"))
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
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"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"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"intermittent contact by bursts "
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
)
)
if k in ("eog", "ecg"):
v = x[:, i][np.isfinite(x[:, i])]
if np.sqrt(np.mean(v**2)) > 20000:
found.append(
(
"aux-amplitude",
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) -> 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`."""
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]
emg = {}
if any(whole):
stack = np.stack([s.T for s, ok in zip(segments, whole, strict=True) if ok])
f, power = signals.periodograms(stack, fs)
power = np.moveaxis(power, -1, 0)
high = signals.band_power(f, power, 30.0, 45.0, lines)
low = signals.band_power(f, power, 4.0, 13.0, lines)
ratio = np.median(high / np.maximum(low, 1e-12), axis=1)
emg = dict(zip([a for a, ok in zip(starts, whole, strict=True) if ok], ratio, strict=True))
out = []
for a, s, ok in zip(starts, segments, whole, strict=True):
if not ok:
out.append((a / fs, (a + n) / fs, "gap"))
continue
p2p = float(np.max(s.max(axis=0) - s.min(axis=0)))
variance = float(np.mean(s.var(axis=0)))
common = float(s.mean(axis=1).var() / variance) if variance > 0 else np.nan
muscle = float(emg[a])
suspect = p2p > 800 or (np.isfinite(muscle) and muscle > 0.6) or common > 0.8
out.append((a / fs, (a + n) / fs, "suspect" if suspect else "clean"))
return out
def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float):
"""(level, bad scalp electrodes by the triage rule)."""
x, fs, kinds = rec.x, rec.fs, rec.kinds()
columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")]
y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0)
rms, flat = {}, {}
for k, i in enumerate(columns):
v = y[:, k][np.isfinite(y[:, k])]
rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan
flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-9)) if len(v) > 1 else 1.0
scalp = rec.of("eeg")
median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan
triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5]
minutes = rec.duration_s * clean_pct / 100 / 60
base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP
if not (base and clean_pct >= 30 and minutes >= 3):
level = NOT_ANALYZABLE
elif not (clean_pct >= 50 and minutes >= 3):
level = "partial"
elif {"A1", "A2"} & {n for n in bad if kinds[n] == "ear"}:
level = "no_ear_reference"
else:
level = "complete"
return level, triaged
def validate(rec: Recording, mains_hz: float) -> Validation:
flagged = bad_channels(rec, mains_hz)
scalp = rec.of("eeg")
usable = [n for n in scalp if n not in flagged]
qc = usable if len(usable) >= 2 else scalp
y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0)
windows = window_qc(y, rec.fs)
clean_pct = 100.0 * sum(v == "clean" for *_, v in windows) / max(len(windows), 1)
coverage = float(np.isfinite(rec.x).all(axis=1).mean())
columns = [rec.names.index(n) for n in scalp] if scalp else slice(None)
db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz)
line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan
level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage)
rows = [
check(code, electrode=name, text=reason, abnormal=True)
for name, found in flagged.items()
for code, reason in found
]
rows += [
check(
"clean-windows",
value=clean_pct,
unit="%",
low=MIN_CLEAN_PCT,
abnormal=clean_pct < MIN_CLEAN_PCT,
decisive=True,
),
check(
"internal-coverage",
value=coverage,
unit="fraction",
low=MIN_COVERAGE,
abnormal=coverage < MIN_COVERAGE,
decisive=True,
),
check(
"bad-scalp-triage",
value=float(len(triaged)),
unit="electrodes",
high=float(MAX_BAD_SCALP),
abnormal=len(triaged) > MAX_BAD_SCALP,
decisive=True,
),
check(
"usable-scalp",
value=float(len(usable)),
unit="electrodes",
low=float(MIN_SCALP),
abnormal=len(usable) < MIN_SCALP,
decisive=True,
),
check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True),
]
if np.isfinite(line):
rows.append(
check(
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
)
)
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(valid, level, bad, clean_pct, line, rows)
+191
View File
@@ -0,0 +1,191 @@
"""Age baselines: each metric's value (and per electrode and zone) against children of the same
age in a reference cohort.
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`:
* Centile curves: on 120 ages log-spaced from 1 to 216 months, the p5, p25, median, p75 and p95
of the reference weighted by a Gaussian on log age (width 0.2), where the effective number of
studies is at least 30 and the age lies within the reference's. A value scores z = (value -
median) / ((median - p5 or p95 - median) / 1.645), outside -1 / +1 below p5 / above p95; the
centiles are interpolated on log age; ages outside the curve get none.
* Count rate (spikes, which most reference children never have): the reference's rate per
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.
"""
import math
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy import stats
QUANTILES = {"p5": 0.05, "p25": 0.25, "median": 0.5, "p75": 0.75, "p95": 0.95}
CURVE_AGES = np.exp(np.linspace(np.log(1.0), np.log(216.0), 120))
LOG_WIDTH = 0.2
MIN_EFFECTIVE = 30
COUNT_AGES = (16.0, 37.0)
Z_MAX = 8.0
EXPOSURE = "minutes"
@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-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",)),
}
PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float:
"""Interpolated between the midpoints of each weight's cumulative share."""
order = np.argsort(x)
x, w = x[order], w[order]
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
v, log_age = values[ok], np.log(ages[ok])
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
for a in CURVE_AGES:
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
n_effective = w.sum() ** 2 / (w**2).sum() if w.sum() > 0 else 0.0
inside = len(log_age) and log_age.min() <= np.log(a) <= log_age.max()
curve["age_months"].append(round(float(a), 3))
curve["n_effective"].append(round(float(n_effective), 1))
for name, q in QUANTILES.items():
enough = n_effective >= MIN_EFFECTIVE and inside
curve[name].append(round(_weighted_quantile(v, w, q), 4) if enough else None)
return {
"kind": "curves",
"log_width": LOG_WIDTH,
"min_effective": MIN_EFFECTIVE,
"curve": curve,
}
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])
n, x = n[keep], exposure[keep]
rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan")
mu = rate * x
excess = float(((n - mu) ** 2 - n).sum())
k = float((mu**2).sum() / excess) if excess > 0 else None # None: Poisson
return {
"kind": "count_rate",
"ages": list(COUNT_AGES),
"rate": rate,
"k": k,
"reference": int(keep.sum()),
"events": int(n.sum()),
}
def train(features: pd.DataFrame, scenario: str) -> dict:
"""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(["age_months", EXPOSURE], errors="ignore"):
values = pd.to_numeric(features[name]).to_numpy(float)
if counts:
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float))
else:
out[name] = _curve(values, ages)
return out
def _number(v) -> float | None:
return float(v) if v is not None and math.isfinite(v) else None
def _score_curve(baseline: dict, value: float, age: float) -> dict:
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"],
}
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 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}
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 or age_months is None:
return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
if baseline["kind"] == "count_rate":
return _score_count(baseline, value, age_months, _number(exposure))
return _score_curve(baseline, value, age_months)
def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
"""Metric code -> {"value": score, "electrodes": {e: score}, "zones": {z: score}} from the
trained scenarios in `models` (scenario -> `train`'s output); a scenario without a model
leaves its parts out."""
out = {m.code: {} for m in analysis.metrics}
metrics = {m.code: m for m in analysis.metrics}
for name, scenario in SCENARIOS.items():
model, metric = models.get(name), metrics.get(scenario.metric)
if model is None or metric is None:
continue
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
)
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
+11
View File
@@ -0,0 +1,11 @@
{
"source": "HK1K reference of the sleep-depth index (223 studies, 16-36 months): each window feature standardised by its median and dispersion, the posterior rhythm's median a line on log10 age; signs and weights of the weighted mean; cut-offs wake < -1.2327 <= drowsy < -0.3032 <= sleep",
"features": {
"delta_beta": {"median": 1.6117037688126001, "dispersion": 0.3097998485854789, "sign": 1, "weight": 1.0},
"posterior_rhythm": {"slope": 4.934510806157707, "intercept": 0.999676072265559, "median": 7.765061458878031, "dispersion": 1.021788597296859, "sign": -1, "weight": 1.0},
"sigma": {"median": 0.019957376774209706, "dispersion": 0.012167857665235331, "sign": 1, "weight": 0.7},
"muscle": {"median": 0.0742822337558628, "dispersion": 0.056777351044491706, "sign": -1, "weight": 0.7},
"alpha": {"median": 0.03498707283228359, "dispersion": 0.016352123389996105, "sign": -1, "weight": 0.6}
},
"cuts": [-1.2326590642152986, -0.3031551001049524]
}
+66
View File
@@ -0,0 +1,66 @@
"""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 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 warnings
from dataclasses import dataclass
import numpy as np
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
@dataclass(frozen=True)
class Prepared:
x: np.ndarray # (samples, scalp channels) µV, average reference
names: tuple[str, ...] # the kept scalp channels
fs: float
starts: np.ndarray # window grid starts, s
unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean
annotations: tuple[tuple[float, float, str], ...]
@property
def duration_s(self) -> float:
return len(self.x) / self.fs
def columns(self, wanted) -> list[str]:
"""The kept channels among `wanted`, in `wanted`'s order."""
return [name for name in wanted if name in self.names]
def data(self, names) -> np.ndarray:
return self.x[:, [self.names.index(name) for name in names]]
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, 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
referenced = y - np.nanmean(y, axis=1, keepdims=True)
# 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)
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)
+213
View File
@@ -0,0 +1,213 @@
"""An EDF's bytes as signals: the recognised channels in µV, their kind, the notes and dates.
`edfio` reads the header first: a file under 256 bytes, an unreadable header, no signals or no
recognised channel is not valid (`FileNotValid`). Channels sampled at another rate than the
majority, and later duplicates of a name, are dropped rather than resampled. MNE then reads the
kept channels' data (`reject_by_annotation="NaN"`: `BAD*` notes are gaps) and the notes.
Labels are normalised to 10-20 names (`EEG Fp1-REF` -> `Fp1`, T7/T8/P7/P8 -> T3/T4/T5/T6) or
to EKG/LOC/ROC; anything else is not a channel the analysis reads.
"""
import io
import re
from dataclasses import dataclass
from datetime import date, datetime
from struct import Struct
import edfio
import mne
import numpy as np
STANDARD = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz"
CANONICAL = {name.upper(): name for name in STANDARD.split()}
RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"}
AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC"))
EARS = {"A1", "A2"}
EOG = {"LOC", "ROC"}
# What a header's start date holds when the writer didn't know it.
UNKNOWN_START = date(1985, 1, 1)
class FileNotValid(ValueError):
"""The bytes are not an EDF the analysis can read."""
def normalize(label: str) -> str | None:
"""The channel's 10-20 name (or EKG/LOC/ROC), None if not a recognised channel."""
text = str(label).strip()
if not text or "ANNOT" in text.upper():
return None
stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0]
key = re.sub(r"[^A-Z0-9]", "", stem.strip().upper())
if key in CANONICAL:
name = CANONICAL[key]
return RENAMED.get(name, name)
return next((name for part, name in AUXILIARY if part in text.upper()), None)
def kind(name: str) -> str:
"""`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name."""
if name in EARS:
return "ear"
if name in EOG:
return "eog"
return "ecg" if name == "EKG" else "eeg"
@dataclass(frozen=True)
class Recording:
x: np.ndarray # (samples, channels) µV, NaN in gaps
fs: float
names: tuple[str, ...]
annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text)
start: date | None
birthday: date | None
@property
def duration_s(self) -> float:
return len(self.x) / self.fs
def kinds(self) -> dict[str, str]:
return {name: kind(name) for name in self.names}
def of(self, *kinds: str) -> list[str]:
"""The channels of these kinds, in file order."""
return [name for name in self.names if kind(name) in kinds]
@dataclass(frozen=True)
class Header:
patient_code: str | None
sex: str | None
birthdate: date | None
start_date: date | None
record_code: str | None
duration_s: float | None
channels: int
_FIXED = Struct("8s80s80s8s8s8s44s8s8s4s")
def _check_length(data: bytes) -> None:
if len(data) < _FIXED.size:
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
def _fixed_header(data: bytes) -> dict:
_check_length(data)
try:
(
version,
patient,
recording,
startdate,
starttime,
size,
reserved,
records,
duration,
signals,
) = (field.decode("ascii").strip() for field in _FIXED.unpack_from(data))
size, records, duration, signals = int(size), int(records), float(duration), int(signals)
if version != "0" or size != 256 * (1 + signals) or signals < 0:
raise ValueError
except ValueError as exc:
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
return dict(
version=version, patient=patient, recording=recording, startdate=startdate,
starttime=starttime, size=size, reserved=reserved, records=records,
duration=duration, signals=signals,
) # fmt: skip
def _date(value: str, fmt: str) -> date | None:
try:
return datetime.strptime(value, fmt).date()
except ValueError:
return None
def header(edf: bytes) -> Header:
"""Read the declared facts from the fixed header without opening any signals."""
fixed = _fixed_header(edf)
patient = fixed["patient"].split(maxsplit=3) + [""] * 3
recording = fixed["recording"].split(maxsplit=3) + [""] * 3
start = _date(recording[1], "%d-%b-%Y") if recording[0] == "Startdate" else None
return Header(
patient_code=None if patient[0] in ("", "X") else patient[0],
sex=patient[1] if patient[1] in ("F", "M") else None,
birthdate=_date(patient[2], "%d-%b-%Y"),
start_date=None if start == UNKNOWN_START else start,
record_code=None if recording[2] in ("", "X") else recording[2],
duration_s=None if fixed["records"] == -1 else fixed["records"] * fixed["duration"],
channels=fixed["signals"],
)
def _open(edf: bytes) -> edfio.Edf:
_check_length(edf)
try:
opened = edfio.read_edf(edf, lazy_load_data=True)
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
declared_records = int(edf[236:244])
if declared_records > opened.num_data_records:
raise FileNotValid("the EDF signal data is truncated")
return opened
def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
signals = _open(edf).signals
if not signals:
raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
named = [(label, name, rate) for label, name, rate in named if name is not None]
if not named:
raise FileNotValid("no recognised channel")
rates = [rate for _, _, rate in named]
fs = max(set(rates), key=rates.count)
kept, seen = [], set()
for label, name, rate in named:
if abs(rate - fs) <= 1e-6 and name not in seen:
seen.add(name)
kept.append((label, name))
return kept
def read(edf: bytes) -> Recording:
kept = _kept(edf)
options = dict(include=[label for label, _ in kept], preload=True, verbose="error")
try:
raw = mne.io.read_raw_edf(io.BytesIO(edf), **options)
except Exception as exc: # notes in a Windows code page
if "latin1" not in str(exc):
raise
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options)
raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name})
names = [name for name in raw.ch_names if name in {n for _, n in kept}]
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6
start = raw.info.get("meas_date")
born = (raw.info.get("subject_info") or {}).get("birthday")
notes = tuple(
(float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations
)
return Recording(
x=x,
fs=float(raw.info["sfreq"]),
names=tuple(names),
annotations=notes,
start=start.date() if isinstance(start, datetime) else start,
birthday=date(*born) if isinstance(born, tuple) else born,
)
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None:
"""Months from birth to the recording, to one decimal; None when a date is missing or is the
unknown-start placeholder, the birth is after the start or the age is over 18 years."""
if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
return None
months = round((start - birthday).days / days_per_month, 1)
return months if months <= 216 else None
+60
View File
@@ -0,0 +1,60 @@
"""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 (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 the cluster's workers; `tables` gives each scenario's training table
from the valid studies.
"""
from pathlib import Path
import pandas as pd
from models import execution
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)
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 = 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, age))
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(study: tuple[str, Path, float, float]) -> dict:
key, path, age, mains_hz = study
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz)
return {
"key": key,
"age_months": age,
"valid": a.valid,
"error": a.error,
"features": a.features,
}
def measure(studies, workers: int | None = None, mains_hz: float = MAINS_HZ) -> list[dict]:
"""Each study's verdict and features, in listing order."""
items = [(k, p, a, mains_hz) for k, p, a in studies]
return execution.map(_one, items, phase="measuring_reference", workers=workers)
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
"""Scenario -> its training table: the valid studies' features and `age_months`."""
usable = [s for s in measured if s["valid"] and s["error"] is None]
return {
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
for name in SCENARIOS
}
+162
View File
@@ -0,0 +1,162 @@
"""Signal primitives every step shares.
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 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
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
"""`(start, stop)` of each run of True."""
edges = np.diff(np.concatenate([[False], np.asarray(valid, bool), [False]]).astype(int))
return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True))
def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray:
"""`fn` on each gap-free run of rows at least `minimum` long; NaN elsewhere."""
x = np.asarray(x, float)
out = np.full_like(x, np.nan)
for a, b in runs(np.isfinite(x).all(axis=1)):
if b - a >= minimum:
out[a:b] = fn(x[a:b])
return out
def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray:
"""Zero-phase Butterworth band-pass of each gap-free run."""
sos = signal.butter(order, [lo / (fs / 2), hi / (fs / 2)], btype="band", output="sos")
minimum = max(3 * (2 * len(sos) + 1), int(fs))
return by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray:
"""Mains removal by spectrum interpolation: around `f0` and each harmonic below 98 % of
Nyquist, the FFT magnitudes within `width` Hz are replaced by a line from the mean magnitude
of the `2 width` Hz on the left to that on the right, keeping the phase."""
centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98]
def interpolate(run):
f = np.fft.rfftfreq(len(run), 1 / fs)
spectrum = np.fft.rfft(run, axis=0)
for c in centres:
inside = (f >= c - width) & (f <= c + width)
left = (f >= c - 3 * width) & (f < c - width)
right = (f > c + width) & (f <= c + 3 * width)
if not (inside.any() and left.any() and right.any()):
continue
k = np.linspace(0, 1, int(inside.sum()))[:, None]
target = (
np.abs(spectrum[left]).mean(axis=0)[None, :] * (1 - k)
+ np.abs(spectrum[right]).mean(axis=0)[None, :] * k
)
current = spectrum[inside]
magnitude = np.abs(current)
phase = np.where(magnitude > 0, current / np.maximum(magnitude, 1e-30), 1.0)
spectrum[inside] = target * phase
return np.fft.irfft(spectrum, n=len(run), axis=0)
return by_runs(x, interpolate, max(int(2 * fs), 256))
def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
"""Per channel, dB of the mains peak (`f0` ± 0.6 Hz) over its neighbourhood (2-6 Hz away),
from one Hann-tapered FFT of the rows finite in every channel."""
finite = np.isfinite(x).all(axis=1)
if not finite.any():
return np.full(x.shape[1], np.nan)
run = x[finite] - x[finite].mean(axis=0)
f = np.fft.rfftfreq(len(run), 1 / fs)
power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2
peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0)
around = ((f >= f0 - 6) & (f <= f0 - 2)) | ((f >= f0 + 2) & (f <= f0 + 6))
near = power[around].mean(axis=0)
with np.errstate(divide="ignore", invalid="ignore"):
return 10 * np.log10(np.where(near > 0, peak / near, np.nan))
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))`."""
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]:
"""Frequencies of narrow fixed lines of a recording (artefacts, not EEG): the power of 8 s
Hann segments, averaged and its median taken over channels, in dB above a 4 Hz running
median; local maxima in [1, f_max] Hz at least 6 dB up and at most 0.5 Hz wide at -3 dB,
the most prominent kept where two lie within 0.5 Hz."""
n = int(round(8 * fs))
f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None]
total, count = None, 0
for a in range(0, len(x) - n + 1, n):
segment = x[a : a + n]
if np.isfinite(segment).all():
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
total = power if total is None else total + power
count += 1
if not count:
return []
db = 10 * np.log10(np.maximum(np.median(total / count, axis=1), 1e-30))
df = float(f[1] - f[0])
half = max(1, int(round(2 / df)))
prominence = db - median_filter(db, size=2 * half + 1, mode="nearest")
f_max = min(f_max, fs / 2 - 2)
found = []
for i in range(1, len(f) - 1):
p = prominence[i]
if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or p < prominence[i + 1]:
continue
a = b = i
while a > 0 and prominence[a - 1] >= p - 3:
a -= 1
while b < len(f) - 1 and prominence[b + 1] >= p - 3:
b += 1
if (b - a + 1) * df <= 0.5:
found.append((round(float(f[i]), 3), round(float(p), 1)))
kept = []
for hz, db_up in sorted(found, key=lambda line: -line[1]):
if all(abs(hz - other) > 0.5 for other, _ in kept):
kept.append((hz, db_up))
return [hz for hz, _ in kept]
def band_power(f, power, lo, hi, lines=(), include_hi=False):
"""Power summed over [lo, hi) Hz (`include_hi`: [lo, hi]) along the first axis of `power`,
without the bins within 1 Hz of a fixed line, rescaled to the band's full width."""
band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
clean = band.copy()
for line in lines:
clean &= np.abs(f - line) > 1.0
if not clean.any():
return np.full(power.shape[1:], np.nan) if power.ndim > 1 else np.nan
return power[clean].sum(axis=0) * (band.sum() / clean.sum())
def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]:
"""The largest 3-14 Hz peak over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz:
(Hz, prominence in dB, found). Found when at least 1.5 dB up and not at the band's edge."""
usable = (f >= 1.5) & (f <= 45) & (power > 0)
background = usable & ~((f >= 4) & (f <= 16))
if background.sum() < 5:
return np.nan, np.nan, False
line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1)
residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable])))
fu = f[usable]
band = (fu >= 3) & (fu <= 14)
if not band.any():
return np.nan, np.nan, False
i = int(np.argmax(residual[band]))
prominence = float(residual[band][i])
found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1
return (float(fu[band][i]) if found else np.nan), prominence, bool(found)
+223
View File
@@ -0,0 +1,223 @@
"""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 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,
muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is standardised by
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 unicodedata
from pathlib import Path
import numpy as np
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())
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)
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:
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]]:
"""(onset s, duration s, state) covering the record: the notes' states and `unmarked`."""
notes = sorted(annotations, key=lambda note: note[0])
found = []
for i, (t0, length, text) in enumerate(notes):
state = note_state(text)
if state is None:
continue
if length > 0:
t1 = t0 + length
else:
following = next((n[0] for n in notes[i + 1 :] if note_state(n[2])), None)
t1 = min(t0 + 60.0, following if following else t0 + 60.0)
if t1 - t0 >= 1:
found.append((t0, t1, state))
found.sort(key=lambda piece: piece[0])
full, cursor = [], 0.0
for t0, t1, state in found:
if t0 - cursor >= 1:
full.append((cursor, t0, "unmarked"))
full.append((t0, t1, state))
cursor = max(cursor, t1)
if duration_s - cursor >= 1:
full.append((cursor, duration_s, "unmarked"))
pieces = [(round(t0, 2), round(t1, 2), state) for t0, t1, state in full]
return [(t0, t1 - t0, state) for t0, t1, state in pieces]
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
"""The state covering most of [t0, t1) and whether it covers less than 80 % of it."""
overlap = {}
for onset, length, state in intervals:
lo, hi = max(t0, onset), min(t1, onset + length)
if hi > lo:
overlap[state] = overlap.get(state, 0) + (hi - lo)
if not overlap:
return "unlabelled", False
dominant = max(overlap, key=overlap.get)
return dominant, overlap[dominant] < 0.8 * (t1 - t0)
def mask(prep: Prepared, intervals) -> np.ndarray:
"""Samples of the QC spans and of the masked notes."""
out = np.zeros(len(prep.x), bool)
spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)]
for onset, length in spans:
out[int(onset * prep.fs) : int((onset + length) * prep.fs)] = True
return out
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]:
"""Start samples of the usable windows and their features."""
fs, x, names = prep.fs, prep.x, list(prep.names)
n, step = int(WINDOW_S * fs), int(2 * fs)
starts = [
a
for a in range(0, len(x) - n + 1, step)
if np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any()
]
if not starts:
return [], {}
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
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))))
posterior = [names.index(c) for c in POSTERIOR if c in names]
delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
features = {
"delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)),
"sigma": np.median((band["sigma"] / total)[:, central], axis=1),
"muscle": np.median(
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
),
"alpha": np.median(band["alpha"] / total, axis=1),
}
if posterior:
peaks = [
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts))
]
features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
return starts, features
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray:
"""The weighted mean of the standardised features, clipped to ±6."""
z, weights = [], []
for name, ref in REFERENCE["features"].items():
if name not in features:
continue
if "slope" in ref and age_months and age_months > 0:
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
else:
median = ref["median"]
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9))
weights.append(ref["weight"])
w = np.array(weights, float)
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
"""`wake`, `drowsy`, `sleep` or `` (not scored) per grid window."""
starts, features = _features(prep, mask(prep, intervals))
out = np.full(len(prep.starts), "", dtype=object)
if not starts:
return out
labels = STATES[np.digitize(depth(features, age_months), REFERENCE["cuts"])]
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
+232
View File
@@ -0,0 +1,232 @@
"""Paroxysmal spikes in sleep: candidates per channel, merged into discharges, counted against
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.
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
flanks at least 6 x the MAD of the channel's slope; inside a kept window. Its field is the
number of 10-20 neighbours with a same-sign candidate within 25 ms.
Discharge: candidates closer than 180 ms are one; the largest (in MADs) gives its channel, state
and width. A useful discharge has field and is not a vertex wave (asleep, max on Cz/Fz/Pz, a
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 (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
import numpy as np
import pandas as pd
from models.tea.eeg import signals
from models.tea.eeg.checks import NEIGHBOURS
from models.tea.eeg.preprocess import WINDOW_S, Prepared
from models.tea.eeg.sleep import EXCLUDED, window_note
from models.tea.eeg.spindles import ZONES
ELECTRODES = tuple(NEIGHBOURS)
GATE_S = 2.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 = ("N2", "N3", "sleep")
@dataclass(frozen=True)
class Spikes:
rate: float # useful discharges per minute of clean sleep
electrodes: dict[str, float]
zones: dict[str, float]
minutes: float # clean sleep minutes, the rate's exposure
def _mad(v: np.ndarray) -> float:
v = v[np.isfinite(v)]
if not len(v):
return np.nan
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
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 = []
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]
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)))
return kept
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
"""(slower flank's slope µV/s, width ms) of the transient peaking at `i`, at half height."""
n = len(y)
if i <= 0 or i >= n - 1:
return np.nan, np.nan
w = int(500 * fs / 1000)
base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
peak = float(y[i]) - base
if peak == 0.0:
return np.nan, np.nan
sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)
a, low = i, max(0, i - reach)
while a > low and sign * (y[a] - base) >= half:
a -= 1
b, high = i, min(n - 1, i + reach)
while b < high and sign * (y[b] - base) >= half:
b += 1
if b <= a:
return np.nan, np.nan
rise, fall = half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)
return float(min(rise, fall)), float((b - a) / fs * 1000.0)
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel()
if np.isfinite(y).sum() < fs * 2:
return []
slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y)
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
return []
v = np.abs(y)
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else []
after = int(100 * fs / 1000), int(500 * fs / 1000)
out = []
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
slope, width = _flanks(y, int(i), fs)
if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0):
continue
if slope < 6.0 * slope_mad:
continue
a, b = int(i) + after[0], min(int(i) + after[1], len(y))
post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
out.append(
dict(
channel=channel,
t=float(i) / fs,
sign=int(np.sign(y[i])),
width=width,
size=float(abs(y[i]) / amplitude_mad),
post=post,
)
)
return out
def _field(c: pd.DataFrame) -> np.ndarray:
"""Per candidate, its 10-20 neighbours with a same-sign candidate within 25 ms."""
times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])}
out = np.zeros(len(c), int)
for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)):
for other in NEIGHBOURS.get(ch, ()):
near = times.get((other, s))
if near is None:
continue
j = np.searchsorted(near, t)
close = near[max(j - 1, 0) : j + 1]
out[k] += bool(np.any(np.abs(close - t) <= 0.025))
return out
def _merge(c: pd.DataFrame) -> pd.DataFrame:
"""One row per discharge: candidates closer than 180 ms."""
c = c.iloc[np.argsort(c.t.to_numpy(), kind="quicksort")].reset_index(drop=True)
groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1)
rows = []
for g in groups:
part = c.iloc[g]
top = c.loc[part["size"].idxmax()]
asleep = top.state in ASLEEP
signs = dict(zip(part.channel, part.sign, strict=True))
frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR)
opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT)
vertex = asleep and top.channel in VERTEX and float(part.post.max()) > 3.0
posts = asleep and top.channel in POSTS and top.sign > 0 and top.width > 80.0
rows.append(
dict(
channel=top.channel,
state=top.state,
field=int(part.field.max()),
useful=not (vertex or posts or frontal_only or opposite),
)
)
return pd.DataFrame(rows, columns=["channel", "state", "field", "useful"])
def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
"""None with fewer than 4 10-20 channels."""
channels = [c for c in prep.names if c in ELECTRODES]
if len(channels) < 4:
return None
fs = prep.fs
x = np.array(prep.data(channels), dtype=np.float64)
labelled = [
(s, s + WINDOW_S, label)
for s, label in zip(prep.starts, states, strict=True)
if label in ("wake", "drowsy", "sleep")
]
def state_at(t: np.ndarray) -> np.ndarray:
"""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 = _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(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:
c = pd.DataFrame(candidates)
t = c.t.to_numpy(float)
inside = np.zeros(len(t), bool)
for t0, t1 in gate:
inside |= (t >= t0) & (t < t1)
c = c[inside]
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) & (found.state == "sleep")]
for channel, n in found.channel.value_counts().items():
counts[channel] = int(n)
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 = {}
for zone, members in ZONES.items():
present = [e for e in members if e in counts]
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))
+181
View File
@@ -0,0 +1,181 @@
"""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 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 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.
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.
"""
from dataclasses import dataclass
import numpy as np
from scipy.signal import hilbert, welch
from models.tea.eeg import signals
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)
ZONES = {
"frontal_left": ("Fp1", "F3", "F7"),
"frontal_right": ("Fp2", "F4", "F8"),
"frontal_midline": ("Fz",),
"central": ("C3", "Cz", "C4"),
"parietal": ("P3", "Pz", "P4"),
"temporal_left": ("T3", "T5"),
"temporal_right": ("T4", "T6"),
"occipital": ("O1", "O2"),
}
@dataclass(frozen=True)
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 the stage)
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
y = signals.bandpass(x, fs, *SIGMA)
envelope = np.abs(hilbert(np.nan_to_num(y), axis=0))
k = max(1, int(0.2 * fs))
envelope = np.apply_along_axis(
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
)
envelope[~np.isfinite(y)] = np.nan
return y, envelope
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
edges = np.diff(extent.astype(np.int8), prepend=0, append=0)
out = []
for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True):
if not core[a:b].any():
continue
if 0.5 <= (b - a) / fs <= 3.0:
out.append((int(a), int(b)))
elif (b - a) / fs > 3.0:
step = int(3.0 * fs)
for c in range(a, b, step):
e = min(c + step, b)
if 0.5 <= (e - c) / fs <= 3.0 and core[c:e].any():
out.append((int(c), int(e)))
return out
def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
"""Sigma over its flanks, and an instantaneous frequency in band."""
if not np.isfinite(x).all():
return False
nperseg = min(len(x), int(fs))
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
if not inside.any() or not flanks.any():
return False
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
return False
frequency = np.diff(np.unwrap(np.angle(hilbert(y)))) * fs / (2 * np.pi)
frequency = frequency[np.isfinite(frequency)]
in_band = frequency[(frequency >= SIGMA[0] - 1) & (frequency <= SIGMA[1] + 1)]
if len(in_band) < 0.5 * max(len(frequency), 1):
return False
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
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, 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 < 1 or not names:
return Spindles([], minutes, [])
x = prep.data(names)
y, envelope = _envelope(x, fs)
events = []
for i, name in enumerate(names):
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_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)
def density(found: Spindles) -> tuple[float, dict[str, float]]:
"""Spindles per minute and channel (rounded to 3), and per zone; NaN when none."""
zones = dict.fromkeys(ZONES, np.nan)
if not found.events or found.minutes <= 0:
return np.nan, zones
counts = {}
for _, _, channel in found.events:
counts[channel] = counts.get(channel, 0) + 1
for zone, electrodes in ZONES.items():
searched = [e for e in electrodes if e in found.channels]
if searched:
total = sum(counts.get(e, 0) for e in searched)
zones[zone] = total / (found.minutes * len(searched))
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
return round(per_channel, 3), zones
def _episodes(events) -> list[list[float]]:
if not events:
return []
a = np.array([onset for onset, _, _ in events], float)
b = a + np.array([length for _, length, _ in events], float)
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 out
def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]:
"""Per spindle electrode, the envelope's median peak over episodes against its sleep median
(NaN for an absent electrode, or without spindles)."""
out = dict.fromkeys(CHANNELS, np.nan)
use = prep.columns(CHANNELS)
episodes = _episodes(found.events)
if not use or not episodes:
return out
fs = prep.fs
y = signals.bandpass(prep.data(use), fs, *SIGMA)
envelope = signals.by_runs(y, lambda run: np.abs(hilbert(run, axis=0)), int(fs))
asleep = np.zeros(len(envelope), bool)
for start, label in zip(prep.starts, states, strict=True):
if label == "sleep":
asleep[int(start * fs) : int((start + WINDOW_S) * fs)] = True
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
peaks = np.full((len(episodes), len(use)), np.nan)
for k, (t0, t1) in enumerate(episodes):
a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))
if b - a >= 3:
peaks[k] = np.nanmax(envelope[a:b], axis=0)
for j, name in enumerate(use):
if np.isfinite(median[j]) and median[j] > 0:
out[name] = float(np.nanmedian(peaks[:, j]) / median[j])
return out
+173
View File
@@ -0,0 +1,173 @@
"""TEA jobs analyse the hospital's EEGs and score them against seven age curves
(models.tea.eeg.curves). Training uses a named reference cohort or the legacy
TEA_REFERENCE_DIR and TEA_REFERENCE_AGES settings.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
features are kept in TEA_REFERENCE_CACHE in a JSON file named by the cohort and its hash.
Changes to the study list, ages or mains frequency require measuring the cohort again."""
import hashlib
import json
import os
from dataclasses import dataclass
from datetime import date
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from models import execution
from models.tea.eeg import analysis, curves
from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
MODELS = curves.SCENARIOS
CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
GOLD_SELECT = ["tea_eeg_analyses+", "tea_eeg_metrics+"] # what a rebuild of TEA's gold selects
class Baseline(mlflow.pyfunc.PythonModel):
"""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
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
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"))
for r in rows]) # fmt: skip
def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
edf, birth, signal = item
return edf, analysis.analyze(signal, birth)
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
"""The EEGs in scope (default: those not analysed yet), analysed in the ambient
execution; then, unless told not to, gold's TEA tables are rebuilt. Bronze is written
once, after the last study, so a cancelled run leaves it as it was."""
rows = eeg.select(scope or eeg.Scope())
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows) # lazy: bytes travel
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
eeg.save_analyses(found)
if rebuild_gold:
silver.build(GOLD_SELECT)
return len(found)
def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
"""The reference cohort's hash, cached measurements, name and mains frequency."""
if reference is None:
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
name, line_hz = cohort_reference.NAME, 50
else:
folder = cluster.reference_dir(reference.name)
ages = folder / "edades.csv"
if not ages.is_file():
raise ValueError(f"reference cohort {reference.name!r} has no edades.csv")
name, line_hz = reference.name, reference.line_hz
studies = cohort_reference.listing(folder, ages)
if reference is not None and not studies:
raise ValueError(f"reference cohort {name!r} has no EDF with an age from 16 to 36 months")
content = "\n".join(f"{p.name}|{a}" for _, p, a in studies)
if line_hz != 50:
content += f"|line_hz={line_hz}"
digest = hashlib.sha256(content.encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{name}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text()), name, line_hz
measured = cohort_reference.measure(studies, mains_hz=float(line_hz))
measured = [{**m, "key": str(m["key"])} for m in measured]
if path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(measured))
return digest, measured, name, line_hz
@dataclass(frozen=True)
class Jobs:
"""The domain's model jobs (models.definitions): every curve is routine."""
def routine(self) -> list[str]:
return list(MODELS)
JOBS = Jobs()
def registered(name: str) -> str:
return f"tea.{name}"
def train(name: str, as_of: date | None = None, reference: cluster.Reference | None = None) -> int:
"""A new version of one age curve, trained on the reference cohort's valid studies,
with its two reports: the cohort it learned from, and its centile curves."""
digest, measured, cohort, hz = _reference(reference)
table = cohort_reference.tables(measured)[name]
baseline = curves.train(table, name)
valid = [m for m in measured if m["valid"] and m["error"] is None]
technical = {
"model": name, "method": "age curves (weighted centiles on log age)",
"cohort": cohort, "cohort_sha256": digest, "line_hz": hz, "studies": len(measured),
"valid_studies": len(valid),
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
"features": sorted(baseline),
} # fmt: skip
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
params = {"cohort": cohort, "cohort_sha256": digest, "line_hz": str(hz)}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
def score_curves() -> dict[str, int | None]:
"""The version of each age curve's champion that scored, None without a champion."""
return {name: score(name) for name in CURVES}
def relate() -> int | None:
"""The ADOS-2 association: scores every analysed EEG with the `ados2_association`
champion (Phase 2). Returns the version that scored, None when the model has no champion.
It writes bronze only (ASSOCIATION_SCORES); the gold rebuild is the job's last step, not
this one's. Until Phase 2 exists it does nothing."""
return None
def score(name: str) -> int | None:
"""The champion curve's scores of every analysed EEG: the metric's value, and each
electrode and zone it measures; None without a champion."""
found = registry.champion(registered(name))
if found is None:
return None
version, model = found
baseline = model.unwrap_python_model().baseline
scenario, label = MODELS[name], f"{registered(name)}/{version}"
rows = []
for one in eeg.analysed():
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
if metric is None:
continue
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]
for site, value in sites.items():
feature = "value" if part == "value" else prefix + site
if feature not in baseline:
continue
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
eeg.save_scores(name, rows)
return version
+216
View File
@@ -0,0 +1,216 @@
"""Analyse a single study and its optional report without persisting the results."""
import math
from dataclasses import replace
from datetime import date
from core import concept_map, tea
from core.pipeline import apply_patterns
from core.tea import ados2 as scoring
from models import graph
from models.tea.eeg import analysis, curves, read
from models.tea.jobs import MODELS
from persistance import config_log, registry
from persistance.previews import PreviewAdos2, PreviewEeg, PreviewMetric, PreviewResult, Site
def _deviations(models: dict, study: analysis.Analysis) -> dict:
metrics = {metric.code: metric for metric in study.metrics}
missing_values = set()
for name, baseline in models.items():
scenario = curves.SCENARIOS[name]
if scenario.metric not in metrics:
continue
metric = metrics[scenario.metric]
changes = {
part: {
site: value
for site, value in getattr(metric, part).items()
if curves.PREFIX[part] + site in baseline
}
for part in scenario.parts
if part != "value"
}
if "value" in scenario.parts and "value" not in baseline:
# A missing value short-circuits curves.score, while the sites still get scored.
models[name] = baseline | {"value": {}}
changes["value"] = None
missing_values.add(metric.code)
metrics[metric.code] = replace(metric, **changes)
features = {name: study.features.get(name, {}) for name in models}
found = curves.deviations(
models, replace(study, metrics=list(metrics.values()), features=features)
)
for code in missing_values:
found.get(code, {}).pop("value", None)
return found
def _sites(values: dict, scores: dict) -> dict[str, Site]:
return {key: Site(value=value, score=scores.get(key)) for key, value in values.items()}
def _metrics(study: analysis.Analysis, warnings: list[str]) -> list[PreviewMetric]:
models, versions = {}, {}
found = {}
if study.valid:
for name in curves.SCENARIOS:
champion = registry.champion(f"tea.{name}")
if champion is not None:
versions[name], model = champion
models[name] = model.unwrap_python_model().baseline
if not models:
warnings.append("there are no champion age curves: no z is shown")
else:
codes = {metric.code for metric in study.metrics}
warnings.extend(
f"no champion for {name}: its z is not shown"
for name, scenario in curves.SCENARIOS.items()
if name not in models and scenario.metric in codes
)
found = _deviations(models, study)
labels = {
MODELS[name].metric: f"tea.{name}/{version}"
for name, version in versions.items()
if "value" in MODELS[name].parts
}
metrics = []
for metric in study.metrics:
parts = found.get(metric.code, {})
metrics.append(
PreviewMetric(
code=metric.code,
value=metric.value,
score=parts.get("value"),
model=labels.get(metric.code) if "value" in parts else None,
electrodes=_sites(metric.electrodes, parts.get("electrodes", {})),
zones=_sites(metric.zones, parts.get("zones", {})),
)
)
return metrics
def _parse(field, value, kind, warnings):
if value is None:
return None
try:
if kind == "date":
return value if isinstance(value, date) else date.fromisoformat(value)
number = float(value)
if math.isfinite(number):
return number
except (TypeError, ValueError):
pass
warnings.append(f"{field}: could not read {value!r} as a {kind}")
return None
def _report(
content: bytes,
pipeline: str,
recorded_on: date | None,
birth: date | None,
warnings: list[str],
) -> PreviewAdos2 | None:
if not content.startswith(b"%PDF"):
warnings.append("the ADOS-2 file is not a PDF")
return None
text = graph.read_file(content)
if error := text["error"]:
warnings.append(f"the ADOS-2 report could not be read: {error}")
return None
try:
saved = config_log.get(pipeline)
except Exception: # noqa: BLE001 -- an unavailable saved pipeline is reported in the result
saved = None
if saved is None:
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
return None
_, definition = saved
node = next((n for n in definition.nodes if n.kind == "extract" and n.entity == "ados2"), None)
if node is None:
warnings.append(f"pipeline {pipeline} has no ados2 extract node")
return None
codes = {}
if node.concept_map:
mapping = config_log.concept_map(node.concept_map)
codes = {field: concept_map.table([mapping], field) for field in node.patterns}
found = apply_patterns(node, text["text"], codes)
if not found:
warnings.append("no ADOS-2 field was found in the report")
return None
row = dict(found[0][0])
fields = sorted(row)
evaluation_date = _parse("evaluation_date", row.get("evaluation_date"), "date", warnings)
if "evaluation_date" not in row:
evaluation_date = recorded_on
items = {
item: _parse(item, row.get(item), "number", warnings)
for item in tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
}
css, classification = None, None
if evaluation_date is None:
warnings.append("ADOS-2 not scored: no evaluation date")
else:
try:
css, classification = scoring.score(
row | items | {"evaluation_date": evaluation_date}, birth
)
except (ValueError, TypeError) as exc:
warnings.append(f"ADOS-2 not scored: {exc}")
else:
if css is None and classification is None:
warnings.append(
"the ADOS-2 score could not be calculated: "
"the report lacks the module or the item scores"
)
return PreviewAdos2(
module=row.get("module"),
evaluation_date=evaluation_date,
items=items,
css=css,
classification=classification,
read=fields,
)
def preview(
edf: bytes,
ados2: bytes | None = None,
birth_date: date | None = None,
pipeline: str = "tea",
) -> PreviewResult:
study = analysis.analyze(edf, birth_date)
try:
header = read.header(edf)
except read.FileNotValid:
header = None
recorded_on = header.start_date if header else None
warnings = []
if study.error:
warnings.append(f"the EEG analysis ended with an error: {study.error}")
eeg = PreviewEeg(
valid=study.valid,
level=study.level,
recorded_on=recorded_on,
age_months=study.age_months,
clean_fraction=study.clean_fraction,
bad_channels=study.bad_channels,
channels=study.channels,
duration_min=study.duration_min,
line_noise_db=study.line_noise_db,
sleep=study.sleep,
checks=study.checks,
metrics=_metrics(study, warnings),
error=study.error,
)
report = None
if ados2 is not None:
birth = birth_date or (header.birthdate if header else None)
report = _report(ados2, pipeline, recorded_on, birth, warnings)
return PreviewResult(eeg=eeg, ados2=report, warnings=warnings)
-143
View File
@@ -1,143 +0,0 @@
"""Bookkeeping around a training run (ML-01..ML-05).
Does not train anything. It opens an MLflow run, records which cohort
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
methods instead of the fluent API's global active run, so two runs in one
process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
"""
import json
import os
from pathlib import Path
from typing import Any
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.repository import Repository
from models.base import resolve_repository
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
class ReadOnlyRepository:
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
Write methods raise `PermissionError` so a training routine cannot
modify clinical data."""
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
def __init__(self, repository: Repository):
self._repository = repository
self.model = repository.model
def get(self, id_):
return self._repository.get(id_)
def list(self, *, limit: int = 100, offset: int = 0, **filters):
return self._repository.list(limit=limit, offset=offset, **filters)
def count(self, **filters) -> int:
return self._repository.count(**filters)
def __getattr__(self, name: str):
if name in self._WRITE_METHODS:
raise PermissionError(
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs require `cohorte_armado_id`, the indicator kit cohort build they were
trained on, so their metrics trace back to that data (ML-03); dev runs may
omit it.
"""
def __init__(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
):
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
environment = Environment(environment)
if environment is Environment.PROD and cohorte_armado_id is None:
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
self.domain = domain
self.scenario = scenario
self.environment = environment
self.cohorte_armado_id = cohorte_armado_id
self.client = MlflowClient()
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
)
self.run_id = run.info.run_id
if cohorte_armado_id is not None:
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
return ReadOnlyRepository(resolve_repository(self.domain, entity))
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
named for its kind."""
kind = ArtifactKind(kind)
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
if metadata:
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
def finish(
self,
*,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""Logs metrics/params to the run, registers it as a new version of
`<domain>-<scenario>` tagged with `models.registry`'s promotion
inputs (environment, cohort link, report URIs), and returns the new
version string. Call once, after training (and artifact logging)
completes."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
for key, value in (metrics or {}).items():
self.client.log_metric(self.run_id, key, value)
for key, value in (hyperparameters or {}).items():
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
name = registered_name(self.domain, self.scenario)
try:
self.client.create_registered_model(name)
except MlflowException as exc:
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
raise
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
if self.cohorte_armado_id is not None:
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
version_tags.update({key: uri for key, uri in reports.items() if uri})
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
self.client.set_terminated(self.run_id)
return str(model_version.version)
+28 -28
View File
@@ -1,36 +1,36 @@
[project]
name = "models"
version = "0.1.0"
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
requires-python = ">=3.11"
version = "0.0.0"
description = "Dagster assets and jobs; one module per model."
requires-python = ">=3.12"
dependencies = [
"core",
"persistance",
"extraction",
"mlflow>=2.9",
"dagster",
"dagster-webserver",
"mlflow-skinny",
"openai>=3.59.0",
"splink>=5.0.0",
"markitdown[docx,xlsx]>=0.1.9",
"ocrmypdf>=17.14.2",
"pdfplumber>=0.11.11",
"scikit-learn>=1.9.1",
"scipy>=1.18.1",
"joblib>=1.6.0",
"lifelines>=0.30.0",
"mne>=1.13.2",
"edfio>=0.4.18",
"statsmodels>=0.15.0",
"pgmpy>=1.1.2",
]
[project.optional-dependencies]
# Only needed to read back a checkpoint's own metadata (opset, producer) in
# models.export.inspect_onnx_metadata — writing/logging a checkpoint never
# requires it, see that module's docstring.
export = [
"onnx>=1.15",
]
[tool.uv.sources]
persistance = { path = "../Persistance", editable = true }
extraction = { path = "../Extraction", editable = true }
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
requires = ["uv_build>=0.12,<0.13"]
build-backend = "uv_build"
[tool.hatch.build.targets.wheel]
packages = ["models"]
[dependency-groups]
dev = [
"pytest>=8.0.0",
"onnx>=1.15",
"reportlab>=4.0",
]
[tool.uv.build-backend]
module-name = "models"
module-root = ""
[tool.uv.sources]
core = { workspace = true }
persistance = { workspace = true }
-93
View File
@@ -1,93 +0,0 @@
import pytest
def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str):
import importlib
from persistance import db as persistance_db
from persistance import settings as persistance_settings
monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}")
engine = getattr(persistance_db, f"get_{domain}_engine")
engine.cache_clear()
importlib.import_module(f"core.{domain}.models")
if domain != "governance":
importlib.import_module(f"core.{domain}.indicadores.models")
base = getattr(importlib.import_module(base_module), base_class)
base.metadata.create_all(engine())
return engine
@pytest.fixture
def governance_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel")
yield
engine.cache_clear()
@pytest.fixture
def cacu_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel")
yield
engine.cache_clear()
@pytest.fixture
def mlflow_tracking(tmp_path, monkeypatch):
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
import mlflow
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
mlflow.set_tracking_uri(uri)
monkeypatch.chdir(tmp_path)
yield
@pytest.fixture
def production_ready(governance_db, cacu_db, mlflow_tracking):
"""Factory: registers a PROD version that passes every promotion check,
returns (domain, scenario, version)."""
from core.governance.enums import ArtifactKind, Environment
from models.registry import registry
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
version = registry.register(
domain=domain, scenario=scenario, environment=Environment.PROD,
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
interpretability_report_uri="docs/interpretabilidad.html",
)
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
return domain, scenario, version
return make
def tiny_onnx() -> bytes:
import onnx.helper
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
def armado(huella: str) -> int:
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
from datetime import date, datetime, timezone
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
from persistance.db import get_cacu_session
with get_cacu_session() as session:
fila = CohorteArmado(
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8,
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
session.add(fila)
session.flush()
session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10),
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
session.commit()
return fila.armado_id
+78
View File
@@ -0,0 +1,78 @@
import sqlite3
from datetime import date
from pathlib import Path
import edfio
import numpy as np
SEX_MAP = {
"resourceType": "ConceptMap",
"status": "active",
"group": [
{
"source": "urn:edf",
"target": "http://hl7.org/fhir/administrative-gender",
"element": [
{"code": "F", "target": [{"code": "female", "equivalence": "equivalent"}]},
{"code": "M", "target": [{"code": "male", "equivalence": "equivalent"}]},
],
}
],
}
def small_edf(
path: Path,
*,
patient_code="N1001",
sex="F",
birthdate=date(2025, 1, 5),
startdate=date(2026, 3, 2),
record_code="LAB-1",
seconds=20,
channels=("Fp1", "Fp2", "Cz"),
) -> bytes:
edf = edfio.Edf(
[
edfio.EdfSignal(
np.random.default_rng(1).normal(0, 20, 100 * seconds),
sampling_frequency=100,
label=name,
)
for name in channels
],
patient=edfio.Patient(code=patient_code, sex=sex, birthdate=birthdate),
recording=edfio.Recording(startdate=startdate, hospital_administration_code=record_code),
)
edf.write(path)
return path.read_bytes()
def hospital(path: Path) -> str:
with sqlite3.connect(path) as con:
con.execute("create table pacientes (record_number text primary key, birth_date text)")
con.executemany("insert into pacientes values (?, ?)",
[("N1001", "2025-01-05"), ("N1002", "2025-02-05")]) # fmt: skip
return f"sqlite:///{path}"
def pipeline(hospital_url: str, bucket_url: str) -> dict:
return {"nodes": [
{"id": "patients", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
"args": {"credentials": hospital_url, "table": "pacientes"}},
{"id": "patients_identity", "kind": "map", "inputs": ["patients"],
"fields": {"record_number": "record_number", "birth_date": "birth_date"},
"formats": {"birth_date": "%Y-%m-%d"}},
{"id": "uploads", "kind": "source", "source": "dlt.sources.filesystem:filesystem",
"args": {"bucket_url": bucket_url, "file_glob": "*.edf"},
"then": "persistance.readers:read_bytes"},
{"id": "header", "kind": "edf", "inputs": ["uploads"], "column": "content"},
{"id": "uploads_identity", "kind": "map", "inputs": ["header"], "concept_map": "edf_sex",
"fields": {"record_number": "edf_patient_code", "birth_date": "edf_birth_date",
"sex": "edf_sex"}, "formats": {"birth_date": "%Y-%m-%d"}},
{"id": "eegs", "kind": "map", "inputs": ["header"],
"fields": {"study_date": "edf_study_date", "lab_record_id": "edf_record_code",
"edf": "content"}, "formats": {"study_date": "%Y-%m-%d"}},
{"id": "people", "kind": "link", "inputs": ["patients_identity", "uploads_identity"]},
{"id": "target", "kind": "target", "inputs": ["eegs", "people"], "entity": "eeg"},
]} # fmt: skip
+215
View File
@@ -0,0 +1,215 @@
import hashlib
import io
import json
import zipfile
import mlflow
import pandas as pd
import pytest
from core.domains import Domain, part
from persistance import bundle, config, registry
DOMAIN = Domain.TEA
NAME = "tea.curve_x"
class Model(mlflow.pyfunc.PythonModel):
def __init__(self, value):
self.value = value
def predict(self, context, model_input: pd.DataFrame, params=None):
return model_input.assign(score=self.value)
@pytest.fixture
def stores(tmp_path, monkeypatch):
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
def use(name):
path = tmp_path / name
path.mkdir(exist_ok=True)
monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{path}/a.db")
monkeypatch.chdir(path)
use("a")
return use
def _register(value=1, clinical=True):
version = registry.register(
NAME,
Model(value),
{"scenario": "curve"},
{"n_reference": 10},
{"technical_validation": {"a": 1}, "interpretability": {"b": 2}},
tags={"source": "test", "bundle.source_version": "stale"},
)
if clinical:
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
return version
def _trust(data):
sha = hashlib.sha256(data).hexdigest()
with bundle.trusted_file().open("a") as file:
file.write(f"\n# approved\n {sha.upper()} \n")
return sha
def _entries(data):
with zipfile.ZipFile(io.BytesIO(data)) as archive:
return {name: archive.read(name) for name in archive.namelist()}
def _zip(entries):
stream = io.BytesIO()
with zipfile.ZipFile(stream, "w") as archive:
for name, data in entries.items():
archive.writestr(name, data)
return stream.getvalue()
def test_export_is_deterministic(stores):
registry.promote(NAME, _register())
first, second = bundle.export(DOMAIN), bundle.export(DOMAIN)
assert first.data == second.data
assert first.sha256 == second.sha256 == hashlib.sha256(first.data).hexdigest()
with zipfile.ZipFile(io.BytesIO(first.data)) as archive:
assert archive.namelist() == sorted(archive.namelist())
for info in archive.infolist():
assert info.date_time == bundle.EPOCH
assert info.compress_type == zipfile.ZIP_DEFLATED
assert info.external_attr == 0o644 << 16
assert info.create_system == 3
def test_layout_and_manifest_hold_every_file_hash(stores):
_register()
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
manifest = json.loads(entries.pop("manifest.json"))
assert (manifest["format"], manifest["domain"]) == (1, "tea")
(item,) = manifest["versions"]
assert (item["name"], item["version"]) == (NAME, 1)
prefix = "models/tea.curve_x/v1/"
assert prefix + "meta.json" in entries
assert prefix + "model/MLmodel" in entries
assert prefix + "reports/clinical_validation.txt" in entries
assert item["files"] == {key: hashlib.sha256(data).hexdigest() for key, data in entries.items()}
meta = json.loads(entries.pop(prefix + "meta.json"))
content = {key.removeprefix(prefix): data for key, data in entries.items()}
assert meta["content_sha256"] == item["content_sha256"] == bundle.content_sha256(content)
def test_selection_champion_latest_all(stores):
for value in (1, 2, 3):
_register(value)
with pytest.raises(bundle.Empty, match="nothing to export"):
bundle.export(DOMAIN)
registry.promote(NAME, 2)
assert bundle.export(DOMAIN).versions == [(NAME, 2)]
assert bundle.export(DOMAIN, ["curve_x"], "latest").versions == [(NAME, 3)]
assert bundle.export(DOMAIN, versions="all").versions == [(NAME, 1), (NAME, 2), (NAME, 3)]
with pytest.raises(bundle.BundleError, match="no tea model missing"):
bundle.export(DOMAIN, ["missing"])
@pytest.mark.parametrize("clinical", [True, False])
def test_roundtrip_registers_candidates_with_lineage(stores, clinical):
_register()
source_version = _register(2, clinical=clinical)
source = registry.snapshot(NAME, source_version)
inputs = pd.DataFrame({"value": [0]})
prediction = mlflow.pyfunc.load_model(f"models:/{NAME}/{source_version}").predict(inputs)
exported = bundle.export(DOMAIN, versions="latest")
stores("b")
_trust(exported.data)
assert bundle.import_(DOMAIN, exported.data) == bundle.Imported(
exported.sha256, [(NAME, 1)], []
)
target = registry.snapshot(NAME, 1)
pd.testing.assert_frame_equal(
mlflow.pyfunc.load_model(f"models:/{NAME}/1").predict(inputs),
prediction,
)
assert target.params == source.params
assert target.metrics == source.metrics
assert target.reports == source.reports
assert target.tags == {
"source": "test",
"bundle.sha256": exported.sha256,
"bundle.source_name": NAME,
"bundle.source_version": "2",
"bundle.content_sha256": json.loads(_entries(exported.data)["manifest.json"])["versions"][
0
]["content_sha256"],
}
assert registry.champion_version(NAME) is None
if clinical:
registry.promote(NAME, 1)
assert registry.champion_version(NAME) == 1
else:
with pytest.raises(registry.MissingReports, match="clinical_validation"):
registry.promote(NAME, 1)
def test_importing_twice_is_a_conflict_and_partial_imports_skip(stores):
_register()
single = bundle.export(DOMAIN, versions="latest")
_register(2)
both = bundle.export(DOMAIN, versions="all")
stores("b")
_trust(single.data)
_trust(both.data)
assert bundle.import_(DOMAIN, single.data).imported == [(NAME, 1)]
with pytest.raises(bundle.Conflict, match="every version is already registered"):
bundle.import_(DOMAIN, single.data)
result = bundle.import_(DOMAIN, both.data)
assert result.imported == [(NAME, 2)]
assert result.skipped == [(NAME, 1)]
def test_tampered_bundles_are_refused(stores):
_register()
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
path = "models/tea.curve_x/v1/model/MLmodel"
manifest = json.loads(entries["manifest.json"])
def with_manifest(**fields):
return entries | {"manifest.json": json.dumps(manifest | fields).encode()}
cases = [
(_zip(entries | {path: entries[path][:-1] + b"!"}), "content does not match the manifest"),
(_zip(entries | {"extra": b""}), "files in the bundle do not match the manifest"),
(_zip({k: v for k, v in entries.items() if k != path}), "files in the bundle do not match"),
(_zip(entries | {"../x": b""}), r"unsafe bundle path: \.\./x"),
(_zip(with_manifest(format=2)), "bundle format 2, this platform reads 1"),
(_zip(with_manifest(domain="cacu")), "bundle is for cacu, not tea"),
(b"hello", "not a bundle"),
]
for data, message in cases:
_trust(data)
with pytest.raises(bundle.BundleError, match=message):
bundle.import_(DOMAIN, data)
def test_guard_runs_on_export_and_on_import(stores, monkeypatch):
_register()
hook = part(DOMAIN, "bundle")
monkeypatch.setattr(hook, "guard", lambda version: [])
exported = bundle.export(DOMAIN, versions="latest")
_trust(exported.data)
monkeypatch.setattr(hook, "guard", lambda version: ["problem"])
for operation in (
lambda: bundle.export(DOMAIN, versions="latest"),
lambda: bundle.import_(DOMAIN, exported.data),
):
with pytest.raises(bundle.BundleError, match=r"tea\.curve_x v1: problem"):
operation()
def test_import_refuses_an_untrusted_digest(stores):
_register()
exported = bundle.export(DOMAIN, versions="latest")
with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"):
bundle.import_(DOMAIN, exported.data)
+125
View File
@@ -0,0 +1,125 @@
"""The CaCu models compute what the current ones compute: fed the timelines the current
platform built for its cohorts (the reference fixtures, in its codes), each rewritten model
gives the current model's predictions.
Fixed on purpose, so left out of the comparison:
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
(1970-01-01 for everyone); the rewrite returns the index sample's date.
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
RTOL = 1e-6 # as captured (models.json)
# The current platform's cohort cutoff, where the logistic model's follow-up ends.
REFERENCE_CUTOFF = "2026-11-23"
TYPES = {
"citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv",
"vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy",
"orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history",
"diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth",
"defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order",
} # fmt: skip
CODES = {
"bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"},
"biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"},
"hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"},
"cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"},
}
COHORTS = {
"cacu_cohort_surveillance": "cohorte_vigilancia",
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
}
def timelines(cohort: str) -> pd.DataFrame:
"""A reference cohort's timelines in the platform's names and codes."""
found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet")
found = found.rename(columns={
"pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type",
"valor_codigo": "value_code", "valor_numerico": "value_num",
"fuente_tabla": "source_table", "fuente_id": "source_id",
}) # fmt: skip
found["type"] = found["type"].map(TYPES)
for kind, codes in CODES.items():
rows = found["type"] == kind
found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes)
return found
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name):
spec = MODELS[name]
events = timelines(COHORTS[spec.cohort])
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"]
assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"]
found = spec.predict(model, events)
both = found.merge(
reference,
left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"],
how="outer",
indicator=True,
)
assert (both["_merge"] == "both").all(), "the same patients and horizons are scored"
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
if theirs in both:
np.testing.assert_allclose(both[ours], both[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():
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
that fixed); out: no birth date, a death by the biopsy."""
spec = MODELS["survival"]
events = timelines("cohorte_total").drop(columns="index_date")
events["date"] = pd.to_datetime(events["date"])
events["record_number"] = "CACU" + events["person_id"].astype(str).str.zfill(4)
cases = events[(events["type"] == "biopsy") & events["value_code"].isin(["CIS", "carcinoma"])]
index = cases.groupby("person_id")["date"].min().rename("index_date")
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
born = set(events.loc[events["type"] == "birth", "person_id"])
died = events[events["type"] == "death"].groupby("person_id")["date"].min()
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
events = events.merge(index, left_on="person_id", right_index=True)
model, metrics, _ = 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)
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
assert len(both) == len(reference) == len(found)
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch):
"""A site with no colposcopies has nobody in the post-colposcopy cohort: training that
model says so (and the train job goes on with the others) instead of failing inside it."""
from models import jobs
from models.cacu.jobs import JOBS
monkeypatch.setattr(jobs.gold, "timelines", lambda *a: pd.DataFrame())
with pytest.raises(jobs.EmptyCohort, match="cacu_cohort_post_colposcopy"):
JOBS.train("cin2_pim_post_colposcopy")
+49
View File
@@ -0,0 +1,49 @@
"""CaMa's models give the current platform's predictions on its own cohort (the reference
fixtures), read in the platform's timeline shape."""
import json
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama"
TRAINED_ON = "2026-11-24" # the day the reference was trained: its follow-up ends there
TYPES = {"nacimiento": "birth", "defuncion": "death", "biopsia": "biopsy"}
CODES = {"CARCINOMA_INVASOR": "invasive", "CARCINOMA_IN_SITU": "in_situ", "BENIGNO": "benign"}
def _timelines() -> pd.DataFrame:
"""The reference cohort's members (first invasive biopsy report in the window) with their
events, as gold.cama_events gives them."""
old = pd.read_parquet(REFERENCE / "cohorts" / "cama" / "cohorte_total" / "dbt" / "1.parquet")
old = old[old["tipo"].isin(TYPES)]
events = pd.DataFrame({
"person_id": old["pac_id"].astype(str), "date": pd.to_datetime(old["fecha"]),
"type": old["tipo"].map(TYPES), "value_code": old["valor_codigo"].map(CODES),
"value_num": old["valor_numerico"], "source_table": old["fuente_tabla"],
"source_id": old["fuente_id"],
"record_number": "CAMA" + old["pac_id"].astype(str).str.zfill(4),
}) # fmt: skip
invasive = events[(events["type"] == "biopsy") & (events["value_code"] == "invasive")]
index = invasive.groupby("person_id")["date"].min().rename("index_date")
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
return events.merge(index, left_on="person_id", right_index=True)
def test_survival_matches_the_current_model():
spec = MODELS["survival"]
events = _timelines()
model, metrics, _ = spec.train(events, pd.Timestamp(TRAINED_ON).date())
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
for name in ("n_train", "n_test", "stack_w_lr_6m", "stack_w_lr_12m", "stack_w_lr_18m"):
assert metrics[name] == current["metrics"][name], name
ours = spec.predict(model, events)
ref = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
ref = ref.assign(person_id=ref["pac_id"].astype(str), horizon_years=ref["horizonte_anios"])
both = ours.merge(ref, on=["person_id", "horizon_years"], validate="1:1")
assert len(both) == len(ref) == len(ours)
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
np.testing.assert_allclose(both["probability"], both["probabilidad"], rtol=1e-6)
-27
View File
@@ -1,27 +0,0 @@
"""`models` reads through Persistance's Repository, the same path WebApi
uses, against a temporary SQLite database."""
import pytest
def test_dataset_pages_through_every_row(cacu_db):
from datetime import date
from core.cacu.models import Paciente
from models.cacu import CaCuModel
model = CaCuModel()
repository = model.repository("paciente")
for i in range(7):
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
rows = list(model.dataset("paciente", batch_size=3))
assert [r["pac_id_hospital"] for r in rows] == [f"M-{i}" for i in range(7)]
assert list(model.dataset("paciente", pac_id_hospital="M-3"))[0]["pac_sexo"] == "Femenino"
def test_unknown_entity_is_a_clear_error():
from models.tea import TeaModel
with pytest.raises(ValueError, match="no nope_repository"):
TeaModel().repository("nope")
+50
View File
@@ -0,0 +1,50 @@
from datetime import date
import pytest
from edf_files import small_edf
from models.tea.eeg.read import FileNotValid, Header, _kept, header
def test_header_reads_the_facts(tmp_path):
data = small_edf(tmp_path / "a.edf")
assert header(data) == Header(
"N1001", "F", date(2025, 1, 5), date(2026, 3, 2), "LAB-1", 20.0, 3
)
def test_placeholders_are_none(tmp_path):
data = small_edf(
tmp_path / "a.edf", patient_code="X", sex="X", birthdate=None,
startdate=date(1985, 1, 1), record_code="X",
) # fmt: skip
assert header(data) == Header(None, None, None, None, None, 20.0, 3)
def test_header_does_not_read_the_signal(tmp_path):
data = small_edf(tmp_path / "a.edf")
truncated = data[: int(data[184:192])]
assert header(truncated) == header(data)
assert header(truncated).duration_s == 20.0
with pytest.warns(UserWarning, match="Updating header"):
with pytest.raises(FileNotValid, match="truncated"):
_kept(truncated)
def test_zero_signal_header_is_valid(tmp_path):
data = small_edf(tmp_path / "a.edf")
zero = data[:184] + b"256 " + data[192:252] + b"0 "
assert header(zero).channels == 0
with pytest.raises(FileNotValid, match="ZeroDivisionError"):
_kept(zero)
@pytest.mark.parametrize("data", [b"", b"x" * 100, b"x" * 300])
def test_not_an_edf_is_not_valid(data):
with pytest.raises(FileNotValid):
header(data)
def test_kept_channels_are_unchanged(tmp_path):
data = small_edf(tmp_path / "a.edf")
assert _kept(data) == [("Fp1", "Fp1"), ("Fp2", "Fp2"), ("Cz", "Cz")]
+54
View File
@@ -0,0 +1,54 @@
import json
from datetime import date
from hashlib import sha256
from edf_files import SEX_MAP, hospital, pipeline, small_edf
def test_edf_pipeline_keeps_and_links_the_files(platform, tmp_path):
hospital_url = hospital(tmp_path / "hospital.db")
uploads = tmp_path / "uploads"
uploads.mkdir()
a = small_edf(uploads / "a.edf")
b = small_edf(uploads / "b.edf", patient_code="N1002", birthdate=date(2025, 2, 5))
bad = b"junk"
(uploads / "bad.edf").write_bytes(bad)
clean = {sha256(a).hexdigest(): a, sha256(b).hexdigest(): b}
bad_hash = sha256(bad).hexdigest()
drawing = tmp_path / "edf.json"
drawing.write_text(json.dumps(pipeline(hospital_url, str(uploads))))
concepts = tmp_path / "sex.json"
concepts.write_text(json.dumps(SEX_MAP))
platform.save("concept_maps", "edf_sex", concepts)
platform.save("pipelines", "edf", drawing)
for _ in range(2):
platform.ingest("edf")
people = dict(
platform.query(
"select i.value, p.person_id from silver.person p "
"join silver.person_identifier i on i.person_id = p.person_id"
)
)
assert set(people) == {"N1001", "N1002"}
studies = platform.query("select person_id, study_date, lab_record_id, edf from silver.eeg")
assert {(p, str(d), lab, key) for p, d, lab, key in studies} == {
(people["N1001"], "2026-03-02", "LAB-1", sha256(a).hexdigest()),
(people["N1002"], "2026-03-02", "LAB-1", sha256(b).hexdigest()),
}
assert len(studies) == 2
assert {
key: bytes(value)
for key, value in platform.query("select key, content from bronze.files")
} == {**clean, bad_hash: bad}
assert platform.count("bronze.n__edf__header") == 3
((error, *fields),) = platform.query(
"select edf_error, edf_patient_code, edf_sex, edf_birth_date, edf_study_date, "
"edf_record_code, edf_duration_s, edf_channels from bronze.n__edf__header "
f"where content = '{bad_hash}'"
)
assert error and fields == [None] * 7
((study, reasons),) = platform.query("select study, _held from bronze.staged__held")
assert study == "eeg"
assert any(reason.startswith("study_date:") for reason in json.loads(reasons))
+60
View File
@@ -0,0 +1,60 @@
import time
import pytest
from edf_files import SEX_MAP, hospital, pipeline, small_edf
def _ok(response):
assert response.status_code == 200, response.text
return response.json()
def wait_for(api, run_id: str, seconds: int = 900) -> None:
deadline = time.monotonic() + seconds
while (state := _ok(api.get(f"/runs/{run_id}"))["state"]) in ("queued", "running"):
assert time.monotonic() < deadline, f"run {run_id} still {state}"
time.sleep(2)
assert state == "succeeded"
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
def test_an_uploaded_edf_is_analysed_by_itself(api, tmp_path):
hospital_url = hospital(tmp_path / "hospital.db")
data = small_edf(tmp_path / "a.edf")
def upload():
result = _ok(api.post("/ingest/uploads", files={"file": ("a.edf", data)}))
assert set(result) == {"bucket_url", "file_name"}
assert result["file_name"] == "a.edf"
return result["bucket_url"]
def run():
wait_for(api, _ok(api.post("/ingest/pipelines/edf/runs", json={}))["run_id"])
def runs():
return _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))
bucket_url = upload()
_ok(api.put("/ingest/concept-maps/edf_sex", json=SEX_MAP))
_ok(api.put("/ingest/pipelines/edf", json=pipeline(hospital_url, bucket_url)))
run()
deadline = time.monotonic() + 600
found = runs()
while not any(item["state"] == "succeeded" for item in found):
assert time.monotonic() < deadline, found
time.sleep(2)
found = runs()
(first,) = found
(study,) = _ok(api.get("/tea/eegs"))
assert study["study_date"] == "2026-03-02"
assert study["lab_record_id"] == "LAB-1"
assert study["analysed"] is True
assert upload() == bucket_url
run()
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
assert [item["id"] for item in runs()] == [first["id"]]
time.sleep(2)
assert [item["id"] for item in runs()] == [first["id"]]
+342
View File
@@ -0,0 +1,342 @@
"""The rewritten TEA EEG analysis computes what the current one computes: for every hospital
EEG with an EDF, the same verdict, checks, metric values and per-electrode / per-zone values
(the reference tables, in the current platform's codes); and age baselines trained on our own
features of the HK1K reference cohort score each EEG as the current registered baselines did
(z, outside, p5, median, p95 of each metric, z of each electrode and zone).
Tolerance: RTOL = 1e-9 relative (absolute below 1). Values are compared after the reference's
own storage (floats as captured); counts, texts, flags and levels exactly. The report at the
end of each test says how many compared fields are bit-identical.
Needs the hospital database (`~/isssteleon-data/hospital_tea.db`), and for the curves the
Helsinki EDFs (`/mnt/drive/eeg-helsinki`) unless their features are cached
(`~/isssteleon-data/cache/eeg_hk1k_features.json`; `EEG_REBUILD_REFERENCE=1` measures the 223
studies again: 10-20 min on 4 workers). The 78 hospital EEGs take about 40 s on 4 workers.
"""
import json
import os
import sqlite3
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import get_context
from pathlib import Path
import pandas as pd
import pytest
pytest.importorskip("mne")
pytest.importorskip("edfio")
from models.tea.eeg import curves, reference # noqa: E402
from models.tea.eeg.analysis import analyze # noqa: E402
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "tea"
DATA = Path.home() / "isssteleon-data"
HOSPITAL = DATA / "hospital_tea.db"
HELSINKI = Path("/mnt/drive/eeg-helsinki")
CACHE = DATA / "cache" / "eeg_hk1k_features.json"
OLD_FEATURES = DATA / "specs" / "eeg" / "hk1k_features.json" # only to check our own features
RTOL = 1e-9
WORKERS = 4
pytestmark = pytest.mark.skipif(not HOSPITAL.exists(), reason="no hospital database")
CODES = {
"RITMO_POSTERIOR": "posterior_rhythm",
"HUSOS_SUENO_N2": "spindles_n2",
"HUSOS_SUENO_N3": "spindles_n3",
"PICOS_PAROXISTICOS": "paroxysmal_spikes",
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient",
}
LEVELS = {
"completo": "complete",
"sin_referencia_auricular": "no_ear_reference",
"parcial": "partial",
"no_analizable": "not_analyzable",
}
ZONES = {
"frontal_izq": "frontal_left",
"frontal_der": "frontal_right",
"frontal_media": "frontal_midline",
"temporal_izq": "temporal_left",
"temporal_der": "temporal_right",
}
# The current platform's features of the HK1K studies, by our scenario's feature names.
OLD_SCENARIOS = {
"eeg-posterior-rhythm": ("posterior_rhythm|", {"value": "posterior_rhythm_hz"}),
"eeg-gradient": ("gradient|", {"value": "gradient_delta_sueno"}),
"eeg-spikes": (
"spikes|",
{
"value": "spike_rate_nrem",
"minutes": "spike_minutes_nrem",
"electrode_": "spike_density_nrem_",
"zone_": "spike_zone_rate_nrem_",
},
),
**{
f"eeg-spindles-{s}": (
f"spindles|{s.upper()}",
{"value": "spindle_density_per_min_channel", "zone_": "spindle_zone_"},
)
for s in ("n2", "n3")
},
**{
f"eeg-spindle-topography-{s}": (
f"spindle_topography|{s.upper()}",
{"electrode_": "topo_enh_"},
)
for s in ("n2", "n3")
},
}
class Tally:
"""Compared fields: bit-identical, within RTOL, and the mismatches."""
def __init__(self):
self.exact, self.close, self.wrong = 0, 0, []
def __call__(self, where, ours, theirs):
if isinstance(ours, bool):
ours = int(ours)
if ours is None or theirs is None or isinstance(ours, str) or isinstance(theirs, str):
ok = ours == theirs
self.exact += ok
else:
a, b = float(ours), float(theirs)
ok = a == b or abs(a - b) <= RTOL * max(1.0, abs(a), abs(b))
self.exact += a == b
self.close += ok and a != b
if not ok:
self.wrong.append((where, ours, theirs))
def report(self, name):
total = self.exact + self.close + len(self.wrong)
print(
f"{name}: {total} fields, {self.exact} identical, {self.close} within {RTOL:g}, "
f"{len(self.wrong)} different"
)
def _table(name):
return json.loads((FIXTURES / "tables" / f"{name}.json").read_text())
def _edfs():
with sqlite3.connect(f"file:{HOSPITAL}?mode=ro", uri=True) as con:
rows = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
return {key: bytes(edf) for key, edf in rows}
def _analysed(key_edf):
key, edf = key_edf
return key, analyze(edf)
@pytest.fixture(scope="module")
def analyses():
edfs = _edfs()
with ProcessPoolExecutor(WORKERS, mp_context=get_context("spawn")) as pool:
return dict(pool.map(_analysed, [(k, edfs[k]) for k in sorted(edfs)]))
def test_verdicts_and_checks(analyses):
eeg = {r["eeg_id"]: r for r in _table("eeg")}
criteria = _table("eeg_criterio")
tally = Tally()
for key, a in analyses.items():
ref = eeg[key]
assert a.error is None, (key, a.error)
pairs = {
"eeg_valido": a.valid,
"eeg_nivel": a.level,
"eeg_edad_meses": a.age_months,
"eeg_fraccion_limpia": a.clean_fraction,
"eeg_canales_malos": a.bad_channels,
"eeg_canales": a.channels,
"eeg_duracion_min": a.duration_min,
"eeg_ruido_linea_db": a.line_noise_db,
"eeg_con_sueno": a.sleep,
"eeg_error": a.error,
}
for field, ours in pairs.items():
theirs = LEVELS[ref[field]] if field == "eeg_nivel" else ref[field]
tally((key, field), ours, theirs)
theirs = sorted(
(
(
r["cri_codigo"],
r["cri_electrodo"] or "",
r["cri_valor"],
LEVELS.get(r["cri_valor_texto"], r["cri_valor_texto"]),
r["cri_unidad"],
r["cri_bajo"],
r["cri_alto"],
r["cri_decisivo"],
r["cri_anormal"],
)
for r in criteria
if r["cri_eeg_id"] == key
),
key=lambda t: (t[0], t[1], str(t[3])),
)
ours = sorted(
(
(
c["code"],
c["electrode"] or "",
c["value"],
c["text"],
c["unit"],
c["low"],
c["high"],
c["decisive"],
c["abnormal"],
)
for c in a.checks
),
key=lambda t: (t[0], t[1], str(t[3])),
)
tally((key, "checks"), len(ours), len(theirs))
for o, t in zip(ours, theirs, strict=False):
for name, x, y in zip(
(
"code",
"electrode",
"value",
"text",
"unit",
"low",
"high",
"decisive",
"abnormal",
),
o,
t,
strict=True,
):
tally((key, o[0], o[1], name), x, y)
tally.report("eeg + eeg_criterio")
assert not tally.wrong, tally.wrong[:20]
def _reference_metrics():
"""(eeg, our code) -> (metric row, {electrode: row}, {our zone: row})."""
electrodes, zones = {}, {}
for r in _table("eeg_metrica_electrodo"):
electrodes.setdefault(r["mel_met_id"], {})[r["mel_electrodo"]] = r
for r in _table("eeg_metrica_zona"):
zones.setdefault(r["mez_met_id"], {})[ZONES.get(r["mez_zona"], r["mez_zona"])] = r
return {
(r["met_eeg_id"], CODES[r["met_codigo"]]): (
r,
electrodes.get(r["met_id"], {}),
zones.get(r["met_id"], {}),
)
for r in _table("eeg_metrica")
}
def test_metric_values(analyses):
reference_rows = _reference_metrics()
tally = Tally()
for key, a in analyses.items():
expected = sorted(code for k, code in reference_rows if k == key)
tally((key, "metrics"), ",".join(sorted(m.code for m in a.metrics)), ",".join(expected))
for m in a.metrics:
row, electrodes, zones = reference_rows[key, m.code]
tally((key, m.code), m.value, row["met_valor"])
tally(
(key, m.code, "electrodes"),
",".join(sorted(m.electrodes)),
",".join(sorted(electrodes)),
)
tally((key, m.code, "zones"), ",".join(sorted(m.zones)), ",".join(sorted(zones)))
for e, v in m.electrodes.items():
tally((key, m.code, e), v, electrodes[e]["mel_valor"])
for z, v in m.zones.items():
tally((key, m.code, z), v, zones[z]["mez_valor"])
tally.report("eeg_metrica + electrodes + zones, values")
assert not tally.wrong, tally.wrong[:20]
def _measure_reference():
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
measured = reference.measure(studies, WORKERS)
CACHE.parent.mkdir(parents=True, exist_ok=True)
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
return measured
@pytest.fixture(scope="module")
def hk1k():
if CACHE.exists() and os.environ.get("EEG_REBUILD_REFERENCE") != "1":
return json.loads(CACHE.read_text())["studies"]
if not HELSINKI.exists():
pytest.skip("no cached HK1K features and no Helsinki EDFs")
return _measure_reference()
def _old_feature(feature: str, names: dict[str, str]) -> str:
"""`electrode_Fp1` -> `topo_enh_Fp1`, `zone_frontal_left` -> `spindle_zone_frontal_izq`."""
if feature in names:
return names[feature]
prefix, rest = feature.split("_", 1)
return names[prefix + "_"] + {ours: old for old, ours in ZONES.items()}.get(rest, rest)
def test_reference_features(hk1k):
"""Our HK1K features are the current platform's (as it measured them for its baselines)."""
if not OLD_FEATURES.exists():
pytest.skip("no captured HK1K features")
old = {s["key"]: s for s in json.loads(OLD_FEATURES.read_text())["studies"]}
tally = Tally()
assert len(hk1k) == len(old) == 223
for study in hk1k:
theirs = old[study["key"]]
tally((study["key"], "age"), study["age_months"], theirs["age_months"])
tally((study["key"], "valid"), study["valid"], theirs["valid"])
for scenario, (old_name, names) in OLD_SCENARIOS.items():
for feature, v in study["features"][scenario].items():
old_feature = _old_feature(feature, names)
tally((study["key"], feature), v, theirs["features"][old_name][old_feature])
tally.report("HK1K features")
assert not tally.wrong, tally.wrong[:20]
def test_curves(analyses, hk1k):
"""Baselines trained on our HK1K features score each EEG as the registered ones did."""
tables = reference.tables(hk1k)
assert all(len(t) == 223 for t in tables.values())
models = {name: curves.train(table, name) for name, table in tables.items()}
json.dumps(models, allow_nan=False) # plain JSON, as MLflow logs it
reference_rows = _reference_metrics()
tally = Tally()
for key, a in analyses.items():
for code, scored in curves.deviations(models, a).items():
row, electrodes, zones = reference_rows[key, code]
value = scored["value"]
for ours, theirs in (
("z", "met_z"),
("outside", "met_fuera"),
("p5", "met_p5"),
("median", "met_mediana"),
("p95", "met_p95"),
):
tally((key, code, ours), value[ours], row[theirs])
for e, s in scored.get("electrodes", {}).items():
tally((key, code, e, "z"), s["z"], electrodes[e]["mel_z"])
for z, s in scored.get("zones", {}).items():
tally((key, code, z, "z"), s["z"], zones[z]["mez_z"])
tally.report("eeg_metrica z/outside/p5/median/p95 + electrode and zone z")
assert not tally.wrong, tally.wrong[:20]
def test_score_without_value_or_coverage():
"""No value, or an age the curve doesn't cover (too few studies anywhere): all None."""
table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]})
baseline = curves.train(table, "eeg-gradient")["value"]
empty = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
assert curves.score(baseline, None, 25.0) == empty
assert curves.score(baseline, 2.0, 25.0) == empty
+380
View File
@@ -0,0 +1,380 @@
"""`execution.map` returns the same list in every mode, spreads lazy input without loading it
all, fails fast when the cluster is wrong, cleans up after a cancel, and reports progress on
the Dagster run. Remote tests need a scheduler: set `DASK_TEST_SCHEDULER` and
`DASK_EXPECTED_WORKERS` (the compose `test` profile does)."""
import json
import os
import signal
import subprocess
import sys
import textwrap
import threading
import time
from types import SimpleNamespace
import cloudpickle
import dagster as dg
import numpy as np
import psutil
import pytest
from models import execution
from models.execution import Execution, ExecutionError, Progress
from persistance import cluster
cloudpickle.register_pickle_by_value(sys.modules[__name__])
def by_value(fn):
"""Mark a worker function so that Dask ships its code, not its name: the scheduler
unpickles task graphs too, and has no test module (Dask wraps `fn` in a task, which
hides the by-value registration above from it)."""
fn.__module__ = "__main__"
return fn
@by_value
def square(x):
return int(x) ** 2
@by_value
def numeric(x):
rng = np.random.default_rng(x)
return float(np.linalg.norm(rng.normal(size=(20, 20)) @ rng.normal(size=(20, 20))))
@by_value
def slow(x):
time.sleep(0.2)
return x
@by_value
def sleep_forever(x):
time.sleep(60)
@by_value
def fail_on_three(x):
if x == 3:
raise RuntimeError("three")
return x
@pytest.fixture(autouse=True)
def env(monkeypatch):
for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"):
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("DASK_LOCAL_WORKERS", "2")
def fake_context():
context = SimpleNamespace(run_id="r1", logs=[], tags=[], metadata=[])
context.log = SimpleNamespace(info=context.logs.append)
context.instance = SimpleNamespace(add_run_tags=lambda run, tags: context.tags.append(tags))
context.add_output_metadata = context.metadata.append
return context
def test_resolve_defaults_and_allow_list(monkeypatch):
assert execution.resolve().mode == "local"
monkeypatch.setenv("EXECUTION_MODE", "sync")
assert execution.resolve().mode == "sync"
with pytest.raises(ExecutionError):
execution.resolve(Execution(mode="remote"))
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786")
assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786"
assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == (
"tcp://b:8786"
)
assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"]
def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786")
with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"):
execution.resolve(Execution(mode="remote", scheduler="c:8786"))
with pytest.raises(ExecutionError, match="only goes with remote"):
execution.resolve(Execution(mode="local", scheduler="a:8786"))
with pytest.raises(ExecutionError, match="not host:port"):
cluster.normalize("http://a:1")
def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
lines = []
assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16]
assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5"
def test_map_empty_items_starts_nothing(monkeypatch):
import distributed
def boom(*a, **k):
raise AssertionError("a cluster was started")
monkeypatch.setattr(distributed, "LocalCluster", boom)
assert execution.map(square, []) == []
assert execution.map(square, iter([]), total=0) == []
def test_map_local_equals_sync(monkeypatch):
items = list(range(12))
monkeypatch.setenv("EXECUTION_MODE", "sync")
expected = execution.map(numeric, items, log=lambda s: None)
monkeypatch.setenv("EXECUTION_MODE", "local")
assert execution.map(numeric, items, log=lambda s: None) == expected
def test_map_lazy_items_are_not_all_loaded_at_once():
state = {"loaded": 0, "finished": 0, "peak": 0}
lock = threading.Lock()
def generate():
for i in range(30):
with lock:
state["loaded"] += 1
state["peak"] = max(state["peak"], state["loaded"] - state["finished"])
yield i
class Counting:
def __init__(self):
self.n = 0
out = []
real = execution._Monitor.item_done
def item_done(self):
with lock:
state["finished"] += 1
real(self)
execution._Monitor.item_done = item_done
try:
out = execution.map(slow, generate(), total=30, log=lambda s: None)
finally:
execution._Monitor.item_done = real
assert out == list(range(30))
assert state["peak"] <= max(4, 2 * 2)
@pytest.mark.parametrize("mode", ["sync", "local"])
def test_map_on_error_converts_a_failed_item(monkeypatch, mode):
monkeypatch.setenv("EXECUTION_MODE", mode)
out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None)
assert out == [0, 1, 2, -3, 4, 5]
@pytest.mark.parametrize("mode", ["sync", "local"])
def test_map_raises_without_on_error(monkeypatch, mode):
monkeypatch.setenv("EXECUTION_MODE", mode)
with pytest.raises(RuntimeError, match="three"):
execution.map(fail_on_three, range(6), log=lambda s: None)
def test_eta_smoothing_and_threshold():
eta = execution.Eta(alpha=0.3, min_done=3)
eta.update(0.0, 0)
eta.update(1.0, 2)
assert eta.eta_s(10) is None # fewer than 3 done
eta.update(2.0, 4)
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
eta.update(3.0, 8) # a faster burst: 4 items/s
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
def test_progress_tag_and_log_lines_inside_running(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
context = fake_context()
with execution.running(context):
execution.map(square, range(6), phase="analyzing")
first, last = (Progress.model_validate_json(t[execution.PROGRESS_TAG]) for t in
(context.tags[0], context.tags[-1])) # fmt: skip
assert first.done == 0 and last.done == last.total == 6 and last.phase == "analyzing"
assert context.logs[0] == "analyzing: 0/6" and context.logs[-1] == "analyzing: 6/6"
summary = context.metadata[-1]
assert set(summary) == {"mode", "scheduler", "phases", "peak_cpu_pct", "peak_memory_bytes"}
def test_no_tag_outside_running(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
context = fake_context()
execution.map(square, range(3), log=context.logs.append)
assert context.tags == [] and context.logs
def test_version_mismatch_fails_before_any_task(monkeypatch):
import distributed
monkeypatch.setenv("DASK_SCHEDULERS", "x:8786")
submitted = []
class SpyClient:
def __init__(self, *a, **k):
self.closed = False
def submit(self, *a, **k):
submitted.append(a)
def close(self):
self.closed = True
monkeypatch.setattr(distributed, "Client", SpyClient)
monkeypatch.setattr(cluster, "versions_error", lambda client: "numpy 1.0 vs 2.0")
with pytest.raises(execution.ClusterVersionError, match="numpy 1.0 vs 2.0"):
execution.map(square, range(3), execution=Execution(mode="remote"))
assert submitted == []
CANCEL_SCRIPT = textwrap.dedent(
"""
import signal, sys
from models import execution
from models.execution import Execution
def stop(*a):
raise KeyboardInterrupt
def sleep_forever(x):
import time
time.sleep(60)
signal.signal(signal.SIGTERM, stop)
import cloudpickle
cloudpickle.register_pickle_by_value(sys.modules["__main__"])
execution.map(sleep_forever, range({n}), log=lambda s: print(s, flush=True),
execution=Execution(mode="{mode}"))
"""
)
def run_cancelled(mode, n):
"""Start a `map` of sleepers in a subprocess, send SIGTERM after its first line."""
proc = subprocess.Popen(
[sys.executable, "-c", CANCEL_SCRIPT.format(n=n, mode=mode)],
stdout=subprocess.PIPE,
text=True,
env={**os.environ, "DASK_LOCAL_WORKERS": "2"},
)
assert proc.stdout.readline().startswith("working: 0/")
time.sleep(3) # the cluster is up and the tasks are submitted
return proc
def test_local_cancel_leaves_no_worker_processes():
proc = run_cancelled("local", 4)
children = psutil.Process(proc.pid).children(recursive=True)
assert children
proc.send_signal(signal.SIGTERM)
proc.wait(timeout=30)
deadline = time.time() + 20
while time.time() < deadline and any(c.is_running() and c.status() != "zombie"
for c in children): # fmt: skip
time.sleep(0.5)
assert not [c for c in children if c.is_running() and c.status() != "zombie"]
def test_health_sync_and_local(monkeypatch):
sync = execution.health(Execution(mode="sync"))
assert sync.reachable and sync.workers == 1 and sync.threads == 1
local = execution.health(Execution(mode="local"))
assert local.reachable and local.workers == 2 and local.versions_ok is None
def test_health_unreachable_remote(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
started = time.time()
h = execution.health(Execution(mode="remote"))
assert not h.reachable and h.error and time.time() - started < 15
def test_health_rejects_unlisted_scheduler(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
with pytest.raises(ExecutionError):
execution.health(Execution(mode="remote", scheduler="tcp://127.0.0.1:2"))
with pytest.raises(ExecutionError):
execution.health(Execution(mode="sync"), reference="../x")
def test_progress_reaches_the_dagster_run():
@dg.op
def analyze(context) -> dg.Nothing:
with execution.running(context, Execution(mode="sync")):
execution.map(square, range(6), phase="analyzing")
@dg.op(ins={"start": dg.In(dg.Nothing)})
def after(context):
pass
@dg.job
def two():
after(analyze())
instance = dg.DagsterInstance.ephemeral()
result = two.execute_in_process(instance=instance)
assert result.success
tags = instance.get_run_by_id(result.run_id).tags
progress = Progress.model_validate_json(tags[execution.PROGRESS_TAG])
assert (progress.done, progress.total, progress.phase) == (6, 6, "analyzing")
event = next(e for e in result.events_for_node("analyze") if e.is_successful_output)
assert "mode" in event.event_specific_data.metadata
@pytest.fixture(scope="module")
def scheduler():
address = os.environ.get("DASK_TEST_SCHEDULER")
if not address:
pytest.skip("DASK_TEST_SCHEDULER is not set")
expected = int(os.environ["DASK_EXPECTED_WORKERS"])
os.environ["DASK_SCHEDULERS"] = address
deadline = time.time() + 60
while time.time() < deadline:
if execution.health(Execution(mode="remote", scheduler=address)).workers == expected:
return cluster.normalize(address)
time.sleep(1)
pytest.fail(f"the scheduler never showed {expected} workers")
def test_map_remote_equals_sync(scheduler, monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
items = list(range(12))
expected = execution.map(numeric, items, execution=Execution(mode="sync"), log=print)
remote = execution.map(numeric, items, execution=Execution(mode="remote"), log=print)
assert remote == expected
def test_health_remote(scheduler, monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
h = execution.health(Execution(mode="remote"))
assert h.reachable and h.workers == h.expected_workers == 2
assert h.versions_ok and h.latency_ms > 0 and h.dashboard_ok
def test_remote_cancel_cancels_futures(scheduler, monkeypatch):
from distributed import Client
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
proc = run_cancelled("remote", 8)
proc.send_signal(signal.SIGTERM)
proc.wait(timeout=30)
with Client(scheduler, timeout=10) as client:
deadline = time.time() + 20
processing = None
while time.time() < deadline:
processing = client.run_on_scheduler(execution._counts).get("processing", 0)
if processing == 0:
break
time.sleep(0.5)
assert processing == 0
assert client.scheduler_info()["workers"]
def test_progress_json_is_stable(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
context = fake_context()
with execution.running(context):
execution.map(square, range(2))
assert json.loads(context.tags[-1][execution.PROGRESS_TAG])["mode"] == "sync"
-60
View File
@@ -1,60 +0,0 @@
import onnx
import onnx.helper
import pytest
from models.export import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes:
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
return model.SerializeToString()
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
path = tmp_path / "model.onnx"
path.write_bytes(_tiny_onnx_bytes())
metadata = inspect_onnx_metadata(path)
assert metadata["available"] is True
assert metadata["producer_name"] == "pytest-fixture"
assert metadata["graph_inputs"] == ["x"]
assert metadata["graph_outputs"] == ["y"]
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
"""A protobuf-valid but structurally broken graph (a node reading an
input the graph never declares) must be rejected: `onnx.load` alone
only parses the protobuf and would let this through."""
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "broken", [], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
path = tmp_path / "model.onnx"
path.write_bytes(model.SerializeToString())
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
inspect_onnx_metadata(path)
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "onnx":
raise ImportError("onnx not installed")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
path = tmp_path / "model.onnx"
path.write_bytes(b"irrelevant")
assert inspect_onnx_metadata(path) == {
"available": False,
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
}
+89
View File
@@ -0,0 +1,89 @@
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
the rules point at is read into text (scanned ones through OCR). The site: the synthetic
hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs)."""
import json
import re
import shutil
import sqlite3
from pathlib import Path
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict:
"""What an operator would draw for this site: one Source per table, and a Read on each
column that holds documents."""
def table(node_id, credentials, name, **args):
args = {"credentials": credentials, "table": name, **args}
return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args}
nodes = [
table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t)
for name, tables in hospital_tables.items()
for t in tables
]
return {
"nodes": nodes
+ [
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
]
}
SQL_TABLE = "dlt.sources.sql_database:sql_table"
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path):
count, query = platform.count, platform.query
tables = {}
for name in ("cacu", "cama"):
shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db")
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
found = con.execute("select name from sqlite_master where type = 'table'")
tables[name] = [t for (t,) in found]
truth = site.truth
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url)))
platform.save("pipelines", "site", tmp_path / "pipeline.json")
by_place = {}
for r in truth:
by_place.setdefault(r["where"].split(":")[0], []).append(r)
documents = len(truth)
expected = {"resultados": documents, "text": documents}
for name, names in tables.items():
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
for t in names:
expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0]
def counts():
return {node: count(f"bronze.n__site__{node}") for node in expected}
for _ in range(2): # loading the same site again changes nothing
platform.ingest()
assert counts() == expected
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
assert len(read_once) == documents # each file read once
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
platform.ingest()
assert counts() == expected
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
assert query(corrected) == [("64000",)]
space = re.compile(r"\s+")
for table in ("ResultadoSubrogado",):
read = query("select id, text, ocr, error from bronze.n__site__text")
assert [error for *_, error in read if error is not None] == []
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place[table]:
txt, ocr = by_id[int(r["where"].split(":")[1])]
assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans
if "record_number" in r["identity"]: # even scanned, the number reads back exactly
assert r["identity"]["record_number"] in txt, (r["where"], txt)
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
read_once
) # reruns never read a file again
-19
View File
@@ -1,19 +0,0 @@
import pytest
from models.cacu import CaCuModel
from models.cama import CaMaModel
from models.tea import TeaModel
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
def test_train_not_implemented(cls):
model = cls()
with pytest.raises(NotImplementedError):
model.train()
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
def test_predict_not_implemented(cls):
model = cls()
with pytest.raises(NotImplementedError):
model.predict(data=None)
-115
View File
@@ -1,115 +0,0 @@
from core.ocr import OcrEstatus
from models.ocr import (
CIT_VPH_COLUMNS,
OcrExtractionResult,
OcrExtractor,
run_pending_extractions,
)
class StubVphExtractor(OcrExtractor):
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
return OcrExtractionResult(
values={"resultado": "POSITIVO", "genotipo_16": 1, "genotipo_18": 0},
confianza=0.92,
estatus=OcrEstatus.REALIZADO,
requiere_revision=False,
metodo_principal="stub-v1",
)
class AlwaysFailsExtractor(OcrExtractor):
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
raise RuntimeError("boom")
def _make_cacu_citologia_repo():
from core.cacu.models import CitologiaCervical
from persistance.cacu import citologia_cervical_repository
return citologia_cervical_repository, CitologiaCervical
def test_run_pending_extractions_populates_result_and_metadata(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(
CitologiaCervical(
pac_id_hospital="H-1",
cit_vph_pdf_blob=b"%PDF-fake",
)
)
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
assert summary.processed == 1
assert summary.skipped_already_done == 0
row = repo.list()[0]
assert row.cit_vph_resultado == "POSITIVO"
assert row.cit_vph_genotipo_16 == 1
assert row.cit_vph_ocr_estatus == OcrEstatus.REALIZADO
assert row.cit_vph_ocr_requiere_revision is False
assert row.cit_vph_ocr_metodo_principal == "stub-v1"
def test_run_pending_extractions_is_idempotent(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
first = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
second = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
assert first.processed == 1
assert second.processed == 0
assert second.skipped_already_done == 1
def test_run_pending_extractions_persists_failure_instead_of_crashing(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, AlwaysFailsExtractor(), domain="cacu", entity="citologiacervical")
assert summary.failed == 1
row = repo.list()[0]
assert row.cit_vph_ocr_estatus == OcrEstatus.FALLIDO
assert row.cit_vph_ocr_requiere_revision is True
def test_run_pending_extractions_logs_to_governance(cacu_db, governance_db):
from persistance.governance import extraction_run_repository
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
run_pending_extractions(
repo,
CIT_VPH_COLUMNS,
StubVphExtractor(),
domain="cacu",
entity="citologiacervical",
governance_repository=extraction_run_repository,
source_description="HIS export 2026-09-01",
)
runs = extraction_run_repository.list()
assert len(runs) == 1
assert runs[0].domain == "cacu"
assert runs[0].source_description == "HIS export 2026-09-01"
def test_done_rows_do_not_use_up_the_batch(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
for n in range(3):
repo.create(CitologiaCervical(pac_id_hospital=f"H-{n}", cit_vph_pdf_blob=b"%PDF-fake",
cit_vph_ocr_estatus=OcrEstatus.REALIZADO.value))
repo.create(CitologiaCervical(pac_id_hospital="H-nuevo", cit_vph_pdf_blob=b"%PDF-fake"))
repo.create(CitologiaCervical(pac_id_hospital="H-sin-pdf"))
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu",
entity="citologiacervical", limit=1)
assert (summary.processed, summary.skipped_already_done) == (1, 3)
assert repo.list(pac_id_hospital="H-nuevo")[0].cit_vph_resultado == "POSITIVO"
assert repo.list(pac_id_hospital="H-sin-pdf")[0].cit_vph_ocr_estatus is None
-40
View File
@@ -1,40 +0,0 @@
from core.ocr import OcrEstatus
from extraction.testing import scanned_pdf, text_pdf
from models.ocr import CinGradoOcrExtractor, GradoHistologicoOcrExtractor, VphOcrExtractor
def test_cin_grade_from_narrative_diagnosis():
report = text_pdf(
[
[
"REPORTE DE ESTUDIO HISTOPATOLOGICO",
"Descripción microscópica: epitelio escamoso con atipia en el tercio inferior.",
"No se observa carcinoma invasor.",
"DIAGNÓSTICO:",
"Lesión intraepitelial escamosa de bajo grado (NIC I) asociada a VPH.",
]
]
)
result = CinGradoOcrExtractor().extract(report)
assert result.values == {"grado": "LIEBG"}
assert result.estatus is OcrEstatus.REALIZADO
def test_breast_histological_grade_prefers_in_situ_over_its_prefix():
report = text_pdf([["Diagnóstico: CARCINOMA DUCTAL IN SITU de alto grado nuclear."]])
assert GradoHistologicoOcrExtractor().extract(report).values == {"grado": "CARCINOMA_IN_SITU"}
def test_scanned_vph_report_uses_tesseract_and_reports_confidence():
report = scanned_pdf([["Resultado VPH: NEGATIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: NO DETECTADO"]])
result = VphOcrExtractor().extract(report)
assert result.values == {"resultado": "NEGATIVO", "genotipo_16": 0, "genotipo_18": 0}
assert result.metodo_principal.startswith("tesseract")
assert 0 < result.confianza <= 1
def test_missing_fields_require_review_and_empty_reports_fail():
partial = VphOcrExtractor().extract(text_pdf([["VPH alto riesgo: POSITIVO"]]))
assert partial.estatus is OcrEstatus.REALIZADO and partial.requiere_revision
empty = VphOcrExtractor().extract(text_pdf([["Hoja sin resultados de laboratorio"]]))
assert empty.estatus is OcrEstatus.FALLIDO and empty.requiere_revision
-80
View File
@@ -1,80 +0,0 @@
import json
import pytest
from models.base import ScreeningModel
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
from models.registry import registry
class StubModel(ScreeningModel):
domain = "cacu"
def train(self, data=None):
raise NotImplementedError
def predict(self, data):
return {"label": "positivo", "confianza": 0.73}
def never_applicable(row: dict) -> bool:
return False
def _promote_a_version(production_ready):
domain, scenario, version = production_ready("v1-prod")
return registry.promote(domain, scenario, version)
def test_predict_and_record_persists_prediction_tagged_with_active_version(production_ready):
version = _promote_a_version(production_ready)
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
prediction = service.predict_and_record(
{"edad": 40},
pac_id_hospital="H-1",
interpretability=Interpretability(odds_ratio=1.8),
)
assert prediction.mlflow_run_id == version.run_id
assert prediction.modelo_version == str(version.version)
assert prediction.applicability_passed is True
assert json.loads(prediction.output)["label"] == "positivo"
assert json.loads(prediction.interpretability)["odds_ratio"] == 1.8
def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
with pytest.raises(RuntimeError, match="no hay una versión en producción"):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
def test_applicability_gate_flags_but_does_not_block_by_default(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable
)
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
assert prediction.applicability_passed is False
def test_applicability_gate_can_reject_outright(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(),
domain="cacu",
scenario="tamizaje",
aplicable=never_applicable,
reject_inapplicable=True,
)
with pytest.raises(ApplicabilityRejected):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
def test_applicability_gate_needs_a_dict(production_ready):
_promote_a_version(production_ready)
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable)
with pytest.raises(TypeError):
service.predict_and_record([40], pac_id_hospital="H-1")
+282
View File
@@ -0,0 +1,282 @@
"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two
published datasets, loaded by the platform's `cama_reference` pipeline (the files are in
`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia).
Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's
constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes
and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal
cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull
curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value
on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence;
v1 stopped its fit on a 60-second wall clock, short of it, so its curve is v1's within
FRACTIONAL_TOLERANCE, not equal. The fractional curve itself is a solver's, within
SOLVER_TOLERANCE of the exact series.
The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to
convergence, a few minutes each) are marked `slow` and run only with RECURRENCE_SLOW=1
(about an hour); the default set takes about two minutes.
"""
import json
import os
import re
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from joblib.externals.loky import get_reusable_executor
from scipy.special import gammaln
from conftest import _platform
from models import curves
from models.cama import recurrence
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1"
# Max |S| difference to v1's fractional Weibull curve: v1 stopped its fit on a 60 s clock,
# short of the optimum this fit converges to (largest gap measured: 0.053).
FRACTIONAL_TOLERANCE = 0.06
SOLVER_TOLERANCE = 1e-6 # max |S| error of the fractional Weibull's solver (~1e-7 measured)
FACTOR_TOLERANCE = 1.01e-4
FILES = ("brca_metabric_clinical_data.tsv", "scanb_clinical_metadata.txt")
PIPELINE = Path(__file__).parents[2] / "tests" / "fixtures" / "pipelines" / "cama_reference.json"
pytestmark = pytest.mark.skipif(
not all((RAW / f).exists() for f in FILES), reason="no reference raw files"
)
slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset")
def _json(path: str):
return json.loads((V1 / path).read_text())
VERSION = _json("version.json") if V1.exists() else {}
DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exists() else {}
FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else []
@pytest.fixture(scope="module")
def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
"""Both datasets as the platform loads them: the `cama_reference` pipeline into a fresh
platform, read back from its tables."""
folder = tmp_path_factory.mktemp("platform")
platform = _platform("sqlite", folder)
drawn = folder / "pipeline.json"
drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW)))
platform.save("pipelines", "cama_reference", drawn)
platform.ingest("cama_reference")
# What the training job reads (models.cama.specs), from that platform.
out = folder / "datasets.pkl"
platform.run("python", "-c", "import pandas as pd; from models.cama.specs import MODELS; "
f"pd.to_pickle(MODELS['recurrence'].datasets(), {str(out)!r})") # fmt: skip
return pd.read_pickle(out)
@pytest.fixture(scope="module")
def prepared(raws):
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
@pytest.fixture(scope="module")
def fits(prepared):
found = modeling.fit(prepared, {})
get_reusable_executor().shutdown(wait=True)
return found
# ---------------------------------------------------------------- comparisons
# v1 read SCAN-B's clinical stage as a number, so its categories print as 0.0, 1.0...; the
# platform keeps the dataset's text (0, 1...). Same categories, in the same order.
STAGES = {f"{n}.0": str(n) for n in range(5)}
def _stages(table: dict) -> dict:
"""v1's summary with the stages as the dataset writes them."""
text = re.sub(r"Estadio_clinico=(\d)\.0", r"Estadio_clinico=\1", json.dumps(table))
return json.loads(text)
def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0):
ref = [{**r, **{k: STAGES.get(r[k], r[k]) for k in ("categoria", "referencia") if k in r}}
if r.get("variable") == "Estadio_clinico" else r for r in ref] # fmt: skip
assert len(mine) == len(ref)
for i, (a, b) in enumerate(zip(mine, ref, strict=True)):
assert a.keys() == b.keys(), i
for c, z in b.items():
x = a[c]
if isinstance(z, float) and not isinstance(z, bool) and x is not None:
assert abs(x - z) <= tolerance, (i, c, x, z)
else:
assert x == z, (i, c, x, z)
def _auc_rows(rows: list[dict], with_bootstrap: bool) -> list[dict]:
keep = slice(None) if with_bootstrap else slice(0, 6)
return [dict(list(r.items())[keep]) for r in rows]
def _reference_selection(source: str) -> dict:
"""v1's bootstrap selection shares, as its risk-factor table published them."""
found = {}
for r in DEVELOPMENT["factores_riesgo"]["filas"]:
if r["cohorte"] == source and r["tipo"] == "factor de riesgo":
found.setdefault(r["horizonte_meses"], {})[r["variable"]] = r[
"freq_seleccion_bootstrap"
]
return found
def _check_figures(records: list[dict], fractional_tolerance: float):
assert [(r["cohorte"], r["escenario"]) for r in records] == [
(r["cohorte"], r["escenario"]) for r in FIGURES
]
for mine, ref in zip(records, FIGURES, strict=True):
fixed = ("condiciones", "n", "recaidas", "observado_hasta", "months_max", "cohorte_nombre")
assert {k: mine[k] for k in fixed} == {k: ref[k] for k in fixed}
assert mine["bootstrap_replicas"] == ref["bootstrap_replicas"]
assert mine["km"]["months"] == ref["km"]["months"]
for part in ("S", "low", "high"):
np.testing.assert_allclose(mine["km"][part], ref["km"][part], rtol=0, atol=1e-12)
got, want = mine["points"]["COMB"][part], ref["points"]["COMB"][part]
np.testing.assert_allclose(got, want, rtol=0, atol=1e-12)
np.testing.assert_allclose(mine["weibull"]["t"], ref["weibull"]["t"], rtol=0, atol=0)
np.testing.assert_allclose(mine["weibull"]["S"], ref["weibull"]["S"], rtol=0, atol=1e-12)
gap = np.nanmax(np.abs(np.subtract(mine["weibull_fractional"]["S"],
ref["weibull_fractional"]["S"]))) # fmt: skip
assert gap <= fractional_tolerance, (mine["escenario"], gap)
# ---------------------------------------------------------------- fast
def test_cohorts(prepared, raws):
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
for source, c in prepared.items():
assert len(c.frame) == sampling[source]["pacientes"]
assert int(c.frame["evento"].sum()) == sampling[source]["recaidas"]
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
assert c.covariates == list(missing[source])
assert cohorts.unknown_shares(c) == missing[source]
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
def test_routines(prepared):
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
for name, record in found.items():
assert record == _json(f"rutinas/{name}.json"), name
def test_c_index_and_internal_auc(fits):
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
metrics = reports.metrics(rows)
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
def test_saved_model(fits):
"""METABRIC's terms (in order of entry), parents, and their whole-cohort refits."""
tables = modeling.tables(fits["metabric"])
for h, mine in tables.items():
ref = VERSION["model"]["tables"][str(h)]
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
assert {**mine, "hbn_cpt": cpt} == ref, h
frame, covariates = fits["metabric"].cohort.frame, fits["metabric"].cohort.covariates
model = recurrence.Recurrence("metabric", recurrence.HORIZONS, covariates, tables)
found = model.predict(frame.iloc[:5])
assert list(found.columns) == ["recurrence_12m", "recurrence_36m", "recurrence_60m"]
t = tables[36]
row = frame.iloc[0]
x = np.array([float(f"{v}_{row[v]}" == term) for term in t["lr_terms"]
for v in [modeling.variable_of(term, model.covariates)]]) # fmt: skip
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + x @ np.array(t["lr_coefficients"]))))
p_hbn = t["hbn_cpt"][tuple(row[p] for p in t["hbn_parents"])]
assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15)
@pytest.mark.slow
@slow
def test_calculator(fits):
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
records, rows = [], []
for source in recurrence.SOURCES:
found = calculator.calculator(fits[source])
records += found[0]
rows += found[1]
get_reusable_executor().shutdown(wait=True)
table = reports.table(pd.DataFrame(rows).round(4))
assert table["columnas"] == DEVELOPMENT["calculadora"]["columnas"]
_same_rows(table["filas"], DEVELOPMENT["calculadora"]["filas"])
_check_figures(records, FRACTIONAL_TOLERANCE)
def test_risk_factors(fits):
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
table = pd.concat(
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
ignore_index=True,
)
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
def test_fractional_weibull_reproduces_the_classic_one():
"""With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's."""
t = np.linspace(0, 300, 61)
for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)):
found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam)
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741
"""E_{rho,m,l}(z) by its defining series, in floats: exact where |z| is small."""
j = np.arange(terms - 1)
log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1)
- gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip
return (np.exp(log_c)[None, :] * z[:, None] ** np.arange(terms)[None, :]).sum(axis=1)
def test_fractional_weibull_solver_matches_the_series():
"""Where the series is exact in floats (|z| < 2), the solver gives it within its error."""
t = np.linspace(0, 72, 289)
for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)):
s = k + a - 2
z = -np.exp(gammaln(k + 1) - gammaln(k + a - 1)) * (t / lam) ** (k + a + b - 2)
assert np.abs(z).max() < 2
found, want = curves.fractional(t, k, a, b, lam), _series(z, b, s / b + 1, s / b)
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
# ---------------------------------------------------------------- slow: the whole v1 run
@pytest.mark.slow
@slow
def test_train_reproduces_v1(raws):
model, metrics, found = recurrence.train(raws, bootstrap=True)
assert metrics == VERSION["metrics"]
for h in recurrence.HORIZONS:
mine = model.tables[h]
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
assert {**mine, "hbn_cpt": cpt} == VERSION["model"]["tables"][str(h)]
technical = found["technical_validation"]
for name, record in technical["rutinas"].items():
assert record == _json(f"rutinas/{name}.json"), name
tables = technical["recurrencia_desarrollo"]["tablas"]
_same_rows(tables["auc"]["filas"], DEVELOPMENT["auc"]["filas"])
_same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"])
_same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip
assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"])
figures = found["interpretability"]["recurrencia"]
assert figures["horizons_months"] == [12, 36, 60]
_check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE)
json.dumps(found, allow_nan=False) # JSON-able as it is
-74
View File
@@ -1,74 +0,0 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.registry import PromotionBlocked, registry
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
version = registry.register(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert registry.status("cacu", "tamizaje", version) == "desarrollo"
with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
domain, scenario, first = production_ready("v1")
_, _, second = production_ready("v2", metrics={"auc": 0.84})
assert registry.status(domain, scenario, first) == "candidata"
registry.promote(domain, scenario, first)
registry.promote(domain, scenario, second)
assert registry.status(domain, scenario, first) == "retirada"
assert registry.status(domain, scenario, second) == "produccion"
other_domain, other_scenario, other_version = production_ready("v1-dx", scenario="diagnostico")
registry.promote(other_domain, other_scenario, other_version)
assert registry.status(domain, scenario, second) == "produccion"
def test_reports_can_be_attached_after_training(production_ready):
domain, scenario, version = production_ready("v1")
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri=None)
assert not next(c for c in registry.checks(domain, scenario, version) if c.code == "MLD-01b").passed
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri="docs/clinica-v2.pdf")
assert all(c.passed for c in registry.checks(domain, scenario, version))
with pytest.raises(ValueError):
registry.attach_reports(domain, scenario, version, metrics="{}")
def test_artifacts_are_logged_to_the_run(production_ready):
domain, scenario, version = production_ready("v1")
lineage = registry.lineage(domain, scenario, version)
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
def test_retire_and_lineage(production_ready):
domain, scenario, first = production_ready("v1", metrics={"auc": 0.8, "brier": 0.2})
_, _, second = production_ready("v2", metrics={"auc": 0.85})
registry.promote(domain, scenario, second)
lineage = registry.lineage(domain, scenario, second)
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
assert [p["paso"] for p in lineage["cohorte_exclusiones"]] == ["candidatas", "sin evento previo"]
assert lineage["model_version"]["status"] == "produccion"
registry.retire(domain, scenario, second)
assert registry.status(domain, scenario, second) == "retirada"
with pytest.raises(ValueError):
registry.retire(domain, scenario, second)
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.export import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "x.onnx"
path.write_bytes(b"weights")
inspect_onnx_metadata(path)
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
with pytest.raises(ValueError):
registry.versions(domain, scenario)
+172
View File
@@ -0,0 +1,172 @@
"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst
can trust, and everything the platform can't decide alone is put in front of a reviewer.
The source hides its answers the way the real one does (synthetic.site): one PDF per study in
one SQL Server table, the institute's forms beside what outsourced labs send back; an HPV result
is a document of its own on its cytology's order; pathology comes scanned, the name surname
first and no birth date; some forms say "MA." for María or misspell the name and leave the
employee number out; some HPV reports were re-issued the other way; two women share a name.
Medical notes (the colposcopy clinic's, oncology's) and death notes are the institute's forms.
"""
import json
from collections import Counter
from datetime import date
from core import catalog
FIELDS = {
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18"),
"cervical_biopsy": ("request_date", "report_date", "histology"),
"mammography": ("exam_date", "report_date", "adequacy", "birads"),
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"),
"breast_treatment": ("start_date", "kind"),
"clinical_note": ("note_date", "specialty", "icd10"),
"death": ("death_date",),
} # fmt: skip
BOOLS = {"hpv", "hpv_16", "hpv_18"}
NUMBERS = {"ki67_pct", "size_mm"}
def value(field, v):
if v is None:
return None
if field in BOOLS:
return bool(v) if not isinstance(v, str) else v == "true"
if field in NUMBERS:
return float(v)
return v.isoformat() if isinstance(v, date) else str(v)
def said(record: dict, entity: str) -> dict | None:
"""What a document says of one study (an oncology note: its treatment and the note)."""
if entity == "clinical_note":
return record.get("clinical_note")
return record["values"] if record["entity"] == entity else None
def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path):
truth = site.truth
(tmp_path / "pipeline.json").write_text(site.drawn)
platform.save("concept_maps", "erick_site", site.concept_map)
platform.save("pipelines", "site", tmp_path / "pipeline.json")
platform.ingest()
q = platform.query
of = site.patients(q)
# Persons: nobody is merged with somebody else, except the two women of one name, joined
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
# whose report it is.
# A person nothing names (a scan whose name line wasn't read) is held as well: there is
# nobody to join her to.
members: dict[str, set] = {}
held, nameless, named, person_of = set(), set(), set(), {}
for record, person, why, *identifiers in q(
"select _record, person_id, _held, full_name, birth_date, record_number "
"from bronze.n__site__persons"
):
members.setdefault(person, set()).add(of[record])
person_of[record] = person
if any(identifiers):
named.add(person)
if why and "no name" in why:
nameless.add(person)
elif why:
held.add(person)
assert nameless == set(members) - named, nameless
torn = {p for p, who in members.items() if len(who) > 1}
assert len(torn) == 1 and torn == held, (torn, held)
assert members[next(iter(torn))] == set(site.meta["namesakes"])
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless}
# Every woman split into several persons (a misspelled form, say) is in the review
# queue, joined by candidates.
parts: dict[str, set] = {}
for p, x in patient.items():
parts.setdefault(x, set()).add(p)
queued = {
frozenset(person_of[r] for r in pair)
for pair in q("select person, candidate from bronze.n__site__persons__review")
}
split = {x: persons for x, persons in parts.items() if len(persons) > 1}
assert split # the misspelled forms, at least
for x, persons in split.items():
reached, frontier = set(), {next(iter(persons))}
while frontier:
reached |= frontier
frontier = {b for a in frontier for pair in queued if a in pair for b in pair}
frontier -= reached
assert persons <= reached, (x, persons)
# Every value accepted from a typed document is what the document says; and most of what
# the documents say is read (a scan's columns can come back out of order, and a value its
# pattern doesn't find is left out, never guessed). A scan can misread one valid code as
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
# values, each listed.
at = {r["where"]: r for r in truth}
place = {r: f"ResultadoSubrogado:{i}"
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
record_of = {w: r for r, w in place.items()}
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
for entity in FIELDS:
mine = accepted[entity] = {}
for record, field, *values in q(
"select _record, field, value_text, value_num, value_bool, value_date "
f"from bronze.staged__observation where study = '{entity}'"
):
got = next((v for v in values if v is not None), None)
mine.setdefault(record, {})[field] = value(field, got)
assert mine, entity
stated = read = scanned = 0
missed: Counter = Counter()
wrong = []
for record, got in mine.items():
t = at[place[record]]
if not t.get("flipped"):
truly = {f: v for f, v in said(t, entity).items() if v is not None}
differ = {f: (v, value(f, truly.get(f))) for f, v in got.items()
if v != value(f, truly.get(f))} # fmt: skip
assert t.get("scanned") or not differ, (t["where"], differ)
wrong += [(t["where"], differ)] if differ else []
scanned += len(got) if t.get("scanned") else 0
stated, read = stated + len(truly), read + len(got)
missed.update(set(truly) - set(got))
assert read >= 0.95 * stated, (entity, read, stated, missed)
assert len(wrong) <= 0.01 * scanned, (entity, wrong)
# A row a rule held because of a value (a scan misread) is held because it is wrong:
# never loaded, and a reviewer sees it.
misread = set()
for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"):
if record in place and person_of.get(record) not in torn | nameless:
t, got = at[place[record]], json.loads(raw)
truly = said(t, entity)
assert {f: value(f, got.get(f)) for f in truly} != {
f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip
misread.add(record)
# Silver: each person's studies, the records of one study key merged (a cytology form and
# its HPV report are one cytology), but for the torn person's, the misreads, and a study
# whose reports contradict each other (until review says which is right).
for entity, fields in FIELDS.items():
key = catalog.studies()[entity].key
merged: dict[tuple, dict] = {}
disputed = set()
for r in truth:
record = record_of[r["where"]]
got = accepted[entity].get(record)
if got is None or person_of[record] in torn | nameless or record in misread:
continue
at_key = (person_of[record], *(got.get(k) for k in key))
merged.setdefault(at_key, {}).update(got)
if r.get("conflict"):
disputed.add(at_key)
expected = {(k[0], *(row.get(f) for f in fields))
for k, row in merged.items() if k not in disputed} # fmt: skip
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True)))
for p, *values in rows if p not in torn | nameless} # fmt: skip
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
sorted(expected - got, key=str)[:4]) # fmt: skip
+182
View File
@@ -0,0 +1,182 @@
"""CaMa survival measured against the SEER-trained original (Luis's pipeline,
`05_curvas_supervivencia.py`): the same model, trained on the same SEER patients, gives each
clinical scenario the same patients and deaths, the same observed curves (Kaplan-Meier,
Weibull, fractional Weibull), and model points close to the original's.
SEER is real registry data under NCI's use agreement: it is read from outside git
(SEER_FILE) and nothing of it is kept. The original's outputs are read from where it ran
(LUIS_RUN: its `subgrupos_*.csv`). Both missing: the test is skipped.
Each SEER case becomes a timeline: a first invasive biopsy at diagnosis with its report's
results, its first course of treatment a month later, and its death or last contact placed so
the platform's whole months of follow-up are SEER's survival months.
The model points are not the original's: it trains on every case, the platform on the
earliest 70% by index date (and validates on the rest), and SEER's latest diagnoses carry few
recorded deaths yet. They are checked against the survival of the cases the model learned
from; their distance to the original's is printed. Slow (a quarter of an hour): SEER_SLOW=1."""
import os
import re
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from models import curves, survival
from models.cama.specs import MODELS
from models.survival import DAYS_PER_MONTH, DAYS_PER_YEAR, TRAIN_FRACTION, scenario_masks
SEER = Path(
os.environ.get("SEER_FILE", Path.home() / "camaSupervivencia" / "dataframe_recodificado.csv")
)
RUN = Path(os.environ.get("LUIS_RUN", Path.home() / "isssteleon-data" / "luis-run"))
AS_OF = pd.Timestamp("2023-12-31") # SEER's follow-up cutoff: survivors are followed to it
pytestmark = [
pytest.mark.skipif(
not (SEER.exists() and (RUN / "subgrupos_KM_Weibull_fraccional.csv").exists()),
reason="SEER and the original's outputs are outside git",
),
pytest.mark.skipif(not os.environ.get("SEER_SLOW"), reason="slow: SEER_SLOW=1"),
]
CURVE = 1e-3 # the fits' agreement (maximum distance to Kaplan-Meier, shape k relative)
CALIBRATION = 0.01 # the model's mean survival against its training cases' Kaplan-Meier
STAGE = {"0 (in situ)": "0", "I": "I", "II": "II", "III": "III", "IV": "IV"}
GRADE = {"G1": "1", "G2": "2", "G3": "3"}
RECEPTOR = {"Positivo": "positive", "Negativo": "negative"}
SURGERY = {"Conservadora": "breast_conserving_surgery", "Mastectomía": "mastectomy"}
def _her2(subtype: str) -> str | None:
return "positive" if "HER2+" in subtype else "negative" if "HER2-" in subtype else None
def _age(recode: str) -> float:
"""The age band's lower bound, as the original reads it ("65-69 years": 65)."""
found = re.search(r"\d+", str(recode))
return float(found.group()) if found else np.nan
def seer_events(frame: pd.DataFrame) -> pd.DataFrame:
"""SEER cases as CaMa timelines (gold `cama_events` shape, indexed at diagnosis)."""
months = pd.to_numeric(frame["Survival_months"], errors="coerce")
frame, months = frame[months.notna()], months[months.notna()]
dead = frame["Vital_status_recode_study_cutoff_used"].str.lower().str.contains("dead")
person = frame["Patient_ID"].to_numpy()
# Whole months from the index are SEER's. A survivor's index is months + 1/2 before the
# cutoff; a death's is in its year of diagnosis (spread over the year by its id, never so
# late that the death would pass the cutoff), and she dies months + 1/4 after it. So the
# index dates keep SEER's calendar, which the model's split by index date reads.
latest = AS_OF - pd.to_timedelta((months + 0.5) * DAYS_PER_MONTH, "D")
year = pd.to_datetime(frame["Year_of_diagnosis"] + "-01-01")
spread = pd.to_timedelta(frame["Patient_ID"].astype(int) % 365, "D")
index = latest.where(~dead, (year + spread).where(year + spread < latest, latest))
death = index + pd.to_timedelta((months + 0.25) * DAYS_PER_MONTH, "D")
birth = index - pd.to_timedelta((frame["Age_recode_with_1_year_olds_and_90"].map(_age) + 0.5)
* DAYS_PER_YEAR, "D") # fmt: skip
base = pd.DataFrame({"person_id": person, "index_date": index.to_numpy(),
"record_number": person}) # fmt: skip
rows = [base.assign(date=birth.to_numpy(), type="birth", value_code=None)]
rows.append(base[dead.to_numpy()].assign(date=death[dead].to_numpy(), type="death",
value_code=None)) # fmt: skip
hr_negative = frame["Subtipo_molecular_cat"].str.startswith("HR-")
hr_positive = frame["Subtipo_molecular_cat"].str.startswith("HR+")
er = frame["Receptor_estrogeno_cat"].map(RECEPTOR)
pr = frame["Receptor_progesterona_cat"].map(RECEPTOR)
both_negative = er.eq("negative") & pr.eq("negative")
results = {
"biopsy": pd.Series("invasive", index=frame.index),
"stage": frame["Estadio_cat"].map(STAGE),
"grade": frame["Grado_histologico_cat"].map(GRADE),
# Hormone receptors as SEER's subtype states them, which the original's scenarios read:
# SEER's own columns disagree in a few cases (HR+ with both recodes negative, likely
# borderline results): HR- makes both negative; HR+ with both negative leaves ER unknown.
"er": er.mask(hr_negative, "negative").mask(hr_positive & both_negative, None),
"pr": pr.mask(hr_negative, "negative"),
"her2": frame["Subtipo_molecular_cat"].map(_her2),
"histologic_type": frame["Histologic_Type_ICD_O_3"].astype(str) + "/3",
}
for kind, values in results.items():
rows.append(base.assign(date=index.to_numpy(), type=kind, value_code=values.to_numpy()))
size = pd.to_numeric(frame["Tumor_Size_Over_Time_Recode_1988"], errors="coerce")
rows.append(base.assign(date=index.to_numpy(), type="size_mm", value_code=None,
value_num=size.where(size < 990).to_numpy())) # fmt: skip
course = {
"surgery": frame["Tratamiento_quirurgico_cat"].map(SURGERY),
"chemotherapy": frame["Quimioterapia_cat"].map({"Sí": "chemotherapy"}),
"radiotherapy": frame["Radioterapia_cat"].map({"Sí": "radiotherapy"}),
}
month_later = index + pd.Timedelta(days=30)
for values in course.values():
rows.append(base.assign(date=month_later.to_numpy(), type="treatment",
value_code=values.to_numpy())) # fmt: skip
events = pd.concat(rows, ignore_index=True)
events = events[events["type"].isin(["birth", "death"]) | events["value_code"].notna()
| events.get("value_num", pd.Series(np.nan)).notna()] # fmt: skip
events["value_num"] = events.get("value_num")
events["source_table"], events["source_id"] = "seer", events["person_id"]
return events.reset_index(drop=True)
@pytest.fixture(scope="module")
def trained():
events = seer_events(pd.read_csv(SEER, dtype=str))
spec = MODELS["survival"]
model, metrics, data = spec.train(events, AS_OF)
return spec, model, metrics, data
def _original(name: str) -> pd.DataFrame:
return pd.read_csv(RUN / name)
def test_each_scenario_takes_the_originals_patients_and_deaths(trained):
spec, _, _, data = trained
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios)
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
for name, row in theirs.iterrows():
mask = masks[name]
assert (int(mask.sum()), int(members["event"][mask].sum())) == (
row["n"],
row["fallecidos"],
), name
@pytest.fixture(scope="module")
def report(trained):
spec, model, _, data = trained
return survival.interpretability(spec, model, data)
def test_each_scenarios_observed_curves_are_the_originals(report):
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
assert {e["escenario"] for e in report["escenarios"]} == set(theirs.index)
for e in report["escenarios"]:
row, km = theirs.loc[e["escenario"]], np.array(e["km"]["S"])
months = np.arange(len(km))
weibull = np.interp(months, e["weibull"]["t"], e["weibull"]["S"])
fractional = np.interp(months, e["weibull_fractional"]["t"], e["weibull_fractional"]["S"])
assert e["weibull"]["k"] == pytest.approx(row["k Weibull"], rel=CURVE), e["escenario"]
assert np.abs(weibull - km).max() == pytest.approx(row["máx|KM−Weibull|"], abs=CURVE)
assert np.abs(fractional - km).max() <= row["máx|KM−fracc.|"] + CURVE, e["escenario"]
def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained, report):
spec, _, _, data = trained
train = data["train"].reset_index(drop=True)
masks = scenario_masks(train, spec.scenarios)
theirs = _original("subgrupos_puntos_LR_HBN.csv")
horizons = list(spec.borders[1:])
for e in report["escenarios"]:
mask = masks[e["escenario"]]
months, event = train["months"][mask].to_numpy(), train["event"][mask].to_numpy(bool)
km, _, _ = curves.kaplan_meier(months, event, horizons[-1])
ours = np.array(e["points"]["COMB"]["S"])
assert ours == pytest.approx(km[horizons], abs=CALIBRATION), e["escenario"]
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max()
print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}")
+174
View File
@@ -0,0 +1,174 @@
"""The tea_eeg job's graph, sensor, config classes and synthetic EEG scope."""
from pathlib import Path
import dagster as dg
import pytest
from pydantic import ValidationError
from sqlalchemy import inspect
from models import definitions
from models.definitions import (
ExecutionConfig,
ScopeConfig,
after_ingest,
defs,
tea_eeg,
tea_eeg_after_ingest,
)
from models.tea import jobs as tea_jobs
from persistance import cluster, destination, eeg
from synthetic import tea
def _config(scope: dict) -> dict:
return {"ops": {"tea_analyze_studies": {"config": {
"scope": scope, "execution": {"mode": "sync"}}}}} # fmt: skip
@pytest.fixture
def calls(monkeypatch):
log = []
def analyze(scope=None, *, rebuild_gold=True):
log.append(("analyze", scope, rebuild_gold))
return 2
monkeypatch.setattr(tea_jobs, "analyze", analyze)
monkeypatch.setattr(tea_jobs, "score_curves", lambda: log.append(("score",)) or {"c": 3})
monkeypatch.setattr(tea_jobs, "relate", lambda: log.append(("relate",)))
monkeypatch.setattr(definitions.silver, "build", lambda sel: log.append(("build", sel)))
return log
def test_tea_eeg_runs_the_four_steps_in_order(calls):
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(), run_config=_config({"mode": "first_n", "n": 2})
)
assert result.success
assert [c[0] for c in calls] == ["analyze", "score", "relate", "build"]
assert calls[0][1].n == 2 and calls[0][2] is False
assert calls[3][1] == tea_jobs.GOLD_SELECT
assert result.output_for_node("tea_analyze_studies") == {"analysed": 2}
assert result.output_for_node("tea_score_curves") == {"scored": {"c": 3}}
assert result.output_for_node("tea_relate_ados2") == {"ados2_association": None}
assert result.output_for_node("tea_build_gold") == {"built": tea_jobs.GOLD_SELECT}
def test_a_failing_analysis_stops_the_graph(calls, monkeypatch):
def boom(scope=None, *, rebuild_gold=True):
raise RuntimeError("no signal")
monkeypatch.setattr(tea_jobs, "analyze", boom)
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(),
run_config=_config({"mode": "pending"}),
raise_on_error=False,
)
assert not result.success
assert calls == []
def test_a_bad_scope_fails_before_any_work(calls):
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(),
run_config=_config({"mode": "first_n"}),
raise_on_error=False,
)
assert not result.success
assert calls == []
failure = next(e for e in result.all_events if e.is_step_failure)
assert "first_n needs n" in str(failure.event_specific_data.error)
def test_scope_validation():
assert eeg.Scope().mode == "pending"
assert eeg.Scope(mode="first_n", n=3).n == 3
good = "p1|2024-05-06"
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
bad = [
{"mode": "first_n"},
{"mode": "first_n", "n": 0},
{"mode": "first_n", "n": 2, "ids": [good]},
{"mode": "ids"},
{"mode": "ids", "ids": [good], "n": 1},
{"mode": "ids", "ids": ["nobar"]},
{"mode": "ids", "ids": ["p|2024-5-6"]},
{"mode": "ids", "ids": ["|2024-05-06"]},
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
{"mode": "pending", "n": 1},
{"mode": "pending", "ids": [good]},
{"mode": "other"},
{"extra": 1},
]
for kwargs in bad:
with pytest.raises(ValidationError):
eeg.Scope(**kwargs)
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
with pytest.raises(ValidationError, match="first_n needs n"):
ScopeConfig(mode="first_n").model()
def test_config_mirrors_match_the_shared_models():
for config, shared in ((ScopeConfig, eeg.Scope), (ExecutionConfig, cluster.Execution)):
assert list(config.model_fields) == list(shared.model_fields)
for name, field in shared.model_fields.items():
assert config.model_fields[name].default == field.default, name
# a wrong value still reaches the shared model's validation
with pytest.raises(ValidationError):
ExecutionConfig(mode="cloud").model()
with pytest.raises(ValidationError):
ScopeConfig(mode="all").model()
def test_after_ingest_requests_a_run_only_with_pending_eegs():
skip = after_ingest("r1", lambda: False)
assert isinstance(skip, dg.SkipReason)
request = after_ingest("r1", lambda: True)
assert isinstance(request, dg.RunRequest)
assert request.run_key == "after-ingest-r1"
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
assert scope == {"mode": "pending"}
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
def test_definitions_load_with_every_job_and_the_sensor():
dg.Definitions.validate_loadable(defs)
names = {j.name for j in defs.jobs}
assert names >= {"ingest", "train", "score", "analyze", "tea_eeg"}
assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING
def test_relate_is_a_no_op_until_phase_2():
assert tea_jobs.relate() is None
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
def test_tea_eeg_first_n_analyses_exactly_n(platform, tmp_path, monkeypatch):
tea.build(tmp_path / "hospital_tea.db")
fixtures = Path(__file__).parents[2] / "tests" / "fixtures"
drawing = tmp_path / "pipeline.json"
drawing.write_text(
(fixtures / "pipelines" / "hospital_tea.json")
.read_text()
.replace("{hospital}", str(tmp_path))
)
platform.save("concept_maps", "hospital_tea", fixtures / "concept_maps" / "hospital_tea.json")
platform.save("pipelines", "tea", drawing)
platform.ingest("tea")
for name in ("PLATFORM_DATABASE_URL", "DLT_DATA_DIR", "EXECUTION_MODE"):
monkeypatch.setenv(name, platform.env[name])
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
destination.engine.cache_clear()
try:
table = "bronze.eeg_analysis"
with destination.engine().connect() as con:
has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze")
before = platform.count(table) if has_analysis else 0
pending = len(eeg.pending())
tea_jobs.analyze(eeg.Scope(mode="first_n", n=3), rebuild_gold=False)
assert platform.count(table) == before + 3
assert len(eeg.pending()) == pending - 3
finally:
destination.engine.cache_clear()
+227
View File
@@ -0,0 +1,227 @@
import hashlib
import os
from datetime import date
from types import SimpleNamespace
import dagster as dg
import pytest
from core import tea
from core.pipeline import Extract, Pipeline, Source
from core.tea import ados2
from models.definitions import tea_preview
from models.tea import preview as study
from models.tea.eeg import analysis, curves
from persistance import config, previews
@pytest.fixture
def preview_area(monkeypatch, tmp_path):
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
return previews.area()
def test_previews_area(preview_area):
key = previews.put(b"file")
assert key == hashlib.sha256(b"file").hexdigest()
os.utime(preview_area / key, (1, 1))
assert previews.put(b"file") == key
assert (preview_area / key).stat().st_mtime == 1
assert previews.get(key) == b"file"
for invalid in ("../x", "abc"):
with pytest.raises(ValueError):
previews.get(invalid)
with pytest.raises(LookupError, match=f"no preview file {'0' * 64}"):
previews.get("0" * 64)
previews.discard([key, None, "0" * 64])
assert not (preview_area / key).exists()
old = previews.put(b"old")
recent = previews.put(b"recent")
os.utime(preview_area / old, (1, 1))
assert previews.sweep() == 1
assert {path.name for path in preview_area.iterdir()} == {recent}
def test_an_unreadable_file_is_a_result_not_a_crash():
result = study.preview(b"nope")
assert result.eeg.valid is False
assert result.eeg.checks
assert result.ados2 is None
assert result.eeg.recorded_on is None
@pytest.fixture
def valid_study(monkeypatch):
metric = analysis.Metric("paroxysmal_spikes", 3, {"F3": 3, "F4": 0}, {"frontal": 3})
analysed = analysis.Analysis(
valid=True,
level="valid",
age_months=42,
clean_fraction=1,
bad_channels=0,
channels=19,
duration_min=20,
line_noise_db=None,
sleep=True,
checks=[],
metrics=[metric],
features={"eeg-spikes": {curves.EXPOSURE: 20}},
error=None,
)
monkeypatch.setattr(analysis, "analyze", lambda *_: analysed)
def test_scores_come_from_the_champions(monkeypatch, valid_study):
baseline = dict.fromkeys(("value", "electrode_F3", "zone_frontal"))
model = SimpleNamespace(unwrap_python_model=lambda: SimpleNamespace(baseline=baseline))
monkeypatch.setattr(study.registry, "champion", lambda _: (3, model))
score = {"z": 1, "outside": 0, "p5": 0, "median": 2, "p95": 4}
def deviations(models, analysed):
assert set(models) == set(curves.SCENARIOS)
assert analysed.metrics[0].electrodes == {"F3": 3}
return {
"paroxysmal_spikes": {
"value": score,
"electrodes": {"F3": score},
"zones": {"frontal": score},
}
}
monkeypatch.setattr(curves, "deviations", deviations)
result = study.preview(b"edf")
metric = result.eeg.metrics[0]
assert metric.score == previews.Score(**score)
assert metric.electrodes == {
"F3": previews.Site(value=3, score=previews.Score(**score)),
"F4": previews.Site(value=0, score=None),
}
assert metric.zones == {"frontal": previews.Site(value=3, score=previews.Score(**score))}
assert metric.model == "tea.eeg-spikes/3"
assert not result.warnings
def test_no_champions_warns_and_leaves_z_empty(monkeypatch, valid_study):
monkeypatch.setattr(study.registry, "champion", lambda _: None)
result = study.preview(b"edf")
assert result.warnings == ["there are no champion age curves: no z is shown"]
metric = result.eeg.metrics[0]
assert metric.score is metric.model is None
assert all(site.score is None for site in (metric.electrodes | metric.zones).values())
def _pipeline(patterns):
return Pipeline(
nodes=[
Source(id="source", source="dlt.sources.sql_database:sql_table"),
Extract(
id="x",
inputs=["source"],
column="text",
entity="ados2",
method="patterns",
patterns=patterns,
), # fmt: skip
]
)
def test_ados2_read_with_the_pipeline_patterns(monkeypatch):
text = "module module_1; date 2025-01-01; pointing 2; gestures 1; intonation 3"
patterns = {
"module": r"module (\w+)",
"evaluation_date": r"date ([\d-]+)",
"pointing": r"pointing (\d+)",
"gestures": r"gestures (\d+)",
"intonation": r"intonation (\d+)",
}
monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "error": None})
monkeypatch.setattr(study.config_log, "get", lambda _: (1, _pipeline(patterns)))
birth = date(2022, 1, 1)
result = study.preview(b"edf", b"%PDF", birth)
row = dict(module="module_1", evaluation_date=date(2025, 1, 1),
pointing=2, gestures=1, intonation=3) # fmt: skip
assert result.ados2 is not None
assert result.ados2.items == {
name: row.get(name) for name in tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
}
assert result.ados2.module == row["module"]
assert result.ados2.evaluation_date == row["evaluation_date"]
assert result.ados2.read == sorted(row)
assert (result.ados2.css, result.ados2.classification) == ados2.score(row, birth)
assert not result.warnings
def test_ados2_problems_are_warnings_not_errors(monkeypatch):
def check(report, *warnings):
result = study.preview(b"edf", report)
assert result.eeg == study.preview(b"edf").eeg
assert result.warnings == list(warnings)
return result.ados2
assert check(b"text", "the ADOS-2 file is not a PDF") is None
monkeypatch.setattr(study.graph, "read_file", lambda _: {"error": "broken"})
assert check(b"%PDF", "the ADOS-2 report could not be read: broken") is None
def missing(_):
raise LookupError("tea")
text = "pointing bad; date 2025-01-01"
monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "error": None})
monkeypatch.setattr(study.config_log, "get", missing)
assert check(b"%PDF", "no saved pipeline tea: the ADOS-2 report is not read") is None
monkeypatch.setattr(study.config_log, "get", lambda _: (1, Pipeline(nodes=[])))
assert check(b"%PDF", "pipeline tea has no ados2 extract node") is None
monkeypatch.setattr(
study.config_log, "get", lambda _: (1, _pipeline({"module": r"missing (.)"}))
)
assert check(b"%PDF", "no ADOS-2 field was found in the report") is None
patterns = {"pointing": r"pointing (\w+)"}
monkeypatch.setattr(study.config_log, "get", lambda _: (1, _pipeline(patterns)))
report = check(
b"%PDF",
"pointing: could not read 'bad' as a number",
"ADOS-2 not scored: no evaluation date",
)
assert report is not None
assert report.read == ["pointing"]
assert report.items["pointing"] is report.css is report.classification is None
patterns = {"evaluation_date": r"date ([\d-]+)"}
report = check(
b"%PDF",
"the ADOS-2 score could not be calculated: the report lacks the module or the item scores",
)
assert report is not None
assert report.css is report.classification is None
def _execute(key, ados_key, *, raise_on_error=True):
with dg.DagsterInstance.ephemeral() as instance:
return tea_preview.execute_in_process(
run_config={"ops": {"preview_study": {"config": {"edf": key, "ados2": ados_key}}}},
instance=instance,
raise_on_error=raise_on_error,
)
def test_the_job_deletes_its_files_and_returns_the_result_as_output(preview_area):
run = _execute(previews.put(b"edf"), previews.put(b"not a report"))
assert run.success
assert not list(preview_area.iterdir())
assert run.output_for_node("preview_study") == {"valid": False, "warnings": 1}
(event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT)
result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value)
assert result.eeg.valid is False
def test_the_job_deletes_its_files_when_the_study_fails(monkeypatch, preview_area):
def failed(*_):
raise RuntimeError("study failed")
monkeypatch.setattr(study, "preview", failed)
run = _execute(previews.put(b"edf"), previews.put(b"%PDF"), raise_on_error=False)
assert not run.success
assert not list(preview_area.iterdir())
+144
View File
@@ -0,0 +1,144 @@
import hashlib
from types import SimpleNamespace
import pytest
from edf_files import small_edf
from pydantic import ValidationError
from models import definitions
from models.tea import jobs
from models.tea.eeg import curves, reference
from persistance.cluster import Reference
@pytest.fixture
def cohort(tmp_path, monkeypatch):
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path))
monkeypatch.delenv("TEA_REFERENCE_CACHE", raising=False)
folder = tmp_path / "hel"
folder.mkdir()
for i in range(3):
small_edf(folder / f"{i}.edf")
ages = folder / "edades.csv"
ages.write_text("name,age\n0.edf,1.5\n1.edf,2.0\n2.edf,2.5\n")
return folder, ages
@pytest.fixture
def measurements(monkeypatch):
calls = []
def measure(studies, *, mains_hz):
calls.append((studies, mains_hz))
return [
{"key": key, "age_months": age, "valid": True, "error": None, "features": {}}
for key, _, age in studies
]
monkeypatch.setattr(reference, "measure", measure)
return calls
def test_a_named_reference_resolves_under_the_root(cohort, measurements):
_, measured, name, hz = jobs._reference(Reference(name="hel"))
[(studies, mains_hz)] = measurements
assert len(studies) == len(measured) == 3
assert all(path.parent == cohort[0] for _, path, _ in studies)
assert mains_hz == 50.0
assert (name, hz) == ("hel", 50)
def test_60_hz_changes_the_digest_and_is_passed_on(cohort, measurements):
digest_50, *_ = jobs._reference(Reference(name="hel"))
digest_60, _, _, hz = jobs._reference(Reference(name="hel", line_hz=60))
assert digest_50 == hashlib.sha256(b"0.edf|18.0\n1.edf|24.0\n2.edf|30.0").hexdigest()
assert digest_60 != digest_50
assert hz == 60
assert measurements[-1][1] == 60.0
def test_the_cache_is_named_by_cohort_and_digest_and_reused(cohort, measurements, monkeypatch):
cache = cohort[0].parent / "c"
monkeypatch.setenv("TEA_REFERENCE_CACHE", str(cache))
result = jobs._reference(Reference(name="hel"))
assert [p.name for p in cache.iterdir()] == [f"hel-{result[0][:16]}.json"]
assert jobs._reference(Reference(name="hel")) == result
assert len(measurements) == 1
def test_bad_references_fail_with_a_reason(cohort):
folder, ages = cohort
for name in ("..", ".", "nope"):
with pytest.raises(ValueError) as exc:
jobs._reference(Reference(name=name))
assert str(exc.value) == f"no reference cohort {name!r}"
ages.write_text("name,age\n0.edf,1\n1.edf,4\n2.edf,5\n")
with pytest.raises(
ValueError, match="reference cohort 'hel' has no EDF with an age from 16 to 36 months"
):
jobs._reference(Reference(name="hel"))
ages.unlink()
with pytest.raises(ValueError, match=r"reference cohort 'hel' has no edades\.csv"):
jobs._reference(Reference(name="hel"))
with pytest.raises(ValidationError, match="name"):
Reference(name="../x")
with pytest.raises(ValidationError, match="line_hz"):
Reference(name="hel", line_hz=55)
def test_legacy_environment_still_works(cohort, measurements, monkeypatch):
folder, ages = cohort
monkeypatch.setenv("TEA_REFERENCE_DIR", str(folder))
monkeypatch.setenv("TEA_REFERENCE_AGES", str(ages))
_, measured, name, hz = jobs._reference(None)
assert len(measured) == 3
assert (name, hz) == ("hk1k", 50)
assert measurements[0][1] == 50.0
def test_train_records_cohort_and_line_hz(cohort, measurements, monkeypatch):
monkeypatch.setattr(reference, "tables", lambda measured: {"curve": measured})
monkeypatch.setattr(curves, "train", lambda table, name: {"value": {}})
registrations = []
def register(*args):
registrations.append(args)
return 1
monkeypatch.setattr(jobs.registry, "register", register)
config = Reference(name="hel", line_hz=60)
assert jobs.train("curve", reference=config) == 1
[(_, _, params, _, reports)] = registrations
digest, *_ = jobs._reference(config)
assert params == {"cohort": "hel", "cohort_sha256": digest, "line_hz": "60"}
technical = reports["technical_validation"]
assert technical["cohort"] == "hel"
assert technical["line_hz"] == 60
def test_the_train_op_passes_the_reference_or_refuses_it(monkeypatch):
calls = []
def train(name, as_of, reference=None):
calls.append((name, as_of, reference))
return 1
fake = SimpleNamespace(train=train)
monkeypatch.setattr(definitions, "_jobs", lambda domain: fake)
config = {"ops": {"train_models": {"config": {
"domain": "tea", "models": ["curve"], "execution": {"mode": "sync"},
"reference": {"name": "a", "line_hz": 60},
}}}} # fmt: skip
assert definitions.train.execute_in_process(run_config=config).success
assert calls == [("curve", None, Reference(name="a", line_hz=60))]
fake.train = lambda name, as_of: 1
with pytest.raises(ValueError, match="tea models take no reference cohort"):
definitions.train.execute_in_process(run_config=config)
def test_reference_config_mirrors_the_shared_model():
assert definitions.ReferenceConfig.model_fields.keys() == Reference.model_fields.keys()
-83
View File
@@ -1,83 +0,0 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.registry import registry
from mlflow import MlflowException
from models.training import ReadOnlyRepository, TrainingRun
def test_prod_run_requires_a_cohort_build():
with pytest.raises(ValueError, match="cohorte_armado_id"):
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD)
def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.cohorte_armado_id is None
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
checkpoint = tmp_path / "model.onnx"
checkpoint.write_bytes(b"fake-onnx-bytes")
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
version = run.finish(metrics={"auc": 0.81})
mv = registry.get("cacu", "tamizaje", version)
assert mv.tags["environment"] == Environment.DEV.value
metrics = registry.client.get_run(mv.run_id).data.metrics
assert metrics["auc"] == 0.81
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
assert any(path.endswith("model.onnx") for path in artifacts)
def test_read_only_repository_blocks_writes(cacu_db):
from persistance.cacu import paciente_repository
read_only = ReadOnlyRepository(paciente_repository)
assert read_only.list() == []
with pytest.raises(PermissionError, match="ML-04"):
read_only.create(object())
with pytest.raises(PermissionError, match="ML-04"):
read_only.open_session()
def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
repo = run.repository("paciente")
assert isinstance(repo, ReadOnlyRepository)
with pytest.raises(PermissionError):
repo.create(object())
def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, tmp_path, monkeypatch):
root = tmp_path / "artefactos"
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(root))
run = TrainingRun(domain="cama", scenario="riesgo", environment=Environment.DEV)
experiment = run.client.get_experiment_by_name("cama-riesgo")
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.finish() == "1"
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert second.finish() == "2"
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
def unreachable(name):
raise MlflowException("servidor no disponible")
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
with pytest.raises(MlflowException, match="no disponible"):
third.finish()
def test_unknown_domain_is_rejected():
with pytest.raises(ValueError, match="dominio desconocido"):
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)