Compare commits

..

24 Commits

Author SHA1 Message Date
edgar a93292f3dd Silver gate: findings as the cytologist confirmed them
No inflammation grade field; one endometrial-cells field (40 or more).
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:03:20 -06:00
edgar 0fcbe95c90 Silver gate checks the cytologist's additional findings
The synthetic cytology form now has a free-text findings section; its text,
the inflammation grade and each stated finding are expected, the rest unknown.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 15:42:46 -06:00
edgar 8908184093 Silver gate checks the cytology's cervix_exam
The synthetic cytology form now records one of the three exploration answers.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 15:38:33 -06:00
edgar 1dc681fb5a Silver gate checks the cytology's presents_ answers
The synthetic cytology form records one "actualmente presenta" answer; only
that field is expected true, the others stay unknown.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:50:23 -06:00
edgar 7b6ffe17f5 Silver gate checks the cytology's gyn_ conditions
The synthetic cytology form records one gynaecological/obstetric condition;
only that field is expected true, the others stay unknown.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:36:07 -06:00
edgar 1f0d38de3c Silver gate checks the cytology's screening_history
The synthetic cytology form now says one of the four detection answers, and
the gate compares screening_history with the rest of the cytology's fields.
Not run yet: tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:33:32 -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
52 changed files with 6760 additions and 461 deletions
-6
View File
@@ -1,8 +1,2 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
-62
View File
@@ -1,62 +0,0 @@
# models
Python package with the standard `train()`/`predict()` interface for the
three screening models — CaCu, CaMa and TEA. Consumed by `WebApi`, but
independent of it: this package can read its own training/inference data
directly from `Persistance`, without going through `WebApi` at all.
## Structure
- `models/base.py` — `ScreeningModel`, the abstract base every model
implements (`train(data)` / `predict(data)`).
- `models/cacu.py`, `models/cama.py`, `models/tea.py` — one concrete
class per domain.
## How entities are accessed from models
This package depends on `../Persistance` (a local `uv` path dependency —
see `pyproject.toml`), and through it on `../Core`. **As of now this is
wiring, not usage**: `train()`/`predict()` in `cacu.py`/`cama.py`/`tea.py`
just raise `NotImplementedError` — no model imports `persistance` yet.
When real training/inference logic is added, the access pattern is the
same repository instances `WebApi` reads from — no separate data layer
for `models` to maintain:
```python
# models/models/cacu.py
from typing import Any
from persistance.cacu import citologia_cervical_repository
from models.base import ScreeningModel
class CaCuModel(ScreeningModel):
def train(self, data: Any = None) -> None:
if data is None:
data = citologia_cervical_repository.list(limit=10_000)
# ... fit on `data`
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaCu prediction is not implemented yet.")
```
The `data: Any = None` default on `train()`/`predict()` is what lets a
caller (e.g. `WebApi`) optionally hand over already-fetched rows instead
of forcing every call to hit the database — but a model implementation is
just as free to call `persistance.<domain>` itself when `data` is `None`,
exactly like the example above.
Each domain's available repositories (`paciente_repository`,
`citologia_cervical_repository`, etc.) and how to extend one with
table-specific business logic are documented in
`../Persistance/README.md`.
## Riesgos (ADR-MD-008)
`models/riesgo.py` es el contrato con que Orquestacion pide riesgos a un modelo: `EstimadorDeRiesgo`
(recibe el marco ancho de un armado de cohorte y devuelve un `Riesgo` por miembro y horizonte, más su
`Procedencia`, las llaves para conciliar con MLflow). `RiesgoSintetico` es un sustituto determinista, sin
MLflow, para pruebas y para desplegar sin el modelo real; no es un modelo clínico. El modelo real
(Modelo-cacu, con su artefacto de MLflow) entra como otra clase que cumple el contrato (MD-Q6).
-21
View File
@@ -1,21 +0,0 @@
from abc import ABC, abstractmethod
from typing import Any
class ScreeningModel(ABC):
"""Standard train()/predict() interface every screening model implements,
regardless of which of the three data marts (CaCu/CaMa/TEA) it targets.
Implementations are free to pull their own data straight from
`persistance.<domain>` — the same standard repository API WebApi uses —
or accept already-fetched rows from a caller; `data` is intentionally
untyped at this scaffolding stage.
"""
@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."""
-19
View File
@@ -1,19 +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.
"""
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
}
+200
View File
@@ -0,0 +1,200 @@
"""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),
"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),
"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
-19
View File
@@ -1,19 +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.
"""
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]))
+108
View File
@@ -0,0 +1,108 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
import importlib
from datetime import date
import dagster as dg
from models import graph
from models.jobs import EmptyCohort
from persistance import config_log, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
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 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)
@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
found = {}
for name in config.models or jobs.JOBS.routine():
try:
found[name] = jobs.train(name, as_of)
except EmptyCohort as e: # the site has no such patients; the others still train
found[name] = None
context.log.warning(f"{e}: not trained")
continue
context.log.info(f"{config.domain}.{name}: version {found[name]}")
return found
@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
@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)."""
found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed")
return found
@dg.job(tags=WRITES)
def analyze():
analyze_studies()
defs = dg.Definitions(jobs=[ingest, train, score, analyze])
+432
View File
@@ -0,0 +1,432 @@
"""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,
Extract,
Fhir,
Join,
Link,
Map,
Pipeline,
Read,
Route,
Target,
answer_schema,
apply_patterns,
ground,
join,
map_row,
matches,
validate,
)
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},
}
@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_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."""
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()
held = json.dumps(["records of this person disagree on birth date or sex"])
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: held if r.cluster_id in torn 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()
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."""
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
if not reasons[int(r.match_key)].endswith("typo apart"):
return a, b
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, "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
-176
View File
@@ -1,176 +0,0 @@
"""El contrato con que se le pide a un modelo el riesgo de los miembros de una cohorte (ADR-MD-008).
Quien llama (la arista `estimar` de Orquestacion) le da al estimador el marco de un armado
de cohorte, ancho: `(columnas, filas)`, con `columnas = ["pac_id", "fecha_indice", <variables>]`
(lo que devuelve `indicadores_kit.cohortes.armado.leer_marco`). El estimador devuelve un
`Riesgo` por miembro y horizonte, y su `Procedencia`: las llaves con que se concilia con
MLflow (opción A del prototipo; MLflow no guarda filas ni pacientes).
Este módulo no importa al kit, a Persistance ni a Orquestacion: recibe listas.
"""
import hashlib
import json
from dataclasses import asdict, dataclass
from typing import NamedTuple, Protocol, runtime_checkable
class Riesgo(NamedTuple):
"""El riesgo de un miembro a un horizonte (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # años desde la fecha índice; 0 = prevalente
probabilidad: float # de 0 a 1
ic_bajo: float | None = None
ic_alto: float | None = None
@dataclass(frozen=True)
class Procedencia:
"""De qué modelo salen los riesgos: las llaves que guarda el lote (`PROCEDENCIA` de Persistance)."""
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str
def como_dict(self) -> dict[str, str]:
return asdict(self)
@runtime_checkable
class EstimadorDeRiesgo(Protocol):
"""Lo que cumple todo modelo de riesgo que Orquestacion puede llamar."""
cohorte_url: str # la cohorte cuyo marco consume ("cacu/cohorte_vigilancia")
desenlace: str # lo que predice ("cin2_mas")
def procedencia(self) -> Procedencia: ...
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: ...
# La regla del sustituto: una probabilidad base y lo que suma cada predictor basal.
REGLA_SINTETICA = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
PAP_NORMALES = ("NORMAL",)
class RiesgoSintetico:
"""Un estimador sustituto determinista, sin MLflow: para pruebas y para desplegar sin el modelo real.
La probabilidad sale de una tabla fija por los predictores basales: `REGLA_SINTETICA["base"]`,
más `pap_anormal` si `pap_0` no es `NORMAL` ni nulo, más `vph_positivo` si `hpv_0` es
`POSITIVO`, con tope. Sin intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "cacu/cohorte_vigilancia", desenlace: str = "cin2_mas",
horizontes: tuple[float, ...] = (0.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA, "pap_normales": PAP_NORMALES, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
faltan = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_pap, i_vph = (columnas.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
riesgos = []
for fila in filas:
p = REGLA_SINTETICA["base"]
if fila[i_pap] is not None and fila[i_pap] not in PAP_NORMALES:
p += REGLA_SINTETICA["pap_anormal"]
if fila[i_vph] == "POSITIVO":
p += REGLA_SINTETICA["vph_positivo"]
p = min(p, REGLA_SINTETICA["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
# La regla del sustituto de TEA: lo que suma la interpretación del M-CHAT índice y lo perinatal.
REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05,
"apgar_corte": 7, "tope": 0.95}
class RiesgoSinteticoTea:
"""El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow.
La probabilidad de un diagnóstico de TEA al horizonte (4 años = 48 meses, el de la cohorte) es
`REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si
`ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin
intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d",
horizontes: tuple[float, ...] = (4.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA_TEA, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow",
modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
necesarias = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min")
faltan = [c for c in necesarias if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_mchat, i_ucin, i_apgar = (columnas.index(c) for c in necesarias)
r = REGLA_SINTETICA_TEA
riesgos = []
for fila in filas:
p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(fila[i_mchat], 0.0)
if fila[i_ucin] == 1:
p += r["ucin"]
if fila[i_apgar] is not None and fila[i_apgar] < r["apgar_corte"]:
p += r["apgar_bajo"]
p = min(p, r["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
# La regla del sustituto de CaMa: lo que suma el BI-RADS índice.
REGLA_SINTETICA_CAMA = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80,
"tope": 0.95}
BIRADS_SUSPECHA = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4",
"B4C": "birads_4", "B5": "birads_5"}
class RiesgoSinteticoCama:
"""El sustituto determinista de CaMa, sobre el marco de `cama/cohorte_tamizaje` (T-21g). Sin MLflow.
La probabilidad de cáncer de mama por biopsia al horizonte (1 año, el de la cohorte) es
`REGLA_SINTETICA_CAMA["base"]` más lo que suma la categoría del BI-RADS índice (`birads_0`), con
tope. Las subcategorías 4A, 4B y 4C suman como 4. Sin intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "cama/cohorte_tamizaje", desenlace: str = "d",
horizontes: tuple[float, ...] = (1.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA_CAMA, "birads": BIRADS_SUSPECHA, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow",
modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
faltan = [c for c in ("pac_id", "birads_0") if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_birads = columnas.index("pac_id"), columnas.index("birads_0")
r = REGLA_SINTETICA_CAMA
riesgos = []
for fila in filas:
p = min(r["base"] + r.get(BIRADS_SUSPECHA.get(fila[i_birads]), 0.0), r["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
+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,
}
-19
View File
@@ -1,19 +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.
"""
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)
+135
View File
@@ -0,0 +1,135 @@
"""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
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]
def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
if len(edf) < 256:
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
try:
signals = edfio.read_edf(edf, lazy_load_data=True).signals
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
if not signals:
raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
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
+62
View File
@@ -0,0 +1,62 @@
"""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 worker processes; `tables` gives each scenario's training table
from the valid studies.
"""
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import pandas as pd
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]) -> dict:
key, path, age = 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 = 4) -> list[dict]:
"""Each study's verdict and features, in listing order."""
context = multiprocessing.get_context("spawn")
with ProcessPoolExecutor(workers, mp_context=context) as pool:
return list(pool.map(_one, studies))
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
+141
View File
@@ -0,0 +1,141 @@
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
or ages table that changes is measured again."""
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 joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
from models.tea.eeg import analysis, curves, reference
from persistance import eeg, registry, silver
MODELS = curves.SCENARIOS
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
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(edf: str, birth) -> tuple[str, analysis.Analysis]:
return edf, analysis.analyze(eeg.signal(edf), birth)
def analyze() -> int:
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
pending = eeg.pending()
found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"])
for r in pending)) # fmt: skip
get_reusable_executor().shutdown(wait=True)
eeg.save_analyses(found)
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
return len(found)
def _reference() -> tuple[str, list[dict]]:
"""The reference cohort's hash and each study's verdict and features, cached."""
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
studies = reference.listing(folder, ages)
digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest()
cache = os.environ.get("TEA_REFERENCE_CACHE")
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
if path and path.exists():
return digest, json.loads(path.read_text())
measured = reference.measure(studies, workers=os.cpu_count() or 4)
measured = [{**m, "key": str(m["key"])} for m in measured]
if path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(measured))
return digest, measured
@dataclass(frozen=True)
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) -> 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 = _reference()
table = 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": reference.NAME, "cohort_sha256": digest, "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": reference.NAME, "cohort_sha256": digest}
reports = {"technical_validation": technical, "interpretability": interpretability}
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
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
+28 -15
View File
@@ -1,23 +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",
"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",
]
[tool.uv.sources]
persistance = { path = "../Persistance", 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",
]
[tool.uv.build-backend]
module-name = "models"
module-root = ""
[tool.uv.sources]
core = { workspace = true }
persistance = { workspace = true }
+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)
+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
+101
View File
@@ -0,0 +1,101 @@
"""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("archivos", site_url, "ArchivosUni", schema="dbo"),
table("subrogados", site_url, "ResultadosSubrogados", schema="dbo"),
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
{
"id": "subrogados_text",
"kind": "read",
"inputs": ["subrogados"],
"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(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
expected = {
"archivos": len(by_place["ArchivosUni"]),
"subrogados": len(by_place["ResultadosSubrogados"]),
"archivos_text": len(by_place["ArchivosUni"]),
"subrogados_text": len(by_place["ResultadosSubrogados"]),
}
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, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_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)
+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
-105
View File
@@ -1,105 +0,0 @@
"""El contrato `EstimadorDeRiesgo` y el estimador sustituto (ADR-MD-008)."""
import pytest
from models import riesgo
from models.riesgo import (
REGLA_SINTETICA_CAMA,
REGLA_SINTETICA_TEA,
EstimadorDeRiesgo,
Riesgo,
RiesgoSintetico,
RiesgoSinteticoCama,
RiesgoSinteticoTea,
)
COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"]
FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)]
def test_el_sustituto_cumple_el_contrato():
assert isinstance(RiesgoSintetico(), EstimadorDeRiesgo)
def test_un_riesgo_por_miembro_y_horizonte_en_el_orden_del_marco():
riesgos = RiesgoSintetico(horizontes=(0.0, 1.0)).estimar(COLUMNAS, FILAS)
assert [(r.pac_id, r.horizonte_anios) for r in riesgos] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)]
assert all(isinstance(r, Riesgo) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in riesgos)
def test_la_regla_suma_por_predictor_basal():
p = {r.pac_id: r.probabilidad for r in RiesgoSintetico().estimar(COLUMNAS, FILAS)}
assert p == {1: 0.01, 2: 0.16, 3: 0.01}
def test_es_determinista():
a, b = RiesgoSintetico(), RiesgoSintetico()
assert a.estimar(COLUMNAS, FILAS) == b.estimar(COLUMNAS, FILAS)
assert a.procedencia() == b.procedencia()
def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monkeypatch):
procedencia = RiesgoSintetico().procedencia()
assert set(procedencia.como_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"}
assert all(procedencia.como_dict().values())
monkeypatch.setitem(riesgo.REGLA_SINTETICA, "vph_positivo", 0.2)
assert RiesgoSintetico().procedencia().modelo_sha != procedencia.modelo_sha
def test_sin_los_predictores_falla_y_los_nombra():
with pytest.raises(ValueError, match="pap_0"):
RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)])
# --- El sustituto de TEA (T-21f) ---------------------------------------------------------------
COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes",
"hipoacusia_0"]
def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte():
estimador = RiesgoSinteticoTea()
assert isinstance(estimador, EstimadorDeRiesgo)
assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (4.0,)
def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo():
filas = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None),
(2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"),
(3, None, None, None, None, None, None, 0, None)]
r = REGLA_SINTETICA_TEA
assert [x.probabilidad for x in RiesgoSinteticoTea().estimar(COLUMNAS_TEA, filas)] == pytest.approx(
[r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]])
def test_el_sustituto_de_tea_sin_sus_predictores_falla():
with pytest.raises(ValueError, match="mchat_0"):
RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], [])
# --- El sustituto de CaMa (T-21g) --------------------------------------------------------------
COLUMNAS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"]
def test_el_sustituto_de_cama_cumple_el_contrato_y_lee_su_cohorte():
estimador = RiesgoSinteticoCama()
assert isinstance(estimador, EstimadorDeRiesgo)
assert estimador.cohorte_url == "cama/cohorte_tamizaje" and estimador.horizontes == (1.0,)
def test_la_regla_de_cama_suma_por_birads_indice_y_4a_cuenta_como_4():
filas = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0),
(3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)]
r = REGLA_SINTETICA_CAMA
assert [x.probabilidad for x in RiesgoSinteticoCama().estimar(COLUMNAS_CAMA, filas)] == pytest.approx(
[r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]])
def test_el_sustituto_de_cama_sin_su_predictor_falla():
with pytest.raises(ValueError, match="birads_0"):
RiesgoSinteticoCama().estimar(["pac_id", "fecha_indice"], [])
+175
View File
@@ -0,0 +1,175 @@
"""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
two SQL Server tables, the institute's forms and 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.
"""
import json
from collections import Counter
from datetime import date
from core import catalog
GYN = ("gyn_puerperium", "gyn_pregnancy", "gyn_iud",
"gyn_hormonal_treatment", "gyn_other_treatment",
"gyn_postmenopause", "gyn_hysterectomy", "gyn_not_applicable")
PRESENTS = ("presents_discharge", "presents_vulvar_pruritus",
"presents_abnormal_bleeding", "presents_none")
CYTO = ("cyto_inflammation", "cyto_reactive_changes",
"cyto_bacterial_vaginosis_flora", "cyto_candida",
"cyto_bacillary_flora_cytolysis", "cyto_intermediate_cytolysis",
"cyto_trichomonas", "cyto_leptothrix",
"cyto_actinomyces_organisms", "cyto_actinomyces_changes",
"cyto_herpes_simplex_changes", "cyto_squamous_tubular_metaplasia",
"cyto_keratotic_changes", "cyto_pregnancy_changes",
"cyto_atrophy", "cyto_hypoestrogenism",
"cyto_radiotherapy_effect", "cyto_iud_changes",
"cyto_post_hysterectomy_glandular_cells",
"cyto_bacteria", "cyto_herpes_image",
"cyto_fungi", "cyto_radiation",
"cyto_repair", "cyto_iud_effect",
"cyto_endometrial_cells_40_plus", "cyto_findings_none")
FIELDS = {
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18", "cyto_findings_text", *CYTO),
"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"),
} # fmt: skip
BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS, *CYTO}
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.
members: dict[str, set] = {}
held, person_of = set(), {}
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
members.setdefault(person, set()).add(of[record])
person_of[record] = person
if why:
held.add(person)
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}
# 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 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).
at = {r["where"]: r for r in truth}
place = {
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
}
place |= {r: f"ResultadosSubrogados:{i}"
for i, r in q("select id, _record from bronze.n__site__subrogados")} # 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 = 0
missed: Counter = Counter()
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}
assert got == {f: value(f, truly.get(f)) for f in got}, (t["where"], got)
stated, read = stated + len(truly), read + len(got)
missed.update(set(truly) - set(got))
assert read >= 0.95 * stated, (entity, read, stated, missed)
# 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:
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 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} # 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}")