C1a: code only, no comments, no Markdown

Remove 212 Python docstrings and 118 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files.

Preserve the existing executable statements and lint pragmas. Use pass for class bodies that previously consisted of only a docstring.
This commit is contained in:
2026-12-01 16:55:32 -06:00
parent e42f6a34b2
commit 24534606f1
32 changed files with 88 additions and 760 deletions
+2 -20
View File
@@ -1,14 +1,10 @@
"""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 numpy as np
import pandas as pd import pandas as pd
from core import cacu from core import cacu
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports RESULTS = ("bethesda", "glandular", "hpv")
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over REFERRED = ("colposcopy", "biopsy")
MISSING = "(none)" MISSING = "(none)"
@@ -23,7 +19,6 @@ def days(events: pd.DataFrame) -> pd.Series:
def _worst(codes: pd.Series, cytology: dict) -> pd.Series: 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} rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
names = list(cytology) names = list(cytology)
worst = codes.map(rank).groupby(level=0).max() worst = codes.map(rank).groupby(level=0).max()
@@ -31,7 +26,6 @@ def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series: 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() first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
before = (events["person_id"].map(first) - events["date"]).dt.days before = (events["person_id"].map(first) - events["date"]).dt.days
near = events[before.between(0, history["lookback_days"])] near = events[before.between(0, history["lookback_days"])]
@@ -46,9 +40,6 @@ def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) ->
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None): 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)] near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
wide = near.sort_values("date", kind="stable").pivot_table( wide = near.sort_values("date", kind="stable").pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first" index="person_id", columns="type", values="value_code", aggfunc="first"
@@ -64,8 +55,6 @@ def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = N
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame: 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] timed = events.assign(days=d.astype(float))[d >= 0]
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)] biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
visits = None visits = None
@@ -86,9 +75,6 @@ def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.Data
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict, def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
history: dict | None = None) -> pd.DataFrame: # fmt: skip 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) d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0) outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min() first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
@@ -110,7 +96,6 @@ def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
def last_screening_cytology(events: pd.DataFrame) -> pd.Series: 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"]) referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
key = ["person_id", "source_table", "source_id"] key = ["person_id", "source_table", "source_id"]
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred), samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
@@ -126,14 +111,12 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test."""
ordered = members.sort_values(["index_date", "person_id"], kind="stable") ordered = members.sort_values(["index_date", "person_id"], kind="stable")
cut = int(len(ordered) * train_fraction) cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut], ordered.iloc[cut:] return ordered.iloc[:cut], ordered.iloc[cut:]
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame: 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 = events.groupby(["person_id", "index_date"], as_index=False).size()
members = members[["person_id", "index_date"]] members = members[["person_id", "index_date"]]
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])] sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
@@ -153,7 +136,6 @@ def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float, def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip 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 window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window) outcome &= days(events).between(0, window)
-2
View File
@@ -1,5 +1,3 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
from models.cacu import reports from models.cacu import reports
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
+3 -30
View File
@@ -1,12 +1,3 @@
"""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 from dataclasses import dataclass
import numpy as np import numpy as np
@@ -18,13 +9,12 @@ from scipy.stats import norm
from sklearn.base import BaseEstimator from sklearn.base import BaseEstimator
UNKNOWN = -999 UNKNOWN = -999
TINY = 1e-12 # floor inside every log TINY = 1e-12
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated FROZEN = 15.0
HESSIAN_STEP = 1e-4 HESSIAN_STEP = 1e-4
def ispline_basis(t, degree: int, knots) -> np.ndarray: 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) 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)] 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]) inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
@@ -37,8 +27,6 @@ def ispline_basis(t, degree: int, knots) -> np.ndarray:
@dataclass(frozen=True) @dataclass(frozen=True)
class ISpline: class ISpline:
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
knots: tuple[float, ...] knots: tuple[float, ...]
degree: int degree: int
@@ -55,12 +43,9 @@ class ISpline:
return ispline_basis(t, self.degree, self.knots) @ np.exp(params) return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
def start(self, c, l, r) -> np.ndarray: 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) at_risk, finite = c != 1, np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum() exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).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))) 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)) return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
@@ -88,7 +73,6 @@ def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray: def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
"""Central-difference Hessian of f at x."""
p = len(x) p = len(x)
out = np.zeros((p, p)) out = np.zeros((p, p))
for i in range(p): for i in range(p):
@@ -103,7 +87,6 @@ def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray: def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
"""Prevalence coefficients from the patients whose index status is known."""
known = c != UNKNOWN known = c != UNKNOWN
if not known.any(): if not known.any():
return np.zeros(X.shape[1]) return np.zeros(X.shape[1])
@@ -122,12 +105,11 @@ class Fit:
n_z: int n_z: int
baseline: ISpline baseline: ISpline
params: np.ndarray params: np.ndarray
covariance: np.ndarray # NaN where a parameter is frozen covariance: np.ndarray
neg_loglik: float neg_loglik: float
converged: bool converged: bool
def risk(self, X, Z, years, params=None) -> np.ndarray: 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 p = self.params if params is None else params
theta, beta, rest = ( theta, beta, rest = (
p[: self.n_x], p[: self.n_x],
@@ -141,7 +123,6 @@ class Fit:
]) # fmt: skip ]) # fmt: skip
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]: 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))) gradient = np.empty((len(self.params), len(X), len(years)))
for k, value in enumerate(self.params): for k, value in enumerate(self.params):
step = 1e-5 * max(1.0, abs(value)) step = 1e-5 * max(1.0, abs(value))
@@ -155,7 +136,6 @@ class Fit:
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: 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] n_x, n_z = X.shape[1], Z.shape[1]
start = baseline.start(c, l, r) 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]] starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
@@ -174,10 +154,6 @@ def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
class Mixture(BaseEstimator): 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, def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
interval_level=0.95): # fmt: skip interval_level=0.95): # fmt: skip
self.horizons_years = horizons_years self.horizons_years = horizons_years
@@ -222,7 +198,6 @@ class Mixture(BaseEstimator):
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups] return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
def fit(self, X: pd.DataFrame, y: pd.DataFrame): 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)], rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
axis=1).assign(w=1.0) # fmt: skip axis=1).assign(w=1.0) # fmt: skip
self.fits_, self.seen_ = {}, {} self.fits_, self.seen_ = {}, {}
@@ -241,8 +216,6 @@ class Mixture(BaseEstimator):
return self return self
def predict(self, X: pd.DataFrame) -> np.ndarray: 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) h = len(self.horizons_years)
out = np.full((len(X), 3 * h), np.nan) out = np.full((len(X), 3 * h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2) z = norm.ppf(0.5 + self.interval_level / 2)
+1 -14
View File
@@ -1,14 +1,3 @@
"""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 numpy as np
import pandas as pd import pandas as pd
from scipy.stats import norm from scipy.stats import norm
@@ -18,7 +7,7 @@ from models import survival
from models.cacu.pim import Mixture from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim from models.cacu.specs import Logistic, Pim
GRID_STEP = 0.1 # years between points of a curve GRID_STEP = 0.1
BOOTSTRAP = 200 BOOTSTRAP = 200
SEED = 20261122 SEED = 20261122
Z = norm.ppf(0.975) Z = norm.ppf(0.975)
@@ -40,8 +29,6 @@ def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, da
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10): 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)] finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]])) 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) low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)
+1 -17
View File
@@ -1,7 +1,3 @@
"""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 dataclasses import dataclass, field
from typing import Literal from typing import Literal
@@ -23,7 +19,6 @@ OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame: 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) h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1) scored = ~np.isnan(risks[:, :h]).any(axis=1)
members, risks = members[scored], risks[scored] members, risks = members[scored], risks[scored]
@@ -43,15 +38,13 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
@dataclass(frozen=True) @dataclass(frozen=True)
class Pim: class Pim:
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
name: str name: str
cohort: str cohort: str
grades: list[str] grades: list[str]
cytology: dict[str, list[str]] cytology: dict[str, list[str]]
strata: tuple[str, ...] strata: tuple[str, ...]
incidence_features: tuple[str, ...] incidence_features: tuple[str, ...]
history: dict | None = None # a feature from before the index (the referral grade) history: dict | None = None
predict_at: Literal["index", "last_screening_cytology"] = "index" predict_at: Literal["index", "last_screening_cytology"] = "index"
horizons: tuple[float, ...] = HORIZONS horizons: tuple[float, ...] = HORIZONS
method: str = field(default="prevalence-incidence mixture", init=False) method: str = field(default="prevalence-incidence mixture", init=False)
@@ -64,8 +57,6 @@ class Pim:
return self.history and {**self.history, "cytology": self.cytology} return self.history and {**self.history, "cytology": self.cytology}
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]: 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) events = f.prepared(events)
coded = f.interval_coded(events, self.grades, self.cytology, self._history()) coded = f.interval_coded(events, self.grades, self.cytology, self._history())
train, test = f.split(coded, TRAIN_FRACTION) train, test = f.split(coded, TRAIN_FRACTION)
@@ -80,7 +71,6 @@ class Pim:
found = { found = {
"n_train": len(train), "n_train": len(train),
"n_test": len(test), "n_test": len(test),
# outcomes, prevalent or incident, each split learned from or was judged on
"events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()), "events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()),
"events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()), "events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()),
"neg_loglik": mixture.neg_loglik_, "neg_loglik": mixture.neg_loglik_,
@@ -115,8 +105,6 @@ class Pim:
@dataclass(frozen=True) @dataclass(frozen=True)
class Logistic: class Logistic:
"""Probability of the outcome within one year of the index sample."""
name: str name: str
cohort: str cohort: str
grades: list[str] grades: list[str]
@@ -125,8 +113,6 @@ class Logistic:
method: str = field(default="logistic regression", init=False) method: str = field(default="logistic regression", init=False)
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]: 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) events = f.prepared(events)
found = f.index_sample(events, list(self.predictors)) found = f.index_sample(events, list(self.predictors))
outcome = f.windowed_outcome(events, self.grades, self.years, outcome = f.windowed_outcome(events, self.grades, self.years,
@@ -160,8 +146,6 @@ class Logistic:
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's most recent observations up to her index (that day included): her age
group, the KPNC category of her latest cytology result and her latest HPV result."""
found = pd.DataFrame(index=members.index) found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (35, 45, 55)) found["age_group"] = age_group(events, members, (35, 45, 55))
prior = events[events["date"] <= events["index_date"]] prior = events[events["date"] <= events["index_date"]]
-2
View File
@@ -1,5 +1,3 @@
"""CaMa's training and scoring jobs (models.jobs) over its models and their reports."""
from models import survival from models import survival
from models.cama.specs import MODELS from models.cama.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
+1 -19
View File
@@ -1,10 +1,3 @@
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
from the site's own patients (site). Per 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."""
from dataclasses import dataclass from dataclasses import dataclass
import joblib import joblib
@@ -13,23 +6,17 @@ import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
HORIZONS = modeling.HORIZONS # months HORIZONS = modeling.HORIZONS
@dataclass @dataclass
class Recurrence: 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 cohort: str
horizons: tuple[int, ...] horizons: tuple[int, ...]
covariates: list[str] covariates: list[str]
tables: dict[int, dict] tables: dict[int, dict]
def predict(self, X: pd.DataFrame) -> pd.DataFrame: 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 = X[self.covariates].astype(object)
found = found.where(found.notna(), cohorts.UNKNOWN).astype(str) found = found.where(found.notna(), cohorts.UNKNOWN).astype(str)
dummies = pd.get_dummies(found).astype(float) dummies = pd.get_dummies(found).astype(float)
@@ -50,9 +37,6 @@ class Recurrence:
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
factors' stability criterion, are then missing)."""
from models.cama.recurrence import site from models.cama.recurrence import site
return fit({"site": site.prepare(rows)}, "site", "site", return fit({"site": site.prepare(rows)}, "site", "site",
@@ -61,8 +45,6 @@ def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence,
def fit(found: dict, saved: str, label: str, def fit(found: dict, saved: str, label: str,
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
"""The models of each prepared cohort, their validation, calculator and risk factors;
the `saved` cohort's is the model kept."""
sources = list(found) sources = list(found)
try: try:
fits = modeling.fit(found, n_bootstrap) fits = modeling.fit(found, n_bootstrap)
+5 -20
View File
@@ -1,12 +1,3 @@
"""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 from dataclasses import dataclass
import numpy as np import numpy as np
@@ -18,9 +9,9 @@ from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
RESAMPLES = 200 RESAMPLES = 200
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences MIN_EVENTS = 15
CAP_MONTHS = 72 # the Weibull curves' extent CAP_MONTHS = 72
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months GRID_POINTS = 289
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
@@ -32,8 +23,6 @@ def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
@dataclass @dataclass
class Risk: class Risk:
"""The cohort coded once: dummies for the LR, integer codes for the HBN."""
fitted: CohortFit fitted: CohortFit
def __post_init__(self): def __post_init__(self):
@@ -51,7 +40,6 @@ class Risk:
return key return key
def _combined(self, rows, horizon) -> np.ndarray | None: 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] t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon) recurred = (e == 1) & (t <= horizon)
known = recurred | (t > horizon) known = recurred | (t > horizon)
@@ -75,8 +63,6 @@ class Risk:
return (p_lr + p_hbn) / 2 return (p_lr + p_hbn) / 2
def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None: 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} out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks}
for j, h in enumerate(HORIZONS): for j, h in enumerate(HORIZONS):
combined = self._combined(rows, h) combined = self._combined(rows, h)
@@ -105,18 +91,17 @@ def _curves(months, event, observed):
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]: def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
"""The figure record of each scenario with enough recurrences, and its table rows."""
source = fitted.cohort.source source = fitted.cohort.source
scenarios = fitted.cohort.scenarios scenarios = fitted.cohort.scenarios
risk = Risk(fitted) risk = Risk(fitted)
found = masks(fitted.cohort.frame, scenarios) found = masks(fitted.cohort.frame, scenarios)
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel rng = np.random.default_rng(SEED)
samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)] samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)]
months = np.floor(risk.time).astype(int) months = np.floor(risk.time).astype(int)
event = risk.event == 1 event = risk.event == 1
drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS} 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(_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 jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples]
done = Parallel(n_jobs=-1)(jobs) done = Parallel(n_jobs=-1)(jobs)
fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :] fitted_curves, (point, *resampled) = done[: len(drawn)], done[len(drawn) :]
replicas = [r for r in resampled if r is not None] replicas = [r for r in resampled if r is not None]
+5 -20
View File
@@ -1,9 +1,3 @@
"""A cohort as one table of categories: 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 from dataclasses import dataclass
import pandas as pd import pandas as pd
@@ -12,9 +6,8 @@ from scipy.stats.contingency import association
UNKNOWN = "Desconocido" UNKNOWN = "Desconocido"
V_MAX = 0.80 V_MAX = 0.80
DAYS_PER_MONTH = 30.4375 DAYS_PER_MONTH = 30.4375
HORIZONS = (12, 36, 60) # months HORIZONS = (12, 36, 60)
# Bands, closed on the left: [a, b).
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]) SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"]) NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
@@ -26,7 +19,6 @@ def _number(s: pd.Series) -> pd.Series:
def _text(s: pd.Series) -> pd.Series: def _text(s: pd.Series) -> pd.Series:
"""As text; missing values are UNKNOWN."""
return s.astype(object).where(s.notna(), UNKNOWN).astype(str) return s.astype(object).where(s.notna(), UNKNOWN).astype(str)
@@ -40,9 +32,6 @@ def cramers_v(a: pd.Series, b: pd.Series) -> float:
def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]: 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( pairs = sorted(
( (
(cramers_v(frame[a], frame[b]), a, b) (cramers_v(frame[a], frame[b]), a, b)
@@ -63,16 +52,14 @@ def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX)
@dataclass(frozen=True) @dataclass(frozen=True)
class Cohort: class Cohort:
"""A source's cohort table and what its covariates are."""
source: str source: str
frame: pd.DataFrame # fixed columns, then the kept covariates frame: pd.DataFrame
covariates: list[str] covariates: list[str]
treatment: list[str] treatment: list[str]
eliminated: list[str] eliminated: list[str]
label: str # as the reports name it label: str
scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories scenarios: dict
sampling: dict # how its patients were chosen (the MUESTREO record) sampling: dict
@property @property
def intrinsic(self) -> list[str]: def intrinsic(self) -> list[str]:
@@ -80,8 +67,6 @@ class Cohort:
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
"""The patients whose status at `horizon` months is known (a recurrence by then, or
followed past it), with `y` = recurred by then."""
t, event = frame["tiempo_meses"], frame["evento"] == 1 t, event = frame["tiempo_meses"], frame["evento"] == 1
found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True) found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True)
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int) found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
+1 -10
View File
@@ -1,7 +1,3 @@
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has
(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2),
the horizon's HBN parents give (3))."""
import warnings import warnings
import numpy as np import numpy as np
@@ -81,14 +77,11 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame: 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: if selection is None:
covariates = fitted.cohort.covariates covariates = fitted.cohort.covariates
selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()} selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()}
with warnings.catch_warnings(), np.errstate(over="ignore"): with warnings.catch_warnings(), np.errstate(over="ignore"):
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios warnings.simplefilter("ignore")
found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons] found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons]
tab = pd.concat(found, ignore_index=True) tab = pd.concat(found, ignore_index=True)
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
@@ -99,8 +92,6 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
"""Per scenario and horizon, the classified factors and treatments nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
frame, source = fitted.cohort.frame, fitted.cohort.source frame, source = fitted.cohort.frame, fitted.cohort.source
scenarios = fitted.cohort.scenarios scenarios = fitted.cohort.scenarios
found = rated.classified(factors[factors["cohorte"] == source]) found = rated.classified(factors[factors["cohorte"] == source])
+2 -47
View File
@@ -1,12 +1,3 @@
"""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 import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
@@ -25,27 +16,21 @@ from models.factors import variable_of
SEED = 42 SEED = 42
TEST_SIZE = 0.3 TEST_SIZE = 0.3
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count ESS = 10
MAX_PARENTS = 6 MAX_PARENTS = 6
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15 ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
MAX_STEPS = 200 MAX_STEPS = 200
COX_PENALIZER = 0.05 COX_PENALIZER = 0.05
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side COX_MIN_COUNT = 10
N_BOOTSTRAP = {"site": 40} N_BOOTSTRAP = {"site": 40}
# ---------------------------------------------------------------- logistic regression
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: 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) X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1] return X.loc[:, X.nunique() > 1]
def logit(y, X: pd.DataFrame, has_constant: str = "skip"): def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
"""Maximum-likelihood logistic regression with an intercept, or None when it fails."""
try: try:
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
@@ -56,8 +41,6 @@ def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
def stepwise(X: pd.DataFrame, y) -> list[str]: 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 = [] included = []
for _ in range(MAX_STEPS): for _ in range(MAX_STEPS):
changed, best, best_p = False, None, ALPHA_IN changed, best, best_p = False, None, ALPHA_IN
@@ -81,8 +64,6 @@ def stepwise(X: pd.DataFrame, y) -> list[str]:
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]): 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 = encode(pd.concat([train, test]), covariates)
X_train = X.loc[train.index] X_train = X.loc[train.index]
X_train = X_train.loc[:, X_train.nunique() > 1] X_train = X_train.loc[:, X_train.nunique() > 1]
@@ -100,9 +81,6 @@ def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
return terms, m.predict(X_test).to_numpy() return terms, m.predict(X_test).to_numpy()
# ---------------------------------------------------------------- Bayesian network
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
table = frame[covariates].astype(str) table = frame[covariates].astype(str)
table["outcome"] = frame["y"].astype(int).astype(str) table["outcome"] = frame["y"].astype(int).astype(str)
@@ -110,8 +88,6 @@ def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]: 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) score = BDeu(table, equivalent_sample_size=ESS)
chosen, current = [], score.local_score("outcome", ()) chosen, current = [], score.local_score("outcome", ())
while len(chosen) < MAX_PARENTS: while len(chosen) < MAX_PARENTS:
@@ -128,8 +104,6 @@ def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]: 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])) q = q or int(np.prod([table[p].nunique() for p in chosen]))
a = ESS / (2 * q) a = ESS / (2 * q)
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size") counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
@@ -140,8 +114,6 @@ def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tu
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray: 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() rate = (train["outcome"] == "1").mean()
if not chosen: if not chosen:
return np.full(len(test), rate) return np.full(len(test), rate)
@@ -149,13 +121,8 @@ def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarra
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())]) return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
# ---------------------------------------------------------------- one split, one cohort
@dataclass(frozen=True) @dataclass(frozen=True)
class Split: class Split:
"""The two models' selection and AUC on one 70/30 split."""
terms: list[str] terms: list[str]
parents: list[str] parents: list[str]
auc_lr: float auc_lr: float
@@ -174,8 +141,6 @@ def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> S
def _replicate(frame, covariates, rows, b) -> Split | None: 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: try:
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b) return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
except Exception: except Exception:
@@ -183,8 +148,6 @@ def _replicate(frame, covariates, rows, b) -> Split | None:
def c_index(cohort: Cohort) -> float: 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"] time_event = ["tiempo_meses", "evento"]
X = pd.get_dummies( X = pd.get_dummies(
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
@@ -205,9 +168,6 @@ def c_index(cohort: Cohort) -> float:
@dataclass @dataclass
class Horizon: 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 n: int
events: int events: int
split: Split split: Split
@@ -218,7 +178,6 @@ class Horizon:
return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2) 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: 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: if not self.replicates:
return None return None
counts = {} counts = {}
@@ -236,8 +195,6 @@ class CohortFit:
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]: 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} frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS}
tasks = [] tasks = []
for (s, h), frame in frames.items(): for (s, h), frame in frames.items():
@@ -268,8 +225,6 @@ def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, Co
def tables(fitted: CohortFit) -> dict[int, dict]: 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 = {} found = {}
for h, hz in fitted.horizons.items(): for h, hz in fitted.horizons.items():
frame = at_horizon(fitted.cohort.frame, h) frame = at_horizon(fitted.cohort.frame, h)
-13
View File
@@ -1,8 +1,3 @@
"""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 numpy as np
import pandas as pd import pandas as pd
@@ -34,7 +29,6 @@ AUC_COLUMNS = [
def table(rows, columns=None) -> dict: 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) frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object)
return { return {
"columnas": [str(c) for c in frame.columns], "columnas": [str(c) for c in frame.columns],
@@ -43,8 +37,6 @@ def table(rows, columns=None) -> dict:
def auc_rows(fitted: CohortFit) -> list[dict]: 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, [] source, rows = fitted.cohort.source, []
for h, hz in fitted.horizons.items(): for h, hz in fitted.horizons.items():
for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))): for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))):
@@ -81,8 +73,6 @@ def auc_rows(fitted: CohortFit) -> list[dict]:
def metrics(auc: list[dict]) -> dict[str, float]: 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 = {} found = {}
for r in auc: for r in auc:
if r["horizonte_meses"] == "completo": if r["horizonte_meses"] == "completo":
@@ -96,7 +86,6 @@ def metrics(auc: list[dict]) -> dict[str, float]:
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"""The five routine records a promotion reads."""
return { return {
"MUESTREO": { "MUESTREO": {
"cohortes": { "cohortes": {
@@ -144,7 +133,6 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict: def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict:
"""`recurrencia_desarrollo`: the tables behind the figures."""
return { return {
"version": VERSION, "version": VERSION,
"tablas": { "tablas": {
@@ -157,5 +145,4 @@ def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[di
def figures(records: list[dict]) -> dict: def figures(records: list[dict]) -> dict:
"""`recurrencia`: each scenario's curves and calculator points."""
return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records} return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records}
+2 -27
View File
@@ -1,18 +1,3 @@
"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa
timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy
report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned
from), so the same fits, calculator and risk factors run on it.
- Time and event: months from the index to her first recurrence (any site) after it, else to
her death, else to the cut-off (the site records its recurrences: a patient without one is
taken as free of it up to then); `muerte_sin_recaida` when she died without one.
- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the
first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN):
age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or
more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate:
Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+,
Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them."""
import numpy as np import numpy as np
import pandas as pd import pandas as pd
@@ -21,7 +6,7 @@ from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collin
RESULT_DAYS = 30 RESULT_DAYS = 30
TREATMENT_DAYS = 365 TREATMENT_DAYS = 365
KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B KI67_HIGH = 20.0
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II", 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 "III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
RECEPTOR = {"positive": "Positive", "negative": "Negative"} RECEPTOR = {"positive": "Positive", "negative": "Negative"}
@@ -30,7 +15,6 @@ TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip "Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
TREATMENT = ["Cirugia", *TREATMENTS] TREATMENT = ["Cirugia", *TREATMENTS]
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
SCENARIOS = { SCENARIOS = {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": { "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
@@ -48,7 +32,7 @@ SCENARIOS = {
"Cirugia": ["Lumpectomy"]}, "Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]}, "Grado 3": {"Grado_histologico": ["3"]},
} # fmt: skip } # fmt: skip
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted MIN_PER_CLASS = 10
SAMPLING = { SAMPLING = {
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, " "criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
"libre de ella hasta su defunción o la fecha de corte", "libre de ella hasta su defunción o la fecha de corte",
@@ -57,7 +41,6 @@ SAMPLING = {
def subtype(er, pr, her2, ki67) -> str: def subtype(er, pr, her2, ki67) -> str:
"""The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it."""
hormone = "positive" in (er, pr) hormone = "positive" in (er, pr)
if her2 == "positive": if her2 == "positive":
return "Luminal B HER2+" if hormone else "Non-luminal HER2+" return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
@@ -71,8 +54,6 @@ def subtype(er, pr, her2, ki67) -> str:
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame: def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
"""One row per member: her time, event and covariates, as `cohorts.prepare` gives a
reference cohort's."""
events = events.assign(date=pd.to_datetime(events["date"]), events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip index_date=pd.to_datetime(events["index_date"])) # fmt: skip
members = events.groupby("person_id")["index_date"].first() members = events.groupby("person_id")["index_date"].first()
@@ -122,8 +103,6 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
def scarce(rows: pd.DataFrame) -> str | None: def scarce(rows: pd.DataFrame) -> str | None:
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
patients recurred by it, or known free of it), or None."""
for h in cohorts.HORIZONS: for h in cohorts.HORIZONS:
y = cohorts.at_horizon(rows, h)["y"] y = cohorts.at_horizon(rows, h)["y"]
fewest = min(int(y.sum()), int((y == 0).sum())) fewest = min(int(y.sum()), int((y == 0).sum()))
@@ -134,10 +113,6 @@ def scarce(rows: pd.DataFrame) -> str | None:
def prepare(rows: pd.DataFrame) -> Cohort: def prepare(rows: pd.DataFrame) -> Cohort:
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
scenarios name patients by them (the subtype, built from the receptors and Ki-67, is
redundant by construction)."""
covariates = [c for c in rows.columns if c not in FIXED] covariates = [c for c in rows.columns if c not in FIXED]
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT]) dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
kept = [c for c in covariates if c not in dropped] kept = [c for c in covariates if c not in dropped]
+2 -25
View File
@@ -1,16 +1,3 @@
"""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 the site's patients
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date
@@ -18,16 +5,13 @@ import pandas as pd
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
RESULTS = ("histologic_type", "grade", "er", "pr", "her2") RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
RESULT_DAYS = 30 RESULT_DAYS = 30
TREATMENT_DAYS = 365 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", 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 "III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
SURGERY = ("breast_conserving_surgery", "mastectomy") # the most extensive one counts SURGERY = ("breast_conserving_surgery", "mastectomy")
# 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")) STAGE_0_II, STAGE_III_IV = ("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV"))
HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative") HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative")
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG) TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
@@ -62,8 +46,6 @@ SCENARIOS = {
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: 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 = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (45, 60, 75)) found["age_group"] = age_group(events, members, (45, 60, 75))
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min() birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
@@ -89,13 +71,9 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
@dataclass(frozen=True) @dataclass(frozen=True)
class SiteRecurrence: class SiteRecurrence:
"""The recurrence model on the site's own patients (models.cama.recurrence.site): the
cohort's timelines in, its fits, calculator and risk factors out, with its own reports;
each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in."""
name: str name: str
cohort: str = "cama_cohort_recurrence" cohort: str = "cama_cohort_recurrence"
reports: bool = True # it writes its own reports (models.jobs) reports: bool = True
method: str = field(default="stepwise logistic regression + Bayesian network", init=False) method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
def train(self, events, as_of=None) -> tuple: def train(self, events, as_of=None) -> tuple:
@@ -142,7 +120,6 @@ MODELS = {
"radiotherapy", "radiotherapy",
), ),
covariates=covariates, covariates=covariates,
# As the SEER-trained original: stage, histologic type and the first course, and age.
parents=( parents=(
"stage", "stage",
"histologic_type", "histologic_type",
+5 -34
View File
@@ -1,21 +1,13 @@
"""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 import numpy as np
from scipy.optimize import minimize, minimize_scalar from scipy.optimize import minimize, minimize_scalar
from scipy.special import beta as beta_function from scipy.special import beta as beta_function
from scipy.special import betainc, gammaln from scipy.special import betainc, gammaln
Z = 1.96 Z = 1.96
INVALID = 1e12 # the likelihood outside a model's parameter region INVALID = 1e12
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0): 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) months, event = np.asarray(months, int), np.asarray(event, bool)
length = max(length, int(months.max()) + 2) length = max(length, int(months.max()) + 2)
d = np.bincount(months[event], minlength=length) d = np.bincount(months[event], minlength=length)
@@ -25,7 +17,6 @@ def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
def kaplan_meier(months, event, until: int): 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) d, _, n = life_table(months, event, until + 1)
with np.errstate(divide="ignore", invalid="ignore"): with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
@@ -55,7 +46,6 @@ def weibull(t, k, lam):
def fit_weibull(d, c) -> tuple[float, float]: 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 best = None
for k0 in (0.7, 1.0, 1.5): for k0 in (0.7, 1.0, 1.5):
for l0 in (50.0, 200.0, 1000.0): for l0 in (50.0, 200.0, 1000.0):
@@ -71,9 +61,7 @@ def fit_weibull(d, c) -> tuple[float, float]:
return float(k), float(lam) return float(k), float(lam)
# ---------------------------------------------------------------- fractional Weibull STEPS = 800
STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here)
class NotConverged(RuntimeError): class NotConverged(RuntimeError):
@@ -87,14 +75,6 @@ def _converged(r, what: str):
def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray: 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)) t = np.atleast_1d(np.asarray(t, float))
e = rho + s e = rho + s
top = float(t.max()) if t.size else 0.0 top = float(t.max()) if t.size else 0.0
@@ -112,15 +92,13 @@ def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x)) 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)) ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
slope = (ie - w[:n] * i0) / dw[:n] slope = (ie - w[:n] * i0) / dw[:n]
own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j own, next_ = i0 - slope, slope
known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n]) known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1]) y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1])
return np.interp(t**e, w, y) return np.interp(t**e, w, y)
def fractional(t, k, alpha, beta, lam) -> np.ndarray: 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)) t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2 s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0: if k + alpha <= 1 or s + beta <= 0:
@@ -130,19 +108,12 @@ def fractional(t, k, alpha, beta, lam) -> np.ndarray:
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]: 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))) 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, ...]: 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 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) top = len(d) + 0.5
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5]) months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5])
lambdas = (0.0, np.log(1e7)) lambdas = (0.0, np.log(1e7))
@@ -155,7 +126,7 @@ def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
return INVALID, np.nan return INVALID, np.nan
rho, s, scale = _shape(k, a, b) rho, s, scale = _shape(k, a, b)
e = rho + s e = rho + s
z_top = scale * top**e # lambda = 1 reaches the farthest z_top = scale * top**e
z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1)) 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) g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0)
+5 -12
View File
@@ -1,5 +1,3 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
import hashlib import hashlib
import importlib import importlib
import inspect import inspect
@@ -22,7 +20,7 @@ from models.tea import preview as tea_preview_analysis
from persistance import backup as backups from persistance import backup as backups
from persistance import bundle, cluster, config_log, eeg, previews, silver from persistance import bundle, cluster, config_log, eeg, previews, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite) WRITES = {"writes": "platform"}
class ExecutionConfig(dg.Config): class ExecutionConfig(dg.Config):
@@ -44,12 +42,11 @@ class ScopeConfig(dg.Config):
class PipelineRun(dg.Config): class PipelineRun(dg.Config):
pipeline: str pipeline: str
version: int | None = None # default: the latest saved version: int | None = None
@dg.op @dg.op
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int: 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) version, pipeline = config_log.get(config.pipeline, config.version)
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes") context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
graph.run(config.pipeline, pipeline, log=context.log.info) graph.run(config.pipeline, pipeline, log=context.log.info)
@@ -62,7 +59,6 @@ def ingest():
def _jobs(domain: str): def _jobs(domain: str):
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
try: try:
return importlib.import_module(f"models.{domain}.jobs") return importlib.import_module(f"models.{domain}.jobs")
except ModuleNotFoundError as e: except ModuleNotFoundError as e:
@@ -71,15 +67,14 @@ def _jobs(domain: str):
class Training(dg.Config): class Training(dg.Config):
domain: str domain: str
models: list[str] = [] # default: every model of the domain models: list[str] = []
as_of: str | None = None # the date the data are taken up to (default: today) as_of: str | None = None
execution: ExecutionConfig = ExecutionConfig() execution: ExecutionConfig = ExecutionConfig()
source: dict[str, Any] | None = None source: dict[str, Any] | None = None
@dg.op @dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict: def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports."""
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None as_of = date.fromisoformat(config.as_of) if config.as_of else None
options = {} options = {}
@@ -107,12 +102,11 @@ def train():
class Scoring(dg.Config): class Scoring(dg.Config):
domain: str domain: str
models: list[str] = [] # default: every model of the domain models: list[str] = []
@dg.op @dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict: def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()} found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()}
for name, version in found.items(): for name, version in found.items():
@@ -133,7 +127,6 @@ class Analysis(dg.Config):
@dg.op @dg.op
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int: def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
with execution.running(context, config.execution.model()): with execution.running(context, config.execution.model()):
found = _jobs(config.domain).analyze() found = _jobs(config.domain).analyze()
context.log.info(f"{config.domain}: {found} analysed") context.log.info(f"{config.domain}: {found} analysed")
-29
View File
@@ -1,16 +1,3 @@
"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models.
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes
1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least
FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its
Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's
direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three
criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get
their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations,
not effects. Each clinical scenario then lists the classified factors nearly all of its
patients have (definitorios) or most have (mayoritarios)."""
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import statsmodels.api as sm import statsmodels.api as sm
@@ -30,19 +17,16 @@ ORDER = {
"no concluyente": 4, "no concluyente": 4,
} }
UNKNOWN_CLASS = "no aplica (categoria desconocida)" UNKNOWN_CLASS = "no aplica (categoria desconocida)"
# Scenario presence: the share of the scenario's patients in the category.
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10 DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
DESCRIBING = ("definitoria", "mayoritaria") DESCRIBING = ("definitoria", "mayoritaria")
def variable_of(term: str, covariates: list[str]) -> str: 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 + "_")] found = [c for c in covariates if term.startswith(c + "_")]
return max(found, key=len) if found else term return max(found, key=len) if found else term
def km_at(months, event, horizon) -> tuple[float, float]: 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) d, _, n = life_table(months, event)
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) 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) v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
@@ -52,8 +36,6 @@ def km_at(months, event, horizon) -> tuple[float, float]:
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame: def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
"""Logistic GLM on every category but each covariate's reference (constant and
duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p."""
X = pd.get_dummies(data[variables]).astype(float) X = pd.get_dummies(data[variables]).astype(float)
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables]) X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
X = X.loc[:, X.nunique() > 1] X = X.loc[:, X.nunique() > 1]
@@ -73,9 +55,6 @@ def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.Da
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame, def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
survival columns)."""
table = table.reset_index(drop=True) table = table.reset_index(drop=True)
table["variable"] = [variable_of(x, variables) for x in table["termino"]] table["variable"] = [variable_of(x, variables) for x in table["termino"]]
table["categoria"] = [ table["categoria"] = [
@@ -101,8 +80,6 @@ def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataF
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str, def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
for the criteria `evaluated`."""
risk = tab[or_name] > 1 risk = tab[or_name] > 1
tab["direccion"] = np.where(risk, "riesgo", "protector") tab["direccion"] = np.where(risk, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA) tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
@@ -136,8 +113,6 @@ def presence(share: float) -> str:
def listing(part: pd.DataFrame) -> str: 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", strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
part["clasificacion"].str.split().str[-1]) # fmt: skip part["clasificacion"].str.split().str[-1]) # fmt: skip
return "; ".join( return "; ".join(
@@ -149,8 +124,6 @@ def listing(part: pd.DataFrame) -> str:
def classified(factors: pd.DataFrame) -> pd.DataFrame: def classified(factors: pd.DataFrame) -> pd.DataFrame:
"""The factors a scenario can list (classified ones and treatments), with `tipo_efecto`:
riesgo, protector or tratamiento."""
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")] found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
kind = np.where( kind = np.where(
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0] found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
@@ -159,8 +132,6 @@ def classified(factors: pd.DataFrame) -> pd.DataFrame:
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict: def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
"""What one scenario's patients (`mask` over `frame`) have of the `classified` factors:
the listings by kind and presence, and how many risk factors describe it."""
share = [ share = [
float((frame.loc[mask, v] == c).mean()) float((frame.loc[mask, v] == c).mean())
for v, c in zip(found["variable"], found["categoria"], strict=True) for v, c in zip(found["variable"], found["categoria"], strict=True)
+15 -63
View File
@@ -1,6 +1,3 @@
"""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 hashlib
import io import io
import json import json
@@ -49,9 +46,9 @@ from core.pipeline import (
from models.tea.eeg import read from models.tea.eeg import read
from persistance import config_log, files, nodes, silver from persistance import config_log, files, nodes, silver
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer MIN_WORDS = 5
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done) READ_BATCH = 32
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` READ_COLUMNS = {
"text": {"data_type": "text", "nullable": True}, "text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"}, "ocr": {"data_type": "bool"},
"error": {"data_type": "text", "nullable": True}, "error": {"data_type": "text", "nullable": True},
@@ -80,25 +77,19 @@ def _reader() -> MarkItDown:
def _lines(text: str) -> str: 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()) return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
def _text(content: bytes) -> str: def _text(content: bytes) -> str:
"""Files other than PDFs, through MarkItDown."""
return _reader().convert_stream(io.BytesIO(content)).text_content return _reader().convert_stream(io.BytesIO(content)).text_content
def _pdf_pages(content: bytes) -> list[str]: def _pdf_pages(content: bytes) -> list[str]:
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
on one line each (spacing within a line collapsed)."""
with pdfplumber.open(io.BytesIO(content)) as pdf: with pdfplumber.open(io.BytesIO(content)) as pdf:
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages] return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]: def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
copied into a PDF of their own: a typed page keeps its own text layer."""
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new() source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
for n in numbers: for n in numbers:
scans.pages.append(source.pages[n]) scans.pages.append(source.pages[n])
@@ -114,8 +105,6 @@ def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
def read_file(content: bytes) -> dict: def read_file(content: bytes) -> dict:
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps
its error; a signal recording (EDF) has no text to read."""
kind = file_format(content) kind = file_format(content)
if kind == "edf": if kind == "edf":
return {"text": None, "ocr": False, "error": None, "format": kind} return {"text": None, "ocr": False, "error": None, "format": kind}
@@ -123,8 +112,6 @@ def read_file(content: bytes) -> dict:
def _read_text(content: bytes) -> dict: def _read_text(content: bytes) -> dict:
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
typed form whose second page is a scan, say)."""
try: try:
if not content.startswith(b"%PDF"): if not content.startswith(b"%PDF"):
return {"text": _text(content), "ocr": False, "error": None} return {"text": _text(content), "ocr": False, "error": None}
@@ -134,26 +121,23 @@ def _read_text(content: bytes) -> dict:
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True): for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
pages[i] = page pages[i] = page
return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None} return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal except Exception as e: # noqa: BLE001
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
def run_read(p: str, node: Read): def run_read(p: str, node: Read):
"""The input's rows with their file's text and format beside the file column (which
keeps the file, for a study that takes the file itself: an EEG's recording); each file
read once."""
rows = list(nodes.rows(p, node.inputs[0])) rows = list(nodes.rows(p, node.inputs[0]))
for row in rows: # the source kept the file; the row carries its hash for row in rows:
row["key"] = row.get(node.column) or None row["key"] = row.get(node.column) or None
keys = {r["key"] for r in rows} - {None} keys = {r["key"] for r in rows} - {None}
found = nodes.cached("read_cache", keys) found = nodes.cached("read_cache", keys)
legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats legacy = [k for k, r in found.items() if r.get("format") is None]
for k in legacy: for k in legacy:
found[k]["format"] = file_format(files.content(k) or b"") found[k]["format"] = file_format(files.content(k) or b"")
nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
for k in legacy], READ_COLUMNS) # fmt: skip for k in legacy], READ_COLUMNS) # fmt: skip
new = sorted(keys - set(found)) new = sorted(keys - set(found))
with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept with ProcessPoolExecutor() as pool:
for start in range(0, len(new), READ_BATCH): for start in range(0, len(new), READ_BATCH):
batch = new[start : start + READ_BATCH] batch = new[start : start + READ_BATCH]
read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)), read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
@@ -203,7 +187,6 @@ def run_route(p: str, node: Route, others: list[Route] = ()):
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: 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: if node.concept_map is None:
return {} return {}
found = config_log.concept_map(node.concept_map) found = config_log.concept_map(node.concept_map)
@@ -217,7 +200,6 @@ def run_map(p: str, node: Map):
def run_fhir(p: str, node: Fhir): def run_fhir(p: str, node: Fhir):
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else [] maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
found: dict[str, dict] = {} found: dict[str, dict] = {}
for row in nodes.rows(p, node.inputs[0]): for row in nodes.rows(p, node.inputs[0]):
@@ -234,7 +216,6 @@ def run_join(p: str, node: Join):
@cache @cache
def _llm() -> tuple[OpenAI, str] | None: def _llm() -> tuple[OpenAI, str] | None:
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
if not (url := os.environ.get("LLM_URL")): if not (url := os.environ.get("LLM_URL")):
return None return None
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600) client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
@@ -300,37 +281,30 @@ def _comparison(field: str):
def _plain(identifier: str) -> str: 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() return "".join(ch for ch in identifier if ch.isalnum()).upper()
def _name(name: str) -> str: def _name(name: str) -> str:
"""A name as compared: upper case, without accents, single spaces."""
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode() plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
return " ".join(plain.upper().split()) return " ".join(plain.upper().split())
def _near(identifier: str) -> list[str]: 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( return sorted(
{identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))} {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]]: 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() skip, fixed = nodes.rejected("identity"), nodes.corrections()
records: dict[str, dict] = {} records: dict[str, dict] = {}
sources: dict[str, str] = {} sources: dict[str, str] = {}
written: dict[str, str] = {} # each record's name as it came (compared normalised) written: dict[str, str] = {}
for i in node.inputs: for i in node.inputs:
for row in nodes.rows(p, i): for row in nodes.rows(p, i):
if row.get(HELD) or row[RECORD] in skip: if row.get(HELD) or row[RECORD] in skip:
continue continue
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins row = {**row, **fixed.get(row[RECORD], {})}
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]}) mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
sources.setdefault(row[RECORD], i) sources.setdefault(row[RECORD], i)
for f in node.fields: for f in node.fields:
@@ -348,10 +322,6 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series: def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
"""Each record's stand-in: one record per identity that the rules join to itself (a
patient's 24 reports carrying one record number are one row to compare, not 24² pairs).
A record a reviewer judged stands for itself, and so does one the rules would not join
to an identical record (nothing compared was read, say)."""
fields = [c for c in records.columns if c != "unique_id"] fields = [c for c in records.columns if c != "unique_id"]
key = records[fields].astype(object).where(records[fields].notna(), None) key = records[fields].astype(object).where(records[fields].notna(), None)
same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index) same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index)
@@ -377,11 +347,6 @@ def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.Da
def run_link(p: str, node: Link): def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
don't contradict each other are queued for review, with Splink's probability. A person
with nothing that names her (no name, birth date or record number read) is held too."""
records, sources, written = _identities(p, node) records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"] fields = [c for c in records.columns if c != "unique_id"]
rules = [r for r in node.rules or node.default_rules() rules = [r for r in node.rules or node.default_rules()
@@ -410,7 +375,6 @@ def run_link(p: str, node: Link):
facts = [f for f in ("birth_date", "sex") if f in fields] facts = [f for f in ("birth_date", "sex") if f in fields]
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame() spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set() torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1) read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1)
nameless = set(read[read == 0].index) nameless = set(read[read == 0].index)
why = {c: "records of this person disagree on birth date or sex" for c in torn} why = {c: "records of this person disagree on birth date or sex" for c in torn}
@@ -425,9 +389,8 @@ def run_link(p: str, node: Link):
for r in persons.itertuples() for r in persons.itertuples()
] # fmt: skip ] # fmt: skip
nodes.write(p, node.id, linked, columns) nodes.write(p, node.id, linked, columns)
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person nodes.stage("identity", p, node.id, linked, silver.identity_columns())
# 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] ids = [f for f in IDENTIFIERS if f in fields]
whole = persons.drop(columns="unique_id").groupby("cluster_id").first() whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
for f in ids: for f in ids:
@@ -456,23 +419,15 @@ def run_link(p: str, node: Link):
known = [f for f in ("birth_date", "sex") if f in fields] 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() orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set() undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
# Answers are kept by record; a person is known by any of hers, whatever joined since.
whose = persons.set_index("unique_id")["cluster_id"].to_dict() whose = persons.set_index("unique_id")["cluster_id"].to_dict()
answered = {frozenset(whose.get(r, r) for r in e) for e in decided} answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
lone = set() # persons whose identifier is carried by one record only lone = set()
for f in ids: for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size() carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
lone |= {person for (person, _), n in carried.items() if n == 1} lone |= {person for (person, _), n in carried.items() if n == 1}
def settle(r) -> tuple[str, str] | None: def settle(r) -> tuple[str, str] | None:
"""(the person to settle, a possible owner), or None when the pair is implausible:
they contradict each other, or one typo apart is all they share (with sequential
record numbers every patient has such neighbours) unless one side has no
demographics and the other's identifier stands on a single record. Names one typo
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
very same identifier on a record that says nothing else (a scan read only in part)."""
a, b = r.unique_id_l, r.unique_id_r a, b = r.unique_id_l, r.unique_id_r
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known] sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in answered or any( if frozenset((a, b)) in answered or any(
@@ -483,10 +438,10 @@ def run_link(p: str, node: Link):
if not reason.endswith("typo apart"): if not reason.endswith("typo apart"):
return a, b return a, b
field = reason.removesuffix(" one typo apart") field = reason.removesuffix(" one typo apart")
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"):
return (a, b) if a in undated or b not in undated else (b, a) return (a, b) if a in undated or b not in undated else (b, a)
if field == "full_name" and (a in undated) != (b in undated): if field == "full_name" and (a in undated) != (b in undated):
return (a, b) if a in undated else (b, a) # names are rarely one typo apart return (a, b) if a in undated else (b, a)
if a in orphan and b in lone: if a in orphan and b in lone:
return a, b return a, b
if b in orphan and a in lone: if b in orphan and a in lone:
@@ -512,14 +467,11 @@ def run_link(p: str, node: Link):
def run_target(p: str, node: Target, kinds: dict[str, str]): 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") link = next(i for i in node.inputs if kinds[i] == "link")
linked = {r[RECORD]: r for r in nodes.rows(p, link)} linked = {r[RECORD]: r for r in nodes.rows(p, link)}
person = {k: r["person_id"] for k, r in linked.items()} person = {k: r["person_id"] for k, r in linked.items()}
model, study = catalog.model(node.entity), catalog.studies()[node.entity] model, study = catalog.model(node.entity), catalog.studies()[node.entity]
fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction fixed = nodes.corrections()
observations, held_rows = [], [] observations, held_rows = [], []
for i in (i for i in node.inputs if i != link): for i in (i for i in node.inputs if i != link):
for row in nodes.rows(p, i): for row in nodes.rows(p, i):
@@ -566,5 +518,5 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
RUNNERS[node.kind](pipeline_id, node) RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done") log(f"{node.id} ({node.kind}) done")
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}): if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
silver.build(["silver+"]) # every entity (empty if never staged) and what derives silver.build(["silver+"])
log(f"silver and gold, from {', '.join(entities)}") log(f"silver and gold, from {', '.join(entities)}")
+2 -16
View File
@@ -1,8 +1,3 @@
"""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 collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date from datetime import date
@@ -15,13 +10,10 @@ from persistance import gold, registry
class EmptyCohort(ValueError): class EmptyCohort(ValueError):
"""The site has nobody in a model's cohort (no colposcopies, say): nothing to learn from.""" pass
class Predictor(mlflow.pyfunc.PythonModel): 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): def __init__(self, spec, fitted):
self.spec, self.fitted = spec, fitted self.spec, self.fitted = spec, fitted
@@ -47,10 +39,8 @@ class Jobs:
return f"{self.domain}.{name}" return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int: 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() spec, as_of = self.models[name], as_of or date.today()
if getattr(spec, "reports", False): # trained on its cohort, with its own reports if getattr(spec, "reports", False):
events = gold.timelines(self.events, spec.cohort, as_of) events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty: if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
@@ -64,16 +54,12 @@ class Jobs:
"technical_validation": self.technical_validation(spec, metrics, data), "technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data), "interpretability": self.interpretability(spec, fitted, data),
} }
# 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) get_reusable_executor().shutdown(wait=True)
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()} params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted) model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found) return registry.register(self.registered(name), model, params, metrics, found)
def score(self, name: str) -> int | None: def score(self, name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet."""
found = registry.champion(self.registered(name)) found = registry.champion(self.registered(name))
if found is None: if found is None:
return None return None
+11 -85
View File
@@ -1,14 +1,3 @@
"""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).
"""
import json import json
import warnings import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
@@ -28,8 +17,6 @@ DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame: 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) index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
died = (death.notna() & (death <= end)).to_numpy() died = (death.notna() & (death <= end)).to_numpy()
last = death.where(died, end) last = death.where(died, end)
@@ -42,7 +29,6 @@ def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.Dat
def band(values: pd.Series, cuts: list) -> pd.Series: 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] edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"] 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) return pd.cut(values, edges, right=False, labels=labels).astype(object)
@@ -50,8 +36,6 @@ def band(values: pd.Series, cuts: list) -> pd.Series:
@dataclass(frozen=True) @dataclass(frozen=True)
class Constant: class Constant:
"""An interval where everyone at risk had the same outcome: the same probability for all."""
p: float p: float
def predict_proba(self, X) -> np.ndarray: def predict_proba(self, X) -> np.ndarray:
@@ -59,7 +43,6 @@ class Constant:
def _bdeu(code, y, w, q, ess) -> float: 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) n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj, ajk = ess / q, ess / q / 2 aj, ajk = ess / q, ess / q / 2
return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1)) return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
@@ -67,7 +50,6 @@ def _bdeu(code, y, w, q, ess) -> float:
def _search(X, levels, y, w, ess, max_parents) -> list[int]: 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 parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess) best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents: while len(parents) < max_parents:
@@ -94,12 +76,6 @@ def _code(X, levels, parents) -> np.ndarray:
class IntervalSurvival(BaseEstimator): 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, def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
folds=5, shrink=20, seed=42): # fmt: skip folds=5, shrink=20, seed=42): # fmt: skip
self.features = features self.features = features
@@ -111,8 +87,6 @@ class IntervalSurvival(BaseEstimator):
self.shrink = shrink self.shrink = shrink
self.seed = seed 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: def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object) found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str) return found.where(found.notna(), UNKNOWN).astype(str)
@@ -136,8 +110,8 @@ class IntervalSurvival(BaseEstimator):
fitted.append((Constant(1.0), ([], np.array([1.0])))) fitted.append((Constant(1.0), ([], np.array([1.0]))))
continue continue
m, e = months[at_risk], event[at_risk] m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) # 1 = survives the interval y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0) # censored inside it: half a risk w = np.where(~e & (m < b), 0.5, 1.0)
if y.min() == y.max(): if y.min() == y.max():
lr = Constant(float(y[0])) lr = Constant(float(y[0]))
else: else:
@@ -147,7 +121,6 @@ class IntervalSurvival(BaseEstimator):
return fitted return fitted
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]: 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: if self.parents is None:
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents) parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
else: else:
@@ -165,7 +138,6 @@ class IntervalSurvival(BaseEstimator):
return lr, hbn return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray: 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) n = len(months)
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds 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)) oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
@@ -209,35 +181,27 @@ class IntervalSurvival(BaseEstimator):
return self return self
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: 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)) return self._predict(self.fitted_, *self._encode(X))
def survival(self, X: pd.DataFrame) -> np.ndarray: def survival(self, X: pd.DataFrame) -> np.ndarray:
"""Each patient's survival to the end of each interval."""
lr, hbn = self.components(X) lr, hbn = self.components(X)
w = self.weights_[None, :] w = self.weights_[None, :]
return np.cumprod(w * lr + (1 - w) * hbn, axis=1) return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
# ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7 TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high", OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"scenarios"] # fmt: skip "scenarios"] # fmt: skip
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios SCENARIO_SEPARATOR = " | "
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""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") ordered = members.sort_values(["index_date", "record_number"], kind="stable")
cut = int(len(ordered) * train_fraction) cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True) 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: 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() birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
return band(age, list(cuts)) return band(age, list(cuts))
@@ -245,31 +209,20 @@ def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
@dataclass(frozen=True) @dataclass(frozen=True)
class Spec: 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 name: str
cohort: str cohort: str
features: tuple[str, ...] features: tuple[str, ...]
covariates: object # Callable[[pd.DataFrame, pd.DataFrame], pd.DataFrame] covariates: object
parents: tuple[str, ...] | None = None parents: tuple[str, ...] | None = None
borders: tuple[int, ...] = (0, 6, 12, 18) # months borders: tuple[int, ...] = (0, 6, 12, 18)
cap_months: int = 24 cap_months: int = 24
interval_level: float | None = None interval_level: float | None = None
replicas: int = 100 replicas: int = 100
seed: int = 0 seed: int = 0
method: str = "interval survival" method: str = "interval survival"
notes: tuple[str, ...] = () # what the technical report states about the method notes: tuple[str, ...] = ()
# 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) scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = () scenario_columns: tuple[str, ...] = ()
# Features that are treatments: their odds ratios are reported as associations, unclassified.
treatments: tuple[str, ...] = () treatments: tuple[str, ...] = ()
@property @property
@@ -277,7 +230,6 @@ class Spec:
return tuple(b / 12 for b in self.borders[1:]) return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame: 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"]), events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip index_date=pd.to_datetime(events["index_date"])) # fmt: skip
found = events.groupby("person_id")[["index_date", "record_number"]].first() found = events.groupby("person_id")[["index_date", "record_number"]].first()
@@ -297,7 +249,7 @@ class Spec:
def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]: def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = self._combinations(train).drop_duplicates() combinations = self._combinations(train).drop_duplicates()
frame = combinations.replace(UNKNOWN, None) frame = combinations.replace(UNKNOWN, None)
rng = np.random.default_rng(self.seed) # resamples drawn in order, refitted in parallel rng = np.random.default_rng(self.seed)
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)] samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
def mortality(rows: np.ndarray) -> np.ndarray: def mortality(rows: np.ndarray) -> np.ndarray:
@@ -312,8 +264,6 @@ class Spec:
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)} return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def train(self, events: pd.DataFrame, as_of) -> tuple: 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 = self.members(events)
members = members.join( members = members.join(
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months) outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
@@ -330,8 +280,6 @@ class Spec:
return model, metrics, {"train": train, "test": test} return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame: def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, its interval when kept, and
the clinical scenarios of the report she falls in (the curves her record draws)."""
members = self.members(events) members = self.members(events)
mortality = 1.0 - model.survival(members) mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons) n, h = len(members), len(self.horizons)
@@ -352,8 +300,6 @@ class Spec:
})[OUTPUT] # fmt: skip })[OUTPUT] # fmt: skip
# ---------------------------------------------------------------- reports (curves)
BOOTSTRAP = 100 BOOTSTRAP = 100
BOOTSTRAP_SEED = 42 BOOTSTRAP_SEED = 42
@@ -382,13 +328,11 @@ def _curve(fitter, name: str) -> dict:
} # fmt: skip } # fmt: skip
MIN_SCENARIO_EVENTS = 5 # fewer deaths than this: no curves for the scenario MIN_SCENARIO_EVENTS = 5
GRID_POINTS = 200 GRID_POINTS = 200
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: 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 = {} found = {}
for name, conditions in scenarios.items(): for name, conditions in scenarios.items():
mask = np.ones(len(members), bool) mask = np.ones(len(members), bool)
@@ -431,12 +375,6 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
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 from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"] train = data["train"]
@@ -447,8 +385,6 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
rng = np.random.default_rng(BOOTSTRAP_SEED) rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)] 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) members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios) masks = scenario_masks(members, spec.scenarios)
@@ -505,14 +441,12 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
for i, row in enumerate(combinations.to_dict("records")) for i, row in enumerate(combinations.to_dict("records"))
], ],
"escenarios": scenarios, "escenarios": scenarios,
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths "escenarios_sin_curvas": skipped,
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS, "min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
**risk_factor_report(spec, model, members), **risk_factor_report(spec, model, members),
} }
# ---------------------------------------------------------------- risk factors
FACTOR_COLUMNS = ( FACTOR_COLUMNS = (
"tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia", "IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
@@ -521,15 +455,10 @@ FACTOR_COLUMNS = (
) # fmt: skip ) # fmt: skip
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S") SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
# The model has no variable selection to resample, so stability (2) is not evaluated.
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia") EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame: def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame:
"""The members' risk factors of death by the last horizon (`models.factors`, as the
SEER-trained original rates them): odds ratios of dying before it, among those dead before
it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at
`cap_months`); the Markov blanket is the HBN's parents in any interval."""
from models import factors as rated from models import factors as rated
horizon = spec.borders[-1] horizon = spec.borders[-1]
@@ -552,7 +481,7 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
SURVIVAL_COLUMNS) # fmt: skip SURVIVAL_COLUMNS) # fmt: skip
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"): with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios warnings.simplefilter("ignore")
try: try:
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"), tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
intrinsic) # fmt: skip intrinsic) # fmt: skip
@@ -581,8 +510,6 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]: def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]:
"""Per clinical scenario, the classified factors and treatments nearly all of its
members have (definitorios) or most have (mayoritarios)."""
from models import factors as rated from models import factors as rated
found = rated.classified(table) if len(table) else table found = rated.classified(table) if len(table) else table
@@ -599,9 +526,8 @@ def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) ->
def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict: def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict:
"""The interpretability report's risk factors: the table and each scenario's summary."""
table = risk_factors(spec, model, members) table = risk_factors(spec, model, members)
rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON rows = json.loads(table.to_json(orient="records"))
return { return {
"factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows}, "factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows},
"factores_escenarios": scenario_factors(spec, members, table), "factores_escenarios": scenario_factors(spec, members, table),
-2
View File
@@ -1,2 +0,0 @@
"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`,
`curves.py`)."""
+5 -22
View File
@@ -1,17 +1,3 @@
"""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 re import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date
@@ -27,7 +13,7 @@ MAINS_HZ = 60.0
class Metric: class Metric:
code: str code: str
value: float | None value: float | None
electrodes: dict[str, float] = field(default_factory=dict) # None where not measured electrodes: dict[str, float] = field(default_factory=dict)
zones: dict[str, float] = field(default_factory=dict) zones: dict[str, float] = field(default_factory=dict)
@@ -42,10 +28,9 @@ class Analysis:
duration_min: float | None duration_min: float | None
line_noise_db: float | None line_noise_db: float | None
sleep: bool | None sleep: bool | None
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal checks: list[dict]
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes, metrics: list[Metric]
# anteroposterior_gradient features: dict[str, dict[str, float]]
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
error: str | None error: str | None
@@ -61,8 +46,6 @@ def analyze(
age_months: float | None = None, age_months: float | None = None,
mains_hz: float = MAINS_HZ, mains_hz: float = MAINS_HZ,
) -> Analysis: ) -> 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( out = dict(
valid=None, valid=None,
level=checks.NOT_ANALYZABLE, level=checks.NOT_ANALYZABLE,
@@ -124,5 +107,5 @@ def analyze(
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()}, features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
) )
return Analysis(**out) return Analysis(**out)
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch except Exception as exc: # noqa: BLE001
return Analysis(**out | dict(error=_error(exc))) return Analysis(**out | dict(error=_error(exc)))
-16
View File
@@ -1,17 +1,3 @@
"""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 import numpy as np
from scipy.fft import rfft, rfftfreq from scipy.fft import rfft, rfftfreq
from scipy.signal.windows import hann from scipy.signal.windows import hann
@@ -37,7 +23,6 @@ CODES = (
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None: 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] starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
if len(starts) < MIN_WINDOWS or not names: if len(starts) < MIN_WINDOWS or not names:
return None return None
@@ -77,7 +62,6 @@ def delta_gradient(prep: Prepared, states) -> float:
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]: def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
"""(metrics: code -> (value, electrodes, zones), features by scenario)."""
metrics, features = {}, {} metrics, features = {}, {}
rhythm = posterior_rhythm(prep, states) rhythm = posterior_rhythm(prep, states)
metrics["posterior_rhythm"] = (rhythm, {}, {}) metrics["posterior_rhythm"] = (rhythm, {}, {})
+1 -26
View File
@@ -1,19 +1,3 @@
"""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 from dataclasses import dataclass, field
import numpy as np import numpy as np
@@ -43,7 +27,7 @@ NOT_ANALYZABLE = "not_analyzable"
class Validation: class Validation:
valid: bool valid: bool
level: str level: str
bad: dict[str, list[str]] # channel -> reasons, every kind of channel bad: dict[str, list[str]]
clean_pct: float clean_pct: float
line_db: float line_db: float
checks: list[dict] = field(default_factory=list) checks: list[dict] = field(default_factory=list)
@@ -84,7 +68,6 @@ def _filtered(x, fs, mains_hz, lo, hi):
def _temporal(v: np.ndarray) -> list[tuple[str, str]]: def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
"""Rules on a channel's raw samples: (code, reason)."""
finite = v[np.isfinite(v)] finite = v[np.isfinite(v)]
if len(finite) < 10 or np.std(finite) < 0.5: if len(finite) < 10 or np.std(finite) < 0.5:
return [("dead-channel", "dead channel")] return [("dead-channel", "dead channel")]
@@ -99,8 +82,6 @@ def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: 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) size = int(10 * fs)
blocks = len(y) // size blocks = len(y) // size
low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan) low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)
@@ -123,7 +104,6 @@ def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]: 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) finite = np.isfinite(y).all(axis=1)
if finite.sum() < 200 or len(scalp) < 2: if finite.sum() < 200 or len(scalp) < 2:
return {} return {}
@@ -142,7 +122,6 @@ def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str
def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]: 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 = {} out = {}
for ear, around in EAR_NEIGHBOURS.items(): for ear, around in EAR_NEIGHBOURS.items():
present = [n for n in around if n in names] present = [n for n in around if n in names]
@@ -159,7 +138,6 @@ def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float,
def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]: 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() x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)} reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
dead = { dead = {
@@ -224,8 +202,6 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]: def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
verdict `gap`, `suspect` or `clean`."""
n = int(4 * fs) n = int(4 * fs)
lines = signals.fixed_lines(y, fs, f_max=44.0) lines = signals.fixed_lines(y, fs, f_max=44.0)
starts = list(range(0, len(y) - n + 1, n)) starts = list(range(0, len(y) - n + 1, n))
@@ -255,7 +231,6 @@ def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float): 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() x, fs, kinds = rec.x, rec.fs, rec.kinds()
columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")] 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) y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0)
+4 -31
View File
@@ -1,22 +1,3 @@
"""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 import math
from dataclasses import dataclass from dataclasses import dataclass
@@ -35,10 +16,10 @@ EXPOSURE = "minutes"
@dataclass(frozen=True) @dataclass(frozen=True)
class Scenario: class Scenario:
metric: str # the metric code it scores metric: str
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones" parts: tuple[str, ...]
stage: str | None = None stage: str | None = None
counts: bool = False # a count against the `minutes` feature, not centile curves counts: bool = False
SCENARIOS = { SCENARIOS = {
@@ -54,7 +35,6 @@ PREFIX = {"electrodes": "electrode_", "zones": "zone_"}
def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float: 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) order = np.argsort(x)
x, w = x[order], w[order] x, w = x[order], w[order]
return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x)) return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x))
@@ -89,7 +69,7 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan") rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan")
mu = rate * x mu = rate * x
excess = float(((n - mu) ** 2 - n).sum()) excess = float(((n - mu) ** 2 - n).sum())
k = float((mu**2).sum() / excess) if excess > 0 else None # None: Poisson k = float((mu**2).sum() / excess) if excess > 0 else None
return { return {
"kind": "count_rate", "kind": "count_rate",
"ages": list(COUNT_AGES), "ages": list(COUNT_AGES),
@@ -101,8 +81,6 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
def train(features: pd.DataFrame, scenario: str) -> dict: 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 counts = SCENARIOS[scenario].counts
ages = features["age_months"].to_numpy(float) ages = features["age_months"].to_numpy(float)
out = {} out = {}
@@ -164,8 +142,6 @@ def _score_count(baseline: dict, value: float, age: float, exposure: float | Non
def score( def score(
baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None
) -> dict: ) -> 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) value, age_months = _number(value), _number(age_months)
if value is None or age_months is None: if value is None or age_months is None:
return dict.fromkeys(("z", "outside", "p5", "median", "p95")) return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
@@ -175,9 +151,6 @@ def score(
def deviations(models: dict[str, dict], analysis) -> dict[str, dict]: 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} out = {m.code: {} for m in analysis.metrics}
metrics = {m.code: m for m in analysis.metrics} metrics = {m.code: m for m in analysis.metrics}
for name, scenario in SCENARIOS.items(): for name, scenario in SCENARIOS.items():
+5 -18
View File
@@ -1,13 +1,3 @@
"""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 import warnings
from dataclasses import dataclass from dataclasses import dataclass
@@ -25,11 +15,11 @@ STEP_S = 2.0
@dataclass(frozen=True) @dataclass(frozen=True)
class Prepared: class Prepared:
x: np.ndarray # (samples, scalp channels) µV, average reference x: np.ndarray
names: tuple[str, ...] # the kept scalp channels names: tuple[str, ...]
fs: float fs: float
starts: np.ndarray # window grid starts, s starts: np.ndarray
unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean unclean: tuple[tuple[float, float], ...]
annotations: tuple[tuple[float, float, str], ...] annotations: tuple[tuple[float, float, str], ...]
@property @property
@@ -37,7 +27,6 @@ class Prepared:
return len(self.x) / self.fs return len(self.x) / self.fs
def columns(self, wanted) -> list[str]: 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] return [name for name in wanted if name in self.names]
def data(self, names) -> np.ndarray: def data(self, names) -> np.ndarray:
@@ -52,10 +41,8 @@ def prepare(rec: Recording, bad) -> Prepared:
gaps = ~np.isfinite(x).all(axis=1) gaps = ~np.isfinite(x).all(axis=1)
y = signals.bandpass(x, rec.fs, 0.5, 100.0) y = signals.bandpass(x, rec.fs, 0.5, 100.0)
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row warnings.simplefilter("ignore", RuntimeWarning)
referenced = y - np.nanmean(y, axis=1, keepdims=True) 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) referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
qc = signals.bandpass(x, rec.fs, 0.5, 45.0) qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
qc[gaps] = np.nan qc[gaps] = np.nan
+5 -23
View File
@@ -1,14 +1,3 @@
"""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 io
import re import re
from dataclasses import dataclass from dataclasses import dataclass
@@ -25,16 +14,14 @@ RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"}
AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC")) AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC"))
EARS = {"A1", "A2"} EARS = {"A1", "A2"}
EOG = {"LOC", "ROC"} EOG = {"LOC", "ROC"}
# What a header's start date holds when the writer didn't know it.
UNKNOWN_START = date(1985, 1, 1) UNKNOWN_START = date(1985, 1, 1)
class FileNotValid(ValueError): class FileNotValid(ValueError):
"""The bytes are not an EDF the analysis can read.""" pass
def normalize(label: str) -> str | None: 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() text = str(label).strip()
if not text or "ANNOT" in text.upper(): if not text or "ANNOT" in text.upper():
return None return None
@@ -47,7 +34,6 @@ def normalize(label: str) -> str | None:
def kind(name: str) -> str: def kind(name: str) -> str:
"""`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name."""
if name in EARS: if name in EARS:
return "ear" return "ear"
if name in EOG: if name in EOG:
@@ -57,10 +43,10 @@ def kind(name: str) -> str:
@dataclass(frozen=True) @dataclass(frozen=True)
class Recording: class Recording:
x: np.ndarray # (samples, channels) µV, NaN in gaps x: np.ndarray
fs: float fs: float
names: tuple[str, ...] names: tuple[str, ...]
annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text) annotations: tuple[tuple[float, float, str], ...]
start: date | None start: date | None
birthday: date | None birthday: date | None
@@ -72,7 +58,6 @@ class Recording:
return {name: kind(name) for name in self.names} return {name: kind(name) for name in self.names}
def of(self, *kinds: str) -> list[str]: 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] return [name for name in self.names if kind(name) in kinds]
@@ -149,7 +134,7 @@ def _open(edf: bytes) -> edfio.Edf:
_check_length(edf) _check_length(edf)
try: try:
opened = edfio.read_edf(edf, lazy_load_data=True) opened = edfio.read_edf(edf, lazy_load_data=True)
except Exception as exc: # noqa: BLE001 -- any parse failure means the same except Exception as exc: # noqa: BLE001
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
declared_records = int(edf[236:244]) declared_records = int(edf[236:244])
if declared_records > opened.num_data_records: if declared_records > opened.num_data_records:
@@ -158,7 +143,6 @@ def _open(edf: bytes) -> edfio.Edf:
def _kept(edf: bytes) -> list[tuple[str, str]]: def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
signals = _open(edf).signals signals = _open(edf).signals
if not signals: if not signals:
@@ -182,7 +166,7 @@ def read(edf: bytes) -> Recording:
options = dict(include=[label for label, _ in kept], preload=True, verbose="error") options = dict(include=[label for label, _ in kept], preload=True, verbose="error")
try: try:
raw = mne.io.read_raw_edf(io.BytesIO(edf), **options) raw = mne.io.read_raw_edf(io.BytesIO(edf), **options)
except Exception as exc: # notes in a Windows code page except Exception as exc:
if "latin1" not in str(exc): if "latin1" not in str(exc):
raise raise
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options) raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options)
@@ -205,8 +189,6 @@ def read(edf: bytes) -> Recording:
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None: 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: if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
return None return None
months = round((start - birthday).days / days_per_month, 1) months = round((start - birthday).days / days_per_month, 1)
-28
View File
@@ -1,13 +1,3 @@
"""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 import numpy as np
from mne.time_frequency import psd_array_welch from mne.time_frequency import psd_array_welch
from scipy import signal from scipy import signal
@@ -15,13 +5,11 @@ from scipy.ndimage import median_filter
def runs(valid: np.ndarray) -> list[tuple[int, int]]: 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)) 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)) return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True))
def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray: 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) x = np.asarray(x, float)
out = np.full_like(x, np.nan) out = np.full_like(x, np.nan)
for a, b in runs(np.isfinite(x).all(axis=1)): for a, b in runs(np.isfinite(x).all(axis=1)):
@@ -31,16 +19,12 @@ def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray:
def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray: 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") sos = signal.butter(order, [lo / (fs / 2), hi / (fs / 2)], btype="band", output="sos")
minimum = max(3 * (2 * len(sos) + 1), int(fs)) minimum = max(3 * (2 * len(sos) + 1), int(fs))
return by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum) 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: 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] centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98]
def interpolate(run): def interpolate(run):
@@ -67,8 +51,6 @@ def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray
def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray: 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) finite = np.isfinite(x).all(axis=1)
if not finite.any(): if not finite.any():
return np.full(x.shape[1], np.nan) return np.full(x.shape[1], np.nan)
@@ -83,18 +65,12 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
"""One Hann periodogram (density, mean removed) of each segment along the last axis:
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
n = segments.shape[-1] n = segments.shape[-1]
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
return f, power return f, power
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]: 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)) n = int(round(8 * fs))
f = np.fft.rfftfreq(n, 1 / fs) f = np.fft.rfftfreq(n, 1 / fs)
taper = np.hanning(n)[:, None] taper = np.hanning(n)[:, None]
@@ -132,8 +108,6 @@ def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
def band_power(f, power, lo, hi, lines=(), include_hi=False): 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)) band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
clean = band.copy() clean = band.copy()
for line in lines: for line in lines:
@@ -144,8 +118,6 @@ def band_power(f, power, lo, hi, lines=(), include_hi=False):
def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]: 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) usable = (f >= 1.5) & (f <= 45) & (power > 0)
background = usable & ~((f >= 4) & (f <= 16)) background = usable & ~((f >= 4) & (f <= 16))
if background.sum() < 5: if background.sum() < 5:
-27
View File
@@ -1,22 +1,3 @@
"""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 json
import unicodedata import unicodedata
from pathlib import Path from pathlib import Path
@@ -61,7 +42,6 @@ def note_state(text: str) -> str | None:
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]: 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]) notes = sorted(annotations, key=lambda note: note[0])
found = [] found = []
for i, (t0, length, text) in enumerate(notes): for i, (t0, length, text) in enumerate(notes):
@@ -89,7 +69,6 @@ def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, s
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]: 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 = {} overlap = {}
for onset, length, state in intervals: for onset, length, state in intervals:
lo, hi = max(t0, onset), min(t1, onset + length) lo, hi = max(t0, onset), min(t1, onset + length)
@@ -102,7 +81,6 @@ def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
def mask(prep: Prepared, intervals) -> np.ndarray: def mask(prep: Prepared, intervals) -> np.ndarray:
"""Samples of the QC spans and of the masked notes."""
out = np.zeros(len(prep.x), bool) out = np.zeros(len(prep.x), bool)
spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)] spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)]
for onset, length in spans: for onset, length in spans:
@@ -111,7 +89,6 @@ def mask(prep: Prepared, intervals) -> np.ndarray:
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]: 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) fs, x, names = prep.fs, prep.x, list(prep.names)
n, step = int(WINDOW_S * fs), int(2 * fs) n, step = int(WINDOW_S * fs), int(2 * fs)
starts = [ starts = [
@@ -144,7 +121,6 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray: 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 = [], [] z, weights = [], []
for name, ref in REFERENCE["features"].items(): for name, ref in REFERENCE["features"].items():
if name not in features: if name not in features:
@@ -160,7 +136,6 @@ def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarr
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray: 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)) starts, features = _features(prep, mask(prep, intervals))
out = np.full(len(prep.starts), "", dtype=object) out = np.full(len(prep.starts), "", dtype=object)
if not starts: if not starts:
@@ -172,7 +147,6 @@ def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]: 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] y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
sign = np.sign(y) sign = np.sign(y)
sign[sign == 0] = 1 sign[sign == 0] = 1
@@ -209,7 +183,6 @@ def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray: 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)] waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
covered = _merged(waves) covered = _merged(waves)
out = np.full(len(prep.starts), "", dtype=object) out = np.full(len(prep.starts), "", dtype=object)
+2 -30
View File
@@ -1,25 +1,3 @@
"""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 from dataclasses import dataclass
import numpy as np import numpy as np
@@ -43,10 +21,10 @@ ASLEEP = ("N2", "N3", "sleep")
@dataclass(frozen=True) @dataclass(frozen=True)
class Spikes: class Spikes:
rate: float # useful discharges per minute of clean sleep rate: float
electrodes: dict[str, float] electrodes: dict[str, float]
zones: dict[str, float] zones: dict[str, float]
minutes: float # clean sleep minutes, the rate's exposure minutes: float
def _mad(v: np.ndarray) -> float: def _mad(v: np.ndarray) -> float:
@@ -57,7 +35,6 @@ def _mad(v: np.ndarray) -> float:
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]: 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) n = int(GATE_S * fs)
top = min(45, fs / 2 * 0.9) top = min(45, fs / 2 * 0.9)
lines = signals.fixed_lines(x, fs, f_max=top) lines = signals.fixed_lines(x, fs, f_max=top)
@@ -82,7 +59,6 @@ def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]: 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) n = len(y)
if i <= 0 or i >= n - 1: if i <= 0 or i >= n - 1:
return np.nan, np.nan return np.nan, np.nan
@@ -137,7 +113,6 @@ def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
def _field(c: pd.DataFrame) -> np.ndarray: 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"])} times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])}
out = np.zeros(len(c), int) out = np.zeros(len(c), int)
for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)): for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)):
@@ -152,7 +127,6 @@ def _field(c: pd.DataFrame) -> np.ndarray:
def _merge(c: pd.DataFrame) -> pd.DataFrame: 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) 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) groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1)
rows = [] rows = []
@@ -177,7 +151,6 @@ def _merge(c: pd.DataFrame) -> pd.DataFrame:
def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None: 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] channels = [c for c in prep.names if c in ELECTRODES]
if len(channels) < 4: if len(channels) < 4:
return None return None
@@ -190,7 +163,6 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
] ]
def state_at(t: np.ndarray) -> np.ndarray: 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) out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
for t0, t1, label in labelled: for t0, t1, label in labelled:
hit = open_ & (t0 <= t) & (t < t1) hit = open_ & (t0 <= t) & (t < t1)
+2 -24
View File
@@ -1,20 +1,3 @@
"""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 from dataclasses import dataclass
import numpy as np import numpy as np
@@ -39,9 +22,9 @@ ZONES = {
@dataclass(frozen=True) @dataclass(frozen=True)
class Spindles: class Spindles:
events: list[tuple[float, float, str]] # (onset s, duration s, channel) events: list[tuple[float, float, str]]
minutes: float minutes: float
channels: list[str] # the channels searched (none when under a minute of the stage) channels: list[str]
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
@@ -73,7 +56,6 @@ def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int
def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool: 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(): if not np.isfinite(x).all():
return False return False
nperseg = min(len(x), int(fs)) nperseg = min(len(x), int(fs))
@@ -93,7 +75,6 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles: 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) fs, n = prep.fs, int(WINDOW_S * prep.fs)
asleep = np.zeros(len(prep.x), bool) asleep = np.zeros(len(prep.x), bool)
for start, s in zip(prep.starts, staged, strict=True): for start, s in zip(prep.starts, staged, strict=True):
@@ -123,7 +104,6 @@ def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
def density(found: Spindles) -> tuple[float, dict[str, float]]: 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) zones = dict.fromkeys(ZONES, np.nan)
if not found.events or found.minutes <= 0: if not found.events or found.minutes <= 0:
return np.nan, zones return np.nan, zones
@@ -155,8 +135,6 @@ def _episodes(events) -> list[list[float]]:
def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]: 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) out = dict.fromkeys(CHANNELS, np.nan)
use = prep.columns(CHANNELS) use = prep.columns(CHANNELS)
episodes = _episodes(found.events) episodes = _episodes(found.events)
+1 -8
View File
@@ -20,7 +20,7 @@ from persistance import cluster, eeg, registry, silver
ASSOCIATION = "ados2_association" ASSOCIATION = "ados2_association"
MODELS = curves.SCENARIOS MODELS = curves.SCENARIOS
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk) GOLD = "tea_eeg_metrics"
GOLD_SELECT = [ GOLD_SELECT = [
"tea_eeg_analyses+", "tea_eeg_analyses+",
"tea_eeg_metrics+", "tea_eeg_metrics+",
@@ -30,9 +30,6 @@ GOLD_SELECT = [
class Baseline(mlflow.pyfunc.PythonModel): 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): def __init__(self, scenario: str, baseline: dict):
self.scenario, self.baseline = scenario, baseline self.scenario, self.baseline = scenario, baseline
@@ -95,8 +92,6 @@ def _cohort(source: cluster.TrainingSource, as_of: date) -> tuple[str, list[dict
@dataclass(frozen=True) @dataclass(frozen=True)
class Jobs: class Jobs:
"""The domain's model jobs (models.definitions): every curve is routine."""
def routine(self) -> list[str]: def routine(self) -> list[str]:
return list(MODELS) return list(MODELS)
@@ -270,8 +265,6 @@ def relate() -> int | None:
def score(name: str) -> int | None: def score(name: str) -> int | None:
"""The champion curve's scores of every analysed EEG: the metric's value, and each
electrode and zone it measures; None without a champion."""
found = registry.champion(registered(name)) found = registry.champion(registered(name))
if found is None: if found is None:
return None return None