Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 49c9ef6448 | |||
| b23a8c4026 | |||
| 789f16ba74 | |||
| 2457859a09 | |||
| 41508efeb6 |
+3
-1
@@ -1,2 +1,4 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
.pytest_cache/
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.angular/
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
+31
-38
@@ -1,14 +1,9 @@
|
|||||||
"""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 +18,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 +25,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"])]
|
||||||
@@ -39,16 +32,20 @@ def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) ->
|
|||||||
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
|
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
|
||||||
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
|
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
|
||||||
positive = persons.isin(hpv["person_id"])
|
positive = persons.isin(hpv["person_id"])
|
||||||
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
|
grade = np.where(
|
||||||
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
|
np.isin(worst, history["high"]),
|
||||||
& positive.to_numpy()), "low", None)) # fmt: skip
|
"high",
|
||||||
|
np.where(
|
||||||
|
np.isin(worst, history["low"])
|
||||||
|
| np.isin(worst, history["low_if_hpv_positive"]) & positive.to_numpy(),
|
||||||
|
"low",
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
)
|
||||||
return pd.Series(grade, index=persons.index, dtype=object)
|
return pd.Series(grade, index=persons.index, dtype=object)
|
||||||
|
|
||||||
|
|
||||||
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 +61,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
|
||||||
@@ -76,45 +71,45 @@ def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.Data
|
|||||||
visits = found
|
visits = found
|
||||||
continue
|
continue
|
||||||
paired = pd.merge_asof(
|
paired = pd.merge_asof(
|
||||||
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
|
visits.sort_values("days"),
|
||||||
left_on="days", right_on=kind, by="person_id", direction="nearest",
|
found.rename(columns={"days": kind}).sort_values(kind),
|
||||||
|
left_on="days",
|
||||||
|
right_on=kind,
|
||||||
|
by="person_id",
|
||||||
|
direction="nearest",
|
||||||
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
|
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
|
||||||
).dropna(subset=[kind]) # fmt: skip
|
).dropna(subset=[kind])
|
||||||
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
|
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
|
||||||
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
|
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
|
def interval_coded(
|
||||||
history: dict | None = None) -> pd.DataFrame: # fmt: skip
|
events: pd.DataFrame, grades: list[str], cytology: dict, history: dict | None = None
|
||||||
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
|
) -> pd.DataFrame:
|
||||||
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()
|
||||||
negatives = _negatives(events, d, grades)
|
negatives = _negatives(events, d, grades)
|
||||||
before = ~(negatives["days"] >= negatives["person_id"].map(first))
|
before = ~(negatives["days"] >= negatives["person_id"].map(first))
|
||||||
last_negative = negatives[before].groupby("person_id")["days"].max()
|
last_negative = negatives[before].groupby("person_id")["days"].max()
|
||||||
|
|
||||||
coded = index_results(events, cytology, history)
|
coded = index_results(events, cytology, history)
|
||||||
window = cacu.PREVALENT_WINDOW_DAYS
|
window = cacu.PREVALENT_WINDOW_DAYS
|
||||||
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
|
event_days, free_until = (coded["person_id"].map(first), coded["person_id"].map(last_negative))
|
||||||
prevalent = event_days <= window
|
prevalent = event_days <= window
|
||||||
free = free_until.notna() & ~prevalent
|
free = free_until.notna() & ~prevalent
|
||||||
later = event_days.notna() & ~prevalent
|
later = event_days.notna() & ~prevalent
|
||||||
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
|
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
|
||||||
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
|
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
|
||||||
coded["r"] = np.where(prevalent, 0.0,
|
coded["r"] = np.where(prevalent, 0.0, np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf))
|
||||||
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
|
|
||||||
return coded
|
return coded
|
||||||
|
|
||||||
|
|
||||||
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[
|
||||||
[*key, "date"]] # fmt: skip
|
(events["type"] == "cytology") & ~events["person_id"].isin(referred), [*key, "date"]
|
||||||
|
]
|
||||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||||
has = has.reindex(columns=list(RESULTS))
|
has = has.reindex(columns=list(RESULTS))
|
||||||
@@ -126,14 +121,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"])]
|
||||||
@@ -151,9 +144,9 @@ def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
|
|||||||
return found.fillna(dict.fromkeys(predictors, MISSING))
|
return found.fillna(dict.fromkeys(predictors, MISSING))
|
||||||
|
|
||||||
|
|
||||||
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
|
def windowed_outcome(
|
||||||
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
|
events: pd.DataFrame, grades: list[str], years: float, follow_up_end: pd.Timestamp
|
||||||
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
|
) -> pd.DataFrame:
|
||||||
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)
|
||||||
|
|||||||
+1
-3
@@ -1,8 +1,6 @@
|
|||||||
"""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
|
||||||
|
|
||||||
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
|
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
|
||||||
train, score = JOBS.train, JOBS.score
|
train, score = (JOBS.train, JOBS.score)
|
||||||
|
|||||||
+53
-62
@@ -1,14 +1,4 @@
|
|||||||
"""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
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from scipy.interpolate import BSpline
|
from scipy.interpolate import BSpline
|
||||||
@@ -18,14 +8,13 @@ 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 = 0.0001
|
||||||
|
|
||||||
|
|
||||||
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])
|
||||||
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
|
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
|
||||||
@@ -37,15 +26,15 @@ 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
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
|
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
|
||||||
times = np.unique(np.r_[l, r[np.isfinite(r)]])
|
times = np.unique(np.r_[l, r[np.isfinite(r)]])
|
||||||
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
|
return cls(
|
||||||
|
tuple((float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))), degree
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def n_params(self) -> int:
|
def n_params(self) -> int:
|
||||||
@@ -55,14 +44,11 @@ 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
|
rate = np.exp(-np.log(max(exposure, 1e-06) / (events + 0.5)))
|
||||||
# last bit, and this is the start the current models were fitted from.
|
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-06) / self.n_params))
|
||||||
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
|
|
||||||
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
|
|
||||||
|
|
||||||
|
|
||||||
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
|
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
|
||||||
@@ -74,13 +60,13 @@ def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
|
|||||||
|
|
||||||
|
|
||||||
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
|
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
|
||||||
n_x, n_z = X.shape[1], Z.shape[1]
|
n_x, n_z = (X.shape[1], Z.shape[1])
|
||||||
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
|
theta, beta, rest = (params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :])
|
||||||
pi = expit(X @ theta)
|
pi = expit(X @ theta)
|
||||||
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
|
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
|
||||||
interval = np.maximum(interval, TINY)
|
interval = np.maximum(interval, TINY)
|
||||||
row = np.zeros(len(c))
|
row = np.zeros(len(c))
|
||||||
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
|
prevalent, free, unknown = (c == 1, c == 0, c == UNKNOWN)
|
||||||
row[prevalent] = np.log(pi[prevalent] + TINY)
|
row[prevalent] = np.log(pi[prevalent] + TINY)
|
||||||
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
|
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
|
||||||
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
|
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
|
||||||
@@ -88,13 +74,12 @@ 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):
|
||||||
for j in range(i, p):
|
for j in range(i, p):
|
||||||
ei, ej = np.zeros(p), np.zeros(p)
|
ei, ej = (np.zeros(p), np.zeros(p))
|
||||||
ei[i], ej[j] = step, step
|
ei[i], ej[j] = (step, step)
|
||||||
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
|
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
|
||||||
4 * step * step
|
4 * step * step
|
||||||
)
|
)
|
||||||
@@ -102,12 +87,11 @@ def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
|
def _ridge_logistic(c, X, ridge: float = 0.001) -> 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])
|
||||||
y, Xk = (c[known] == 1).astype(float), X[known]
|
y, Xk = ((c[known] == 1).astype(float), X[known])
|
||||||
|
|
||||||
def loss(theta):
|
def loss(theta):
|
||||||
eta = Xk @ theta
|
eta = Xk @ theta
|
||||||
@@ -122,12 +106,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],
|
||||||
@@ -135,28 +118,29 @@ class Fit:
|
|||||||
p[self.n_x + self.n_z :],
|
p[self.n_x + self.n_z :],
|
||||||
)
|
)
|
||||||
pi = expit(X @ theta)
|
pi = expit(X @ theta)
|
||||||
return np.column_stack([
|
return np.column_stack(
|
||||||
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
|
[
|
||||||
|
pi
|
||||||
|
+ (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
|
||||||
for t in years
|
for t in years
|
||||||
]) # 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-05 * max(1.0, abs(value))
|
||||||
up, down = self.params.copy(), self.params.copy()
|
up, down = (self.params.copy(), self.params.copy())
|
||||||
up[k] += step
|
up[k] += step
|
||||||
down[k] -= step
|
down[k] -= step
|
||||||
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
||||||
covariance = np.nan_to_num(self.covariance, nan=0.0)
|
covariance = np.nan_to_num(self.covariance, nan=0.0)
|
||||||
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
||||||
return self.risk(X, Z, years), np.maximum(variance, 0.0)
|
return (self.risk(X, Z, years), np.maximum(variance, 0.0))
|
||||||
|
|
||||||
|
|
||||||
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]]
|
||||||
args = (c, l, r, X, Z, baseline, w)
|
args = (c, l, r, X, Z, baseline, w)
|
||||||
@@ -169,17 +153,21 @@ def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
|
|||||||
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
|
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
|
||||||
except np.linalg.LinAlgError:
|
except np.linalg.LinAlgError:
|
||||||
pass
|
pass
|
||||||
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
|
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 0.001)
|
||||||
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
|
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
|
||||||
|
|
||||||
|
|
||||||
class Mixture(BaseEstimator):
|
class Mixture(BaseEstimator):
|
||||||
"""One mixture per stratum. Categorical features get one dummy per level after the first
|
def __init__(
|
||||||
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
|
self,
|
||||||
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
|
horizons_years,
|
||||||
|
incidence_features,
|
||||||
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
|
strata,
|
||||||
interval_level=0.95): # fmt: skip
|
levels,
|
||||||
|
knots=3,
|
||||||
|
degree=4,
|
||||||
|
interval_level=0.95,
|
||||||
|
):
|
||||||
self.horizons_years = horizons_years
|
self.horizons_years = horizons_years
|
||||||
self.incidence_features = incidence_features
|
self.incidence_features = incidence_features
|
||||||
self.strata = strata
|
self.strata = strata
|
||||||
@@ -213,7 +201,7 @@ class Mixture(BaseEstimator):
|
|||||||
|
|
||||||
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
|
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
|
||||||
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
|
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
|
||||||
return prevalence, self._columns(X, self.incidence_features, seen)
|
return (prevalence, self._columns(X, self.incidence_features, seen))
|
||||||
|
|
||||||
def _groups(self, X: pd.DataFrame):
|
def _groups(self, X: pd.DataFrame):
|
||||||
if not self.strata:
|
if not self.strata:
|
||||||
@@ -222,10 +210,10 @@ 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(
|
||||||
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
|
[X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1
|
||||||
axis=1).assign(w=1.0) # fmt: skip
|
).assign(w=1.0)
|
||||||
self.fits_, self.seen_ = {}, {}
|
self.fits_, self.seen_ = ({}, {})
|
||||||
for key, index in self._groups(X):
|
for key, index in self._groups(X):
|
||||||
group = rows.iloc[index]
|
group = rows.iloc[index]
|
||||||
seen = self._seen(group)
|
seen = self._seen(group)
|
||||||
@@ -236,13 +224,11 @@ class Mixture(BaseEstimator):
|
|||||||
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
|
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
|
||||||
self.seen_[key] = seen
|
self.seen_[key] = seen
|
||||||
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
|
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
|
||||||
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
|
self.neg_loglik_ = float(sum((f.neg_loglik for f in self.fits_.values())))
|
||||||
self.converged_ = all(f.converged for f in self.fits_.values())
|
self.converged_ = all((f.converged for f in self.fits_.values()))
|
||||||
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)
|
||||||
@@ -259,7 +245,12 @@ class Mixture(BaseEstimator):
|
|||||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||||
)
|
)
|
||||||
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
|
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
|
||||||
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
|
band = np.column_stack(
|
||||||
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
[
|
||||||
|
point,
|
||||||
|
np.clip(point * np.exp(-z * relative), 0, 1),
|
||||||
|
np.clip(point * np.exp(z * relative), 0, 1),
|
||||||
|
]
|
||||||
|
)
|
||||||
out[index[placed]] = band[inverse.ravel()]
|
out[index[placed]] = band[inverse.ravel()]
|
||||||
return out
|
return out
|
||||||
|
|||||||
+54
-40
@@ -1,24 +1,12 @@
|
|||||||
"""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
|
||||||
from sklearn.metrics import brier_score_loss
|
from sklearn.metrics import brier_score_loss
|
||||||
|
|
||||||
from models import survival
|
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,11 +28,9 @@ 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))
|
||||||
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
|
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
|
||||||
patterns, counts = np.unique(inside, axis=0, return_counts=True)
|
patterns, counts = np.unique(inside, axis=0, return_counts=True)
|
||||||
p = np.full(len(support), 1 / len(support))
|
p = np.full(len(support), 1 / len(support))
|
||||||
@@ -55,7 +41,7 @@ def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
|
|||||||
p = new
|
p = new
|
||||||
if done:
|
if done:
|
||||||
break
|
break
|
||||||
return support, np.cumsum(p)
|
return (support, np.cumsum(p))
|
||||||
|
|
||||||
|
|
||||||
def _at(support, cumulative, t) -> np.ndarray:
|
def _at(support, cumulative, t) -> np.ndarray:
|
||||||
@@ -73,8 +59,10 @@ def _label(feature: str, value) -> str:
|
|||||||
|
|
||||||
def _band(curve, variance) -> tuple[list, list]:
|
def _band(curve, variance) -> tuple[list, list]:
|
||||||
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
|
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
|
||||||
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
return (
|
||||||
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
||||||
|
np.clip(curve * np.exp(Z * relative), 0, 1).tolist(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
|
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
|
||||||
@@ -83,7 +71,7 @@ def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
|
|||||||
return None
|
return None
|
||||||
prevalence, incidence = mixture._design(row, mixture.seen_[key])
|
prevalence, incidence = mixture._design(row, mixture.seen_[key])
|
||||||
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
|
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
|
||||||
return point[0], variance[0]
|
return (point[0], variance[0])
|
||||||
|
|
||||||
|
|
||||||
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
|
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
|
||||||
@@ -92,8 +80,9 @@ def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) ->
|
|||||||
if isinstance(spec, Logistic):
|
if isinstance(spec, Logistic):
|
||||||
return _logistic(model, data["test"])
|
return _logistic(model, data["test"])
|
||||||
coded = data["coded"]
|
coded = data["coded"]
|
||||||
full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
|
full = Mixture(spec.horizons, spec.incidence_features, spec.strata, model.levels).fit(
|
||||||
model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
|
coded[spec.features], coded[["c", "l", "r"]]
|
||||||
|
)
|
||||||
members = coded.reset_index(drop=True)
|
members = coded.reset_index(drop=True)
|
||||||
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
|
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
|
||||||
horizons = np.asarray(spec.horizons, dtype=float)
|
horizons = np.asarray(spec.horizons, dtype=float)
|
||||||
@@ -105,53 +94,78 @@ def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) ->
|
|||||||
group = members[mask]
|
group = members[mask]
|
||||||
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
||||||
support, cumulative = turnbull(c, l, r)
|
support, cumulative = turnbull(c, l, r)
|
||||||
boot_grid, boot_h = [], []
|
boot_grid, boot_h = ([], [])
|
||||||
for _ in range(BOOTSTRAP):
|
for _ in range(BOOTSTRAP):
|
||||||
pick = rng.integers(0, len(group), len(group))
|
pick = rng.integers(0, len(group), len(group))
|
||||||
s, cum = turnbull(c[pick], l[pick], r[pick])
|
s, cum = turnbull(c[pick], l[pick], r[pick])
|
||||||
boot_grid.append(_at(s, cum, grid))
|
boot_grid.append(_at(s, cum, grid))
|
||||||
boot_h.append(_at(s, cum, horizons))
|
boot_h.append(_at(s, cum, horizons))
|
||||||
observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
|
observed, var_observed = (
|
||||||
|
_at(support, cumulative, horizons),
|
||||||
|
np.var(boot_h, axis=0, ddof=1),
|
||||||
|
)
|
||||||
entry = {
|
entry = {
|
||||||
"combination": combination.to_dict(),
|
"combination": combination.to_dict(),
|
||||||
"n": int(mask.sum()),
|
"n": int(mask.sum()),
|
||||||
"prevalent": int((c == 1).sum()),
|
"prevalent": int((c == 1).sum()),
|
||||||
"incident": int(((c != 1) & np.isfinite(r)).sum()),
|
"incident": int(((c != 1) & np.isfinite(r)).sum()),
|
||||||
"observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
|
"observed": {
|
||||||
|
"years": grid.tolist(),
|
||||||
|
"risk": _at(support, cumulative, grid).tolist(),
|
||||||
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
|
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
|
||||||
"high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
|
"high": np.percentile(boot_grid, 97.5, axis=0).tolist(),
|
||||||
|
},
|
||||||
"predicted": None,
|
"predicted": None,
|
||||||
"expected_over_observed": [],
|
"expected_over_observed": [],
|
||||||
} # fmt: skip
|
}
|
||||||
probe = group.iloc[[0]][spec.features]
|
probe = group.iloc[[0]][spec.features]
|
||||||
at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
|
at_grid, at_h = (_mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons))
|
||||||
if at_grid is not None:
|
if at_grid is not None:
|
||||||
low, high = _band(*at_grid)
|
low, high = _band(*at_grid)
|
||||||
entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
|
entry["predicted"] = {
|
||||||
"low": low, "high": high} # fmt: skip
|
"years": grid.tolist(),
|
||||||
|
"risk": at_grid[0].tolist(),
|
||||||
|
"low": low,
|
||||||
|
"high": high,
|
||||||
|
}
|
||||||
for k, h in enumerate(horizons):
|
for k, h in enumerate(horizons):
|
||||||
e = None if at_h is None else float(at_h[0][k])
|
e = None if at_h is None else float(at_h[0][k])
|
||||||
ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
|
ratio = {
|
||||||
"ratio": None, "low": None, "high": None} # fmt: skip
|
"years": float(h),
|
||||||
|
"expected": e,
|
||||||
|
"observed": float(observed[k]),
|
||||||
|
"ratio": None,
|
||||||
|
"low": None,
|
||||||
|
"high": None,
|
||||||
|
}
|
||||||
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
|
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
|
||||||
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
|
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
|
||||||
value = e / observed[k]
|
value = e / observed[k]
|
||||||
ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
|
ratio |= {
|
||||||
"high": value * np.exp(Z * se)} # fmt: skip
|
"ratio": value,
|
||||||
|
"low": value * np.exp(-Z * se),
|
||||||
|
"high": value * np.exp(Z * se),
|
||||||
|
}
|
||||||
entry["expected_over_observed"].append(ratio)
|
entry["expected_over_observed"].append(ratio)
|
||||||
groups.append(entry)
|
groups.append(entry)
|
||||||
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
|
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
|
||||||
return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
|
return {
|
||||||
"groups": groups} # fmt: skip
|
"model": spec.name,
|
||||||
|
"kind": "subgroups",
|
||||||
|
"bootstrap": BOOTSTRAP,
|
||||||
|
"seed": SEED,
|
||||||
|
"groups": groups,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
||||||
classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
|
classifier, encoder = (model.named_steps["classify"], model.named_steps["encode"])
|
||||||
names = encoder.get_feature_names_out()
|
names = encoder.get_feature_names_out()
|
||||||
p = test["p"]
|
p = test["p"]
|
||||||
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
|
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
|
||||||
table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
|
table = test.groupby(deciles, observed=True).agg(
|
||||||
observed=("y", "mean")) # fmt: skip
|
n=("y", "size"), predicted=("p", "mean"), observed=("y", "mean")
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
"model": "logistic regression",
|
"model": "logistic regression",
|
||||||
"kind": "coefficients",
|
"kind": "coefficients",
|
||||||
@@ -168,5 +182,5 @@ def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
|||||||
}
|
}
|
||||||
for k, v in table.iterrows()
|
for k, v in table.iterrows()
|
||||||
],
|
],
|
||||||
}, # fmt: skip
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
+69
-50
@@ -1,17 +1,11 @@
|
|||||||
"""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
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from sklearn.linear_model import LogisticRegression
|
from sklearn.linear_model import LogisticRegression
|
||||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||||
from sklearn.pipeline import Pipeline
|
from sklearn.pipeline import Pipeline
|
||||||
from sklearn.preprocessing import OneHotEncoder
|
from sklearn.preprocessing import OneHotEncoder
|
||||||
|
|
||||||
from core import cacu
|
from core import cacu
|
||||||
from models.cacu import features as f
|
from models.cacu import features as f
|
||||||
from models.cacu.pim import Mixture
|
from models.cacu.pim import Mixture
|
||||||
@@ -23,19 +17,20 @@ 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])
|
||||||
n = len(members)
|
n = len(members)
|
||||||
frame = pd.DataFrame({
|
frame = pd.DataFrame(
|
||||||
|
{
|
||||||
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||||
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
||||||
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
||||||
"probability": risks[:, :h].ravel(),
|
"probability": risks[:, :h].ravel(),
|
||||||
}) # fmt: skip
|
}
|
||||||
|
)
|
||||||
if risks.shape[1] == 3 * h:
|
if risks.shape[1] == 3 * h:
|
||||||
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
frame["ci_low"], frame["ci_high"] = (risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel())
|
||||||
else:
|
else:
|
||||||
frame["ci_low"] = frame["ci_high"] = np.nan
|
frame["ci_low"] = frame["ci_high"] = np.nan
|
||||||
return frame[OUTPUT]
|
return frame[OUTPUT]
|
||||||
@@ -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)
|
||||||
@@ -74,13 +65,12 @@ class Pim:
|
|||||||
levels[self.history["feature"]] = list(self.history["levels"])
|
levels[self.history["feature"]] = list(self.history["levels"])
|
||||||
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
|
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
|
||||||
mixture.fit(train[self.features], train[["c", "l", "r"]])
|
mixture.fit(train[self.features], train[["c", "l", "r"]])
|
||||||
return mixture, self.metrics(mixture, train, test), {"coded": coded}
|
return (mixture, self.metrics(mixture, train, test), {"coded": coded})
|
||||||
|
|
||||||
def metrics(self, mixture: Mixture, train, test) -> dict:
|
def metrics(self, mixture: Mixture, train, test) -> dict:
|
||||||
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_,
|
||||||
@@ -88,11 +78,11 @@ class Pim:
|
|||||||
}
|
}
|
||||||
risks = mixture.predict(test[self.features])
|
risks = mixture.predict(test[self.features])
|
||||||
for column, horizon in enumerate(self.horizons):
|
for column, horizon in enumerate(self.horizons):
|
||||||
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
|
case = (test["c"] == 1) | (test["c"] != 1) & (test["r"] <= horizon)
|
||||||
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
|
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
|
||||||
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
|
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
|
||||||
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
|
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
|
||||||
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
|
y, p, tag = (status[known], risks[known, column], f"{horizon:g}y")
|
||||||
found[f"n_known_{tag}"] = int(known.sum())
|
found[f"n_known_{tag}"] = int(known.sum())
|
||||||
if known.any():
|
if known.any():
|
||||||
found[f"observed_{tag}"] = float(y.mean())
|
found[f"observed_{tag}"] = float(y.mean())
|
||||||
@@ -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,18 +113,19 @@ 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, pd.Timestamp(follow_up_end))
|
||||||
pd.Timestamp(follow_up_end)) # fmt: skip
|
|
||||||
labelled = found.merge(outcome, on="person_id")
|
labelled = found.merge(outcome, on="person_id")
|
||||||
labelled = labelled[labelled["known"]].reset_index(drop=True)
|
labelled = labelled[labelled["known"]].reset_index(drop=True)
|
||||||
train, test = f.split(labelled, TRAIN_FRACTION)
|
train, test = f.split(labelled, TRAIN_FRACTION)
|
||||||
X = list(self.predictors)
|
X = list(self.predictors)
|
||||||
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
|
model = Pipeline(
|
||||||
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
|
[
|
||||||
|
("encode", OneHotEncoder(handle_unknown="ignore")),
|
||||||
|
("classify", LogisticRegression(max_iter=1000)),
|
||||||
|
]
|
||||||
|
)
|
||||||
model.fit(train[X], train["y"])
|
model.fit(train[X], train["y"])
|
||||||
p = model.predict_proba(test[X])[:, 1]
|
p = model.predict_proba(test[X])[:, 1]
|
||||||
metrics = {
|
metrics = {
|
||||||
@@ -150,7 +139,7 @@ class Logistic:
|
|||||||
"positive_rate_test": float(test["y"].mean()),
|
"positive_rate_test": float(test["y"].mean()),
|
||||||
"mean_probability_test": float(p.mean()),
|
"mean_probability_test": float(p.mean()),
|
||||||
}
|
}
|
||||||
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
|
return (model, metrics, {"labelled": labelled, "test": test.assign(p=p)})
|
||||||
|
|
||||||
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
|
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
|
||||||
members = f.index_sample(f.prepared(events), list(self.predictors))
|
members = f.index_sample(f.prepared(events), list(self.predictors))
|
||||||
@@ -160,8 +149,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"]]
|
||||||
@@ -178,28 +165,60 @@ def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataF
|
|||||||
|
|
||||||
|
|
||||||
_REFERRAL = {
|
_REFERRAL = {
|
||||||
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
"feature": "referral_grade",
|
||||||
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
|
"lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
||||||
|
"levels": ["low", "high"],
|
||||||
|
"low": ["ASC-US/LSIL"],
|
||||||
|
"low_if_hpv_positive": ["NILM"],
|
||||||
"high": ["High Grade"],
|
"high": ["High Grade"],
|
||||||
} # fmt: skip
|
}
|
||||||
|
|
||||||
MODELS = {
|
MODELS = {
|
||||||
m.name: m
|
m.name: m
|
||||||
for m in [
|
for m in [
|
||||||
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
|
Pim(
|
||||||
strata=("hpv_positive",), incidence_features=("cytology",),
|
"cin2_pim",
|
||||||
predict_at="last_screening_cytology"),
|
"cacu_cohort_surveillance",
|
||||||
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
|
cacu.CIN2_PLUS,
|
||||||
strata=("hpv_positive",), incidence_features=("cytology",),
|
cacu.KPNC,
|
||||||
predict_at="last_screening_cytology"),
|
strata=("hpv_positive",),
|
||||||
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
|
incidence_features=("cytology",),
|
||||||
cacu.KPNC_3, strata=("referral_grade",),
|
predict_at="last_screening_cytology",
|
||||||
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
),
|
||||||
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
|
Pim(
|
||||||
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
|
"cancer_pim",
|
||||||
|
"cacu_cohort_surveillance",
|
||||||
|
cacu.CANCER,
|
||||||
|
cacu.KPNC,
|
||||||
|
strata=("hpv_positive",),
|
||||||
|
incidence_features=("cytology",),
|
||||||
|
predict_at="last_screening_cytology",
|
||||||
|
),
|
||||||
|
Pim(
|
||||||
|
"cin2_pim_post_colposcopy",
|
||||||
|
"cacu_cohort_post_colposcopy",
|
||||||
|
cacu.CIN2_PLUS,
|
||||||
|
cacu.KPNC_3,
|
||||||
|
strata=("referral_grade",),
|
||||||
|
incidence_features=("cytology", "hpv_positive"),
|
||||||
|
history=_REFERRAL,
|
||||||
|
),
|
||||||
|
Pim(
|
||||||
|
"cin2_pim_post_treatment",
|
||||||
|
"cacu_cohort_post_treatment",
|
||||||
|
cacu.CIN2_PLUS,
|
||||||
|
cacu.KPNC_3,
|
||||||
|
strata=(),
|
||||||
|
incidence_features=("cytology", "hpv_positive"),
|
||||||
|
),
|
||||||
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
||||||
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
Spec(
|
||||||
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
"survival",
|
||||||
interval_level=0.95),
|
"cacu_cohort_survival",
|
||||||
|
("age_group", "cytology", "hpv"),
|
||||||
|
survival_covariates,
|
||||||
|
borders=(0, 12, 36, 60),
|
||||||
|
cap_months=60,
|
||||||
|
interval_level=0.95,
|
||||||
|
),
|
||||||
]
|
]
|
||||||
} # fmt: skip
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
+1
-3
@@ -1,8 +1,6 @@
|
|||||||
"""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
|
||||||
|
|
||||||
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
|
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
|
||||||
train, score = JOBS.train, JOBS.score
|
train, score = (JOBS.train, JOBS.score)
|
||||||
|
|||||||
@@ -1,45 +1,20 @@
|
|||||||
"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
|
|
||||||
learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
|
|
||||||
published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
|
|
||||||
regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
|
|
||||||
(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
|
|
||||||
with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by
|
|
||||||
four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's,
|
|
||||||
refitted on each whole horizon cohort."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
import joblib
|
import joblib
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||||
|
|
||||||
SOURCES = ("metabric", "scanb")
|
HORIZONS = modeling.HORIZONS
|
||||||
HORIZONS = modeling.HORIZONS # months
|
|
||||||
SAVED = "metabric"
|
|
||||||
|
|
||||||
|
|
||||||
def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
"""The source's cohort table, from its dataset's rows: fixed columns, then its
|
|
||||||
covariates as categories."""
|
|
||||||
return cohorts.prepare(source, rows).frame
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@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)
|
||||||
@@ -59,28 +34,18 @@ class Recurrence:
|
|||||||
return pd.DataFrame(out, index=X.index)
|
return pd.DataFrame(out, index=X.index)
|
||||||
|
|
||||||
|
|
||||||
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
|
||||||
"""Both reference cohorts' models, validation, calculator and risk factors, from their
|
|
||||||
datasets' rows; the saved model is METABRIC's.
|
|
||||||
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
|
|
||||||
stability criterion, are then missing)."""
|
|
||||||
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
|
|
||||||
return fit(found, SAVED, "metabric+scanb", bootstrap)
|
|
||||||
|
|
||||||
|
|
||||||
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 same, on the site's own cohort (models.cama.recurrence.site)."""
|
|
||||||
from models.cama.recurrence import site
|
from models.cama.recurrence import site
|
||||||
|
|
||||||
return fit({"site": site.prepare(rows)}, "site", "site", bootstrap)
|
return fit(
|
||||||
|
{"site": site.prepare(rows)}, "site", "site", modeling.N_BOOTSTRAP if bootstrap else {}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def fit(found: dict, saved: str, label: str,
|
def fit(
|
||||||
bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
found: dict, saved: str, label: str, n_bootstrap: dict[str, int]
|
||||||
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
) -> tuple[Recurrence, dict, dict]:
|
||||||
the `saved` cohort's is the model kept."""
|
|
||||||
sources = list(found)
|
sources = list(found)
|
||||||
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
|
|
||||||
try:
|
try:
|
||||||
fits = modeling.fit(found, n_bootstrap)
|
fits = modeling.fit(found, n_bootstrap)
|
||||||
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
||||||
@@ -105,4 +70,4 @@ def fit(found: dict, saved: str, label: str,
|
|||||||
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
|
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
|
||||||
}
|
}
|
||||||
reports_ = {"technical_validation": technical, "interpretability": interpretability}
|
reports_ = {"technical_validation": technical, "interpretability": interpretability}
|
||||||
return model, reports.metrics(auc), reports_
|
return (model, reports.metrics(auc), reports_)
|
||||||
|
|||||||
@@ -1,65 +1,15 @@
|
|||||||
"""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
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import statsmodels.api as sm
|
import statsmodels.api as sm
|
||||||
from joblib import Parallel, delayed
|
from joblib import Parallel, delayed
|
||||||
|
|
||||||
from models import curves
|
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
|
||||||
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"}
|
|
||||||
|
|
||||||
# Each scenario: covariate -> the categories it takes (AND across covariates).
|
|
||||||
SCENARIOS = {
|
|
||||||
"metabric": {
|
|
||||||
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
|
||||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
|
||||||
"Tamano_tumor": ["<=20 mm"]},
|
|
||||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
|
||||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
|
||||||
"< 45 años": {"Edad": ["<45"]},
|
|
||||||
"≥ 75 años": {"Edad": ["75+"]},
|
|
||||||
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
|
||||||
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
|
||||||
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
|
||||||
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
|
||||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
|
||||||
"Cirugia": ["BREAST CONSERVING"]},
|
|
||||||
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
|
||||||
},
|
|
||||||
"scanb": {
|
|
||||||
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
|
||||||
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
|
|
||||||
"Tamano_tumor": ["<=20 mm"]},
|
|
||||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
|
||||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
|
||||||
"< 45 años": {"Edad": ["<45"]},
|
|
||||||
"≥ 75 años": {"Edad": ["75+"]},
|
|
||||||
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
|
||||||
"HER2+ (luminal B HER2+ o no luminal)": {
|
|
||||||
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
|
||||||
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
|
||||||
"Luminal · 1-3 ganglios · lumpectomía": {
|
|
||||||
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
|
|
||||||
"Cirugia": ["Lumpectomy"]},
|
|
||||||
"Grado 3": {"Grado_histologico": ["3"]},
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
SCENARIOS["site"] = SCENARIOS["scanb"] # the site's cohort is described as SCAN-B's
|
|
||||||
|
|
||||||
|
|
||||||
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
||||||
@@ -71,17 +21,15 @@ 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):
|
||||||
frame, covariates = self.fitted.cohort.frame, self.fitted.cohort.covariates
|
frame, covariates = (self.fitted.cohort.frame, self.fitted.cohort.covariates)
|
||||||
self.n = len(frame)
|
self.n = len(frame)
|
||||||
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
||||||
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
|
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
|
||||||
self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()}
|
self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()}
|
||||||
self.time, self.event = frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()
|
self.time, self.event = (frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy())
|
||||||
|
|
||||||
def _key(self, chosen, rows) -> np.ndarray:
|
def _key(self, chosen, rows) -> np.ndarray:
|
||||||
key = np.zeros(len(rows), dtype=np.int64)
|
key = np.zeros(len(rows), dtype=np.int64)
|
||||||
@@ -90,11 +38,10 @@ 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)
|
||||||
train, y = rows[known], recurred[known].astype(int)
|
train, y = (rows[known], recurred[known].astype(int))
|
||||||
split = self.fitted.horizons[horizon].split
|
split = self.fitted.horizons[horizon].split
|
||||||
p_lr = p_hbn = np.full(self.n, y.mean())
|
p_lr = p_hbn = np.full(self.n, y.mean())
|
||||||
if split.terms:
|
if split.terms:
|
||||||
@@ -114,8 +61,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)
|
||||||
@@ -143,33 +88,32 @@ def _curves(months, event, observed):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def calculator(fitted: CohortFit, scenarios: dict | None = None) -> 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 = SCENARIOS[source] if scenarios is None else 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]
|
||||||
records, rows = [], []
|
records, rows = ([], [])
|
||||||
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
|
for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True):
|
||||||
free = 1 - point[name]
|
free = 1 - point[name]
|
||||||
risks = np.array([r[name] for r in replicas])
|
risks = np.array([r[name] for r in replicas])
|
||||||
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0)
|
low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0)
|
||||||
observed, n, events = int(months[mask].max()), int(mask.sum()), int(event[mask].sum())
|
observed, n, events = (int(months[mask].max()), int(mask.sum()), int(event[mask].sum()))
|
||||||
km, grid = drawn_curves["km"], drawn_curves["grid"].tolist()
|
km, grid = (drawn_curves["km"], drawn_curves["grid"].tolist())
|
||||||
records.append(
|
records.append(
|
||||||
{
|
{
|
||||||
"cohorte": source,
|
"cohorte": source,
|
||||||
"cohorte_nombre": LABELS[source],
|
"cohorte_nombre": fitted.cohort.label,
|
||||||
"escenario": name,
|
"escenario": name,
|
||||||
"condiciones": scenarios[name],
|
"condiciones": scenarios[name],
|
||||||
"n": n,
|
"n": n,
|
||||||
@@ -209,4 +153,4 @@ def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[d
|
|||||||
"replicas_bootstrap": len(replicas),
|
"replicas_bootstrap": len(replicas),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return records, rows
|
return (records, rows)
|
||||||
|
|||||||
@@ -1,64 +1,22 @@
|
|||||||
"""Each reference cohort as one table of categories, from its dataset as the platform loaded
|
|
||||||
it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
|
|
||||||
`line` the order the file is published in): the patients with a known recurrence time and
|
|
||||||
status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
|
|
||||||
covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN);
|
|
||||||
nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's
|
|
||||||
V >= V_MAX), the one with more unknowns is dropped."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from scipy.stats.contingency import association
|
from scipy.stats.contingency import association
|
||||||
|
|
||||||
UNKNOWN = "Desconocido"
|
UNKNOWN = "Desconocido"
|
||||||
V_MAX = 0.80
|
V_MAX = 0.8
|
||||||
DAYS_PER_MONTH = 30.4375
|
DAYS_PER_MONTH = 30.4375
|
||||||
|
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, 10000.0], ["<=20 mm", "21-50 mm", ">50 mm"])
|
||||||
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
NODES = ([0, 1, 4, 1000.0], ["0", "1-3", "4+"])
|
||||||
GRADES = {"1": "1", "2": "2", "3": "3"}
|
GRADES = {"1": "1", "2": "2", "3": "3"}
|
||||||
|
|
||||||
FIXED = {
|
|
||||||
"metabric": ["paciente", "tiempo_meses", "evento"],
|
|
||||||
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
|
||||||
}
|
|
||||||
TREATMENT = {
|
|
||||||
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
|
||||||
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
|
||||||
}
|
|
||||||
# Covariates taken as they come (our name: the dataset's column).
|
|
||||||
PASSTHROUGH = {
|
|
||||||
"metabric": {
|
|
||||||
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
|
||||||
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
|
|
||||||
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
|
|
||||||
"Estado_menopausico": "inferred_menopausal_state",
|
|
||||||
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
|
|
||||||
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
|
|
||||||
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
|
|
||||||
},
|
|
||||||
"scanb": {
|
|
||||||
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
|
||||||
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
|
||||||
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
|
||||||
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
|
||||||
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
|
||||||
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
|
||||||
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
|
||||||
|
|
||||||
|
|
||||||
def _number(s: pd.Series) -> pd.Series:
|
def _number(s: pd.Series) -> pd.Series:
|
||||||
return pd.to_numeric(s, errors="coerce")
|
return pd.to_numeric(s, errors="coerce")
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
|
|
||||||
@@ -66,56 +24,12 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
|
|||||||
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
||||||
|
|
||||||
|
|
||||||
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
|
||||||
|
|
||||||
|
|
||||||
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
|
||||||
d = d.reset_index(drop=True)
|
|
||||||
out = pd.DataFrame({"paciente": d["patient_id"]})
|
|
||||||
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
|
||||||
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
|
||||||
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
|
||||||
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
|
||||||
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
|
||||||
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
|
||||||
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
|
||||||
load = _number(d["mutation_count"])
|
|
||||||
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
|
||||||
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
|
||||||
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
|
||||||
for name, column in PASSTHROUGH["metabric"].items():
|
|
||||||
out[name] = _text(d[column])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
d = _in_order(rows)
|
|
||||||
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
|
||||||
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
|
||||||
out = pd.DataFrame({"paciente": d["patient_name"]})
|
|
||||||
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
|
||||||
out["evento"] = rfi.astype(int)
|
|
||||||
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
|
||||||
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
|
||||||
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
|
||||||
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
|
||||||
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
|
||||||
for name, column in PASSTHROUGH["scanb"].items():
|
|
||||||
out[name] = _text(d[column])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
||||||
table = pd.crosstab(a, b).to_numpy()
|
table = pd.crosstab(a, b).to_numpy()
|
||||||
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
||||||
|
|
||||||
|
|
||||||
def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]:
|
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)
|
||||||
@@ -136,33 +50,23 @@ 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
|
||||||
|
scenarios: dict
|
||||||
|
sampling: dict
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def intrinsic(self) -> list[str]:
|
def intrinsic(self) -> list[str]:
|
||||||
return [c for c in self.covariates if c not in self.treatment]
|
return [c for c in self.covariates if c not in self.treatment]
|
||||||
|
|
||||||
|
|
||||||
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
|
||||||
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
|
||||||
fixed, treatment = FIXED[source], TREATMENT[source]
|
|
||||||
covariates = [c for c in full.columns if c not in fixed]
|
|
||||||
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
|
||||||
kept = [c for c in covariates if c not in dropped]
|
|
||||||
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped)
|
|
||||||
|
|
||||||
|
|
||||||
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
||||||
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
t, event = (frame["tiempo_meses"], frame["evento"] == 1)
|
||||||
followed past it), with `y` = recurred by then."""
|
found = frame[event & (t <= horizon) | (t > horizon)].reset_index(drop=True)
|
||||||
t, event = frame["tiempo_meses"], frame["evento"] == 1
|
|
||||||
found = frame[(event & (t <= horizon)) | (t > horizon)].reset_index(drop=True)
|
|
||||||
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
|
found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int)
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,8 @@
|
|||||||
"""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
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from models import factors as rated
|
from models import factors as rated
|
||||||
from models.cama.recurrence.calculator import SCENARIOS, masks
|
from models.cama.recurrence.calculator import masks
|
||||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
||||||
from models.cama.recurrence.modeling import CohortFit
|
from models.cama.recurrence.modeling import CohortFit
|
||||||
from models.factors import FREQ_MIN, ORDER
|
from models.factors import FREQ_MIN, ORDER
|
||||||
@@ -47,17 +41,18 @@ DESCRIBING = rated.DESCRIBING
|
|||||||
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
|
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
|
||||||
cohort = fitted.cohort
|
cohort = fitted.cohort
|
||||||
frame = at_horizon(cohort.frame, horizon)
|
frame = at_horizon(cohort.frame, horizon)
|
||||||
data, y = frame[cohort.covariates].astype(str), frame["y"].to_numpy()
|
data, y = (frame[cohort.covariates].astype(str), frame["y"].to_numpy())
|
||||||
reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates}
|
reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates}
|
||||||
t, everyone = cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]
|
t, everyone = (cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates])
|
||||||
months = np.floor(np.minimum(t, horizon + 1)).astype(int)
|
months = np.floor(np.minimum(t, horizon + 1)).astype(int)
|
||||||
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
|
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
|
||||||
|
|
||||||
def complete(table, variables):
|
def complete(table, variables):
|
||||||
return rated.complete(table, variables, reference, everyone, months, event, horizon,
|
return rated.complete(
|
||||||
SURVIVAL) # fmt: skip
|
table, variables, reference, everyone, months, event, horizon, SURVIVAL
|
||||||
|
)
|
||||||
|
|
||||||
intrinsic, treatment = cohort.intrinsic, cohort.treatment
|
intrinsic, treatment = (cohort.intrinsic, cohort.treatment)
|
||||||
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
|
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
|
||||||
hz = fitted.horizons[horizon]
|
hz = fitted.horizons[horizon]
|
||||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
||||||
@@ -74,21 +69,18 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
|
|||||||
tr = complete(
|
tr = complete(
|
||||||
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
||||||
)
|
)
|
||||||
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
|
tr["tipo"], tr["clasificacion"] = ("tratamiento", TREATMENT_CLASS)
|
||||||
tab = pd.concat([tab, tr], ignore_index=True)
|
tab = pd.concat([tab, tr], ignore_index=True)
|
||||||
tab["cohorte"], tab["horizonte_meses"] = cohort.source, horizon
|
tab["cohorte"], tab["horizonte_meses"] = (cohort.source, horizon)
|
||||||
return tab
|
return tab
|
||||||
|
|
||||||
|
|
||||||
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,20 +91,23 @@ 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
|
frame, source = (fitted.cohort.frame, fitted.cohort.source)
|
||||||
patients have (definitorios) or most have (mayoritarios)."""
|
scenarios = fitted.cohort.scenarios
|
||||||
frame, source = fitted.cohort.frame, fitted.cohort.source
|
|
||||||
scenarios = SCENARIOS[source]
|
|
||||||
found = rated.classified(factors[factors["cohorte"] == source])
|
found = rated.classified(factors[factors["cohorte"] == source])
|
||||||
rows = []
|
rows = []
|
||||||
for name, mask in masks(frame, scenarios).items():
|
for name, mask in masks(frame, scenarios).items():
|
||||||
if not mask.any() or found.empty:
|
if not mask.any() or found.empty:
|
||||||
continue
|
continue
|
||||||
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
|
definition = "; ".join((f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items()))
|
||||||
for h in fitted.horizons:
|
for h in fitted.horizons:
|
||||||
rows.append({
|
rows.append(
|
||||||
"cohorte": source, "escenario": name, "definicion": definition,
|
{
|
||||||
"n_escenario": int(mask.sum()), "horizonte_meses": h,
|
"cohorte": source,
|
||||||
|
"escenario": name,
|
||||||
|
"definicion": definition,
|
||||||
|
"n_escenario": int(mask.sum()),
|
||||||
|
"horizonte_meses": h,
|
||||||
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
|
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
|
||||||
}) # fmt: skip
|
}
|
||||||
|
)
|
||||||
return rows
|
return rows
|
||||||
|
|||||||
@@ -1,15 +1,5 @@
|
|||||||
"""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
|
||||||
|
|
||||||
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
|
||||||
@@ -19,34 +9,26 @@ from lifelines.utils import concordance_index
|
|||||||
from pgmpy.structure_score import BDeu
|
from pgmpy.structure_score import BDeu
|
||||||
from sklearn.metrics import roc_auc_score
|
from sklearn.metrics import roc_auc_score
|
||||||
from sklearn.model_selection import train_test_split
|
from sklearn.model_selection import train_test_split
|
||||||
|
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
|
||||||
from models.cama.recurrence.cohorts import Cohort, at_horizon
|
|
||||||
from models.factors import variable_of
|
from models.factors import variable_of
|
||||||
|
|
||||||
HORIZONS = (12, 36, 60) # months
|
|
||||||
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.1, 0.1, 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 = {"metabric": 100, "scanb": 40, "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")
|
||||||
@@ -57,17 +39,15 @@ 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)
|
||||||
for c in X.columns:
|
for c in X.columns:
|
||||||
if c in included:
|
if c in included:
|
||||||
continue
|
continue
|
||||||
m = logit(y, X[included + [c]])
|
m = logit(y, X[included + [c]])
|
||||||
if m is not None and m.pvalues[c] < best_p:
|
if m is not None and m.pvalues[c] < best_p:
|
||||||
best, best_p = c, m.pvalues[c]
|
best, best_p = (c, m.pvalues[c])
|
||||||
if best is not None:
|
if best is not None:
|
||||||
included.append(best)
|
included.append(best)
|
||||||
changed = True
|
changed = True
|
||||||
@@ -82,8 +62,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]
|
||||||
@@ -95,13 +73,10 @@ def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
|
|||||||
]
|
]
|
||||||
terms = stepwise(X_train[candidates], y) if candidates else []
|
terms = stepwise(X_train[candidates], y) if candidates else []
|
||||||
if not terms:
|
if not terms:
|
||||||
return [], np.full(len(test), y.mean())
|
return ([], np.full(len(test), y.mean()))
|
||||||
m = logit(y, X_train[terms])
|
m = logit(y, X_train[terms])
|
||||||
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
|
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
|
||||||
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:
|
||||||
@@ -111,16 +86,14 @@ 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:
|
||||||
best, gain = None, 0.0
|
best, gain = (None, 0.0)
|
||||||
for c in [c for c in covariates if c not in chosen]:
|
for c in [c for c in covariates if c not in chosen]:
|
||||||
g = score.local_score("outcome", (*chosen, c)) - current
|
g = score.local_score("outcome", (*chosen, c)) - current
|
||||||
if g > gain:
|
if g > gain:
|
||||||
best, gain = c, g
|
best, gain = (c, g)
|
||||||
if best is None:
|
if best is None:
|
||||||
break
|
break
|
||||||
chosen.append(best)
|
chosen.append(best)
|
||||||
@@ -129,20 +102,16 @@ 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")
|
||||||
return {
|
return {
|
||||||
(k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
|
k if isinstance(k, tuple) else (k,): float((r.n1 + a) / (r.n + 2 * a))
|
||||||
for k, r in counts.iterrows()
|
for k, r in counts.iterrows()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -150,13 +119,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
|
||||||
@@ -168,15 +132,13 @@ def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> S
|
|||||||
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
|
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
|
||||||
)
|
)
|
||||||
terms, p_lr = lr(train, test, covariates)
|
terms, p_lr = lr(train, test, covariates)
|
||||||
bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
|
bn_train, bn_test = (bn_table(train, covariates), bn_table(test, covariates))
|
||||||
chosen = parents(bn_train, covariates)
|
chosen = parents(bn_train, covariates)
|
||||||
p_hbn = hbn(bn_train, bn_test, chosen)
|
p_hbn = hbn(bn_train, bn_test, chosen)
|
||||||
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
|
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
|
||||||
|
|
||||||
|
|
||||||
def _replicate(frame, covariates, rows, b) -> Split | None:
|
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:
|
||||||
@@ -184,8 +146,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
|
||||||
@@ -206,9 +166,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
|
||||||
@@ -219,7 +176,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 = {}
|
||||||
@@ -237,8 +193,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():
|
||||||
@@ -250,31 +204,29 @@ def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, Co
|
|||||||
]
|
]
|
||||||
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
|
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
|
||||||
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
|
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
|
||||||
done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks))
|
done = Parallel(n_jobs=-1)((delayed(f)(*args) for _, f, args in reversed(tasks)))
|
||||||
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
|
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
|
||||||
out = {}
|
out = {}
|
||||||
for s, cohort in cohorts.items():
|
for s, cohort in cohorts.items():
|
||||||
horizons = {}
|
horizons = {}
|
||||||
for h in HORIZONS:
|
for h in HORIZONS:
|
||||||
frame = frames[(s, h)]
|
frame = frames[s, h]
|
||||||
reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
|
reps = [results[s, h, b] for b in range(n_bootstrap.get(s, 0))]
|
||||||
horizons[h] = Horizon(
|
horizons[h] = Horizon(
|
||||||
len(frame),
|
len(frame),
|
||||||
int(frame["y"].sum()),
|
int(frame["y"].sum()),
|
||||||
results[(s, h, "split")],
|
results[s, h, "split"],
|
||||||
[r for r in reps if r is not None],
|
[r for r in reps if r is not None],
|
||||||
)
|
)
|
||||||
out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
|
out[s] = CohortFit(cohort, results[s, None, "cox"], horizons)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
|
covariates, terms, chosen = (fitted.cohort.covariates, hz.split.terms, hz.split.parents)
|
||||||
prior = float(frame["y"].mean())
|
prior = float(frame["y"].mean())
|
||||||
entry = {
|
entry = {
|
||||||
"lr_prior": prior,
|
"lr_prior": prior,
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
"""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
|
||||||
|
|
||||||
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
|
from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES
|
||||||
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
|
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares
|
||||||
from models.cama.recurrence.modeling import (
|
from models.cama.recurrence.modeling import (
|
||||||
@@ -34,7 +28,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,9 +36,7 @@ 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
|
source, rows = (fitted.cohort.source, [])
|
||||||
replicates (mean, 2.5 and 97.5 percentiles); then the Cox model's C-index."""
|
|
||||||
source, rows = fitted.cohort.source, []
|
|
||||||
for h, hz in fitted.horizons.items():
|
for 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))):
|
||||||
aucs = hz.aucs[:, j]
|
aucs = hz.aucs[:, j]
|
||||||
@@ -77,12 +68,10 @@ def auc_rows(fitted: CohortFit) -> list[dict]:
|
|||||||
"AUC_validacion_interna": fitted.c_index,
|
"AUC_validacion_interna": fitted.c_index,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in rows]
|
return [{k: round(v, 4) if isinstance(v, float) else v for k, v in r.items()} for r in rows]
|
||||||
|
|
||||||
|
|
||||||
def metrics(auc: list[dict]) -> dict[str, float]:
|
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":
|
||||||
@@ -95,19 +84,7 @@ def metrics(auc: list[dict]) -> dict[str, float]:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
REFERENCE_SAMPLING = {
|
|
||||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
|
||||||
"origen": "METABRIC y SCAN-B (externas)",
|
|
||||||
}
|
|
||||||
SITE_SAMPLING = {
|
|
||||||
"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",
|
|
||||||
"origen": "la sede (sus propias pacientes)",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
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": {
|
||||||
@@ -119,16 +96,14 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
|||||||
}
|
}
|
||||||
for s, c in cohorts.items()
|
for s, c in cohorts.items()
|
||||||
},
|
},
|
||||||
**(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING),
|
**next(iter(cohorts.values())).sampling,
|
||||||
},
|
},
|
||||||
"DATOS_FALTANTES": {
|
"DATOS_FALTANTES": {
|
||||||
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); no se imputa ni se descarta",
|
||||||
"no se imputa ni se descarta",
|
|
||||||
"desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
|
"desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()},
|
||||||
},
|
},
|
||||||
"METODO_ANALITICO": {
|
"METODO_ANALITICO": {
|
||||||
"modelos": "regresión logística con selección stepwise y red bayesiana con padres "
|
"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
|
||||||
"del desenlace por BDeu, uno por horizonte",
|
|
||||||
"horizontes_meses": list(HORIZONS),
|
"horizontes_meses": list(HORIZONS),
|
||||||
"alfa_entrada": ALPHA_IN,
|
"alfa_entrada": ALPHA_IN,
|
||||||
"alfa_salida": ALPHA_OUT,
|
"alfa_salida": ALPHA_OUT,
|
||||||
@@ -139,23 +114,17 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
|||||||
},
|
},
|
||||||
"BALANCE_CLASES": {
|
"BALANCE_CLASES": {
|
||||||
"aplica": False,
|
"aplica": False,
|
||||||
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres "
|
"motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea",
|
||||||
"de ella después; no se rebalancea",
|
|
||||||
},
|
},
|
||||||
"CONFIANZA_SALIDA": {
|
"CONFIANZA_SALIDA": {
|
||||||
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
|
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap",
|
||||||
"bootstrap",
|
"replicas": {**{s: n_bootstrap.get(s, 0) for s in cohorts}, "calculadora": RESAMPLES},
|
||||||
"replicas": {
|
|
||||||
**{s: n_bootstrap.get(s, 0) for s in cohorts},
|
|
||||||
"calculadora": RESAMPLES,
|
|
||||||
},
|
|
||||||
"eventos_minimos_por_escenario": MIN_EVENTS,
|
"eventos_minimos_por_escenario": MIN_EVENTS,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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": {
|
||||||
@@ -168,5 +137,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}
|
||||||
|
|||||||
@@ -1,39 +1,65 @@
|
|||||||
"""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
|
||||||
|
|
||||||
from models.cama.recurrence import cohorts
|
from models.cama.recurrence import cohorts
|
||||||
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
|
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
|
||||||
|
|
||||||
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 = {
|
||||||
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
|
"0": "0",
|
||||||
|
"I": "I",
|
||||||
|
"IA": "I",
|
||||||
|
"IB": "I",
|
||||||
|
"II": "II",
|
||||||
|
"IIA": "II",
|
||||||
|
"IIB": "II",
|
||||||
|
"III": "III",
|
||||||
|
"IIIA": "III",
|
||||||
|
"IIIB": "III",
|
||||||
|
"IIIC": "III",
|
||||||
|
"IV": "IV",
|
||||||
|
}
|
||||||
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
|
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
|
||||||
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
|
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
|
||||||
TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
|
TREATMENTS = {
|
||||||
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
"Quimioterapia": "chemotherapy",
|
||||||
|
"Radioterapia": "radiotherapy",
|
||||||
|
"Hormonoterapia": "hormone_therapy",
|
||||||
|
"AntiHER2": "anti_her2",
|
||||||
|
}
|
||||||
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
||||||
TREATMENT = ["Cirugia", *TREATMENTS]
|
TREATMENT = ["Cirugia", *TREATMENTS]
|
||||||
|
SCENARIOS = {
|
||||||
|
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||||
|
"Subtipo_clinico": ["Luminal A"],
|
||||||
|
"Ganglios_positivos": ["0"],
|
||||||
|
"Tamano_tumor": ["<=20 mm"],
|
||||||
|
},
|
||||||
|
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||||
|
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||||
|
"< 45 años": {"Edad": ["<45"]},
|
||||||
|
"≥ 75 años": {"Edad": ["75+"]},
|
||||||
|
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
||||||
|
"HER2+ (luminal B HER2+ o no luminal)": {
|
||||||
|
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]
|
||||||
|
},
|
||||||
|
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
||||||
|
"Luminal · 1-3 ganglios · lumpectomía": {
|
||||||
|
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"],
|
||||||
|
"Ganglios_positivos": ["1-3"],
|
||||||
|
"Cirugia": ["Lumpectomy"],
|
||||||
|
},
|
||||||
|
"Grado 3": {"Grado_histologico": ["3"]},
|
||||||
|
}
|
||||||
|
MIN_PER_CLASS = 10
|
||||||
|
SAMPLING = {
|
||||||
|
"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",
|
||||||
|
"origen": "la sede (sus propias pacientes)",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
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+"
|
||||||
@@ -47,10 +73,9 @@ 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
|
events = events.assign(
|
||||||
reference cohort's."""
|
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
|
||||||
events = events.assign(date=pd.to_datetime(events["date"]),
|
)
|
||||||
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()
|
||||||
days = (events["date"] - events["index_date"]).dt.days
|
days = (events["date"] - events["index_date"]).dt.days
|
||||||
cut = pd.Timestamp(as_of)
|
cut = pd.Timestamp(as_of)
|
||||||
@@ -64,16 +89,16 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
|||||||
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
|
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
|
||||||
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
|
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
|
||||||
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
|
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
|
||||||
|
|
||||||
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
||||||
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731
|
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first()
|
||||||
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731
|
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first()
|
||||||
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
|
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
|
||||||
age = (members - birth.reindex(members.index)).dt.days / 365.25
|
age = (members - birth.reindex(members.index)).dt.days / 365.25
|
||||||
out["Edad"] = _band(age, *cohorts.AGE)
|
out["Edad"] = _band(age, *cohorts.AGE)
|
||||||
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
|
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
|
||||||
out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
|
out["Ganglios_positivos"] = _band(
|
||||||
*cohorts.NODES) # fmt: skip
|
number("positive_nodes").reindex(members.index), *cohorts.NODES
|
||||||
|
)
|
||||||
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
|
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
|
||||||
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
|
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
|
||||||
ki67 = number("ki67_pct").reindex(members.index)
|
ki67 = number("ki67_pct").reindex(members.index)
|
||||||
@@ -82,8 +107,10 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
|||||||
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
|
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
|
||||||
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
|
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
|
||||||
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
|
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
|
||||||
out["Subtipo_clinico"] = [subtype(*a) for a in zip(
|
out["Subtipo_clinico"] = [
|
||||||
receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
|
subtype(*a)
|
||||||
|
for a in zip(receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)
|
||||||
|
]
|
||||||
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
|
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
|
||||||
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
|
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
|
||||||
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
|
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
|
||||||
@@ -97,13 +124,20 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
|||||||
return out.reset_index(drop=True)
|
return out.reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def scarce(rows: pd.DataFrame) -> str | None:
|
||||||
|
for h in cohorts.HORIZONS:
|
||||||
|
y = cohorts.at_horizon(rows, h)["y"]
|
||||||
|
fewest = min(int(y.sum()), int((y == 0).sum()))
|
||||||
|
if fewest < MIN_PER_CLASS:
|
||||||
|
return f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, {MIN_PER_CLASS} of each needed"
|
||||||
|
return 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]
|
||||||
treatment = [c for c in TREATMENT if c in kept]
|
treatment = [c for c in TREATMENT if c in kept]
|
||||||
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped)
|
return Cohort(
|
||||||
|
"site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio", SCENARIOS, SAMPLING
|
||||||
|
)
|
||||||
|
|||||||
+54
-50
@@ -1,36 +1,28 @@
|
|||||||
"""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); slow (its bootstraps
|
|
||||||
take minutes), so it trains only when asked for by name."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import pandas as pd
|
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 = {
|
||||||
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
|
"0": "0",
|
||||||
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
|
"I": "I",
|
||||||
SURGERY = ("breast_conserving_surgery", "mastectomy") # the most extensive one counts
|
"IA": "I",
|
||||||
|
"IB": "I",
|
||||||
# The clinical scenarios the survival report draws (as the SEER-trained original named them).
|
"II": "II",
|
||||||
STAGE_0_II, STAGE_III_IV = ("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV"))
|
"IIA": "II",
|
||||||
HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative")
|
"IIB": "II",
|
||||||
|
"III": "III",
|
||||||
|
"IIIA": "III",
|
||||||
|
"IIIB": "III",
|
||||||
|
"IIIC": "III",
|
||||||
|
"IV": "IV",
|
||||||
|
}
|
||||||
|
SURGERY = ("breast_conserving_surgery", "mastectomy")
|
||||||
|
STAGE_0_II, STAGE_III_IV = (("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV")))
|
||||||
|
HER2_POS, HER2_NEG = (("her2", "==", "positive"), ("her2", "==", "negative"))
|
||||||
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
|
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
|
||||||
CONSERVING = ("surgery", "==", "breast_conserving_surgery")
|
CONSERVING = ("surgery", "==", "breast_conserving_surgery")
|
||||||
|
|
||||||
@@ -51,20 +43,26 @@ SCENARIOS = {
|
|||||||
"≥ 75 años": (_older(75),),
|
"≥ 75 años": (_older(75),),
|
||||||
"< 45 años": (_younger(45),),
|
"< 45 años": (_younger(45),),
|
||||||
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
|
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
|
||||||
_younger(45), HER2_NEG, STAGE_0_II, CONSERVING),
|
_younger(45),
|
||||||
|
HER2_NEG,
|
||||||
|
STAGE_0_II,
|
||||||
|
CONSERVING,
|
||||||
|
),
|
||||||
"HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING),
|
"HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING),
|
||||||
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING),
|
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING),
|
||||||
"Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II),
|
"Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II),
|
||||||
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
|
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
|
||||||
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
|
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
|
||||||
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
|
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
|
||||||
_older(65), HER2_NEG, STAGE_0_II, CONSERVING),
|
_older(65),
|
||||||
} # fmt: skip
|
HER2_NEG,
|
||||||
|
STAGE_0_II,
|
||||||
|
CONSERVING,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
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()
|
||||||
@@ -73,8 +71,10 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
|||||||
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
||||||
for kind in RESULTS:
|
for kind in RESULTS:
|
||||||
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
|
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
|
||||||
for name, kind, cuts in (("ki67_group", "ki67_pct", (14, 20)),
|
for name, kind, cuts in (
|
||||||
("size_group", "size_mm", (20, 50))): # fmt: skip
|
("ki67_group", "ki67_pct", (14, 20)),
|
||||||
|
("size_group", "size_mm", (20, 50)),
|
||||||
|
):
|
||||||
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
|
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
|
||||||
found[name] = band(value.reindex(found.index), list(cuts))
|
found[name] = band(value.reindex(found.index), list(cuts))
|
||||||
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
|
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
|
||||||
@@ -90,21 +90,20 @@ 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"
|
||||||
slow: bool = True
|
reports: bool = True
|
||||||
reports: bool = True # it writes its own reports (models.jobs)
|
|
||||||
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:
|
||||||
from models.cama import recurrence
|
from models.cama import recurrence
|
||||||
from models.cama.recurrence import site
|
from models.cama.recurrence import site
|
||||||
|
from models.jobs import EmptyCohort
|
||||||
|
|
||||||
return recurrence.train_site(site.frame(events, as_of or date.today()))
|
rows = site.frame(events, as_of or date.today())
|
||||||
|
if reason := site.scarce(rows):
|
||||||
|
raise EmptyCohort(f"cama.recurrence: {reason}")
|
||||||
|
return recurrence.train_site(rows)
|
||||||
|
|
||||||
def predict(self, model, events) -> pd.DataFrame:
|
def predict(self, model, events) -> pd.DataFrame:
|
||||||
from models.cama.recurrence import calculator, site
|
from models.cama.recurrence import calculator, site
|
||||||
@@ -112,16 +111,25 @@ class SiteRecurrence:
|
|||||||
members = site.frame(events, date.today())
|
members = site.frame(events, date.today())
|
||||||
found = model.predict(members)
|
found = model.predict(members)
|
||||||
index = events.groupby("person_id")["index_date"].first()
|
index = events.groupby("person_id")["index_date"].first()
|
||||||
masks = calculator.masks(members, calculator.SCENARIOS["site"])
|
masks = calculator.masks(members, site.SCENARIOS)
|
||||||
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
named = [
|
||||||
for i in range(len(members))] # fmt: skip
|
SCENARIO_SEPARATOR.join((n for n, m in masks.items() if m[i])) or None
|
||||||
|
for i in range(len(members))
|
||||||
|
]
|
||||||
rows = []
|
rows = []
|
||||||
for i, person in enumerate(members["paciente"]):
|
for i, person in enumerate(members["paciente"]):
|
||||||
for h in model.horizons:
|
for h in model.horizons:
|
||||||
rows.append({"person_id": person,
|
rows.append(
|
||||||
|
{
|
||||||
|
"person_id": person,
|
||||||
"index_date": pd.Timestamp(index[person]).date(),
|
"index_date": pd.Timestamp(index[person]).date(),
|
||||||
"horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
|
"horizon_years": h / 12,
|
||||||
"ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
|
"probability": found[f"recurrence_{h}m"][i],
|
||||||
|
"ci_low": None,
|
||||||
|
"ci_high": None,
|
||||||
|
"scenarios": named[i],
|
||||||
|
}
|
||||||
|
)
|
||||||
return pd.DataFrame(rows, columns=OUTPUT)
|
return pd.DataFrame(rows, columns=OUTPUT)
|
||||||
|
|
||||||
|
|
||||||
@@ -140,7 +148,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",
|
||||||
@@ -155,10 +162,7 @@ MODELS = {
|
|||||||
scenario_columns=("age",),
|
scenario_columns=("age",),
|
||||||
treatments=("surgery", "chemotherapy", "radiotherapy"),
|
treatments=("surgery", "chemotherapy", "radiotherapy"),
|
||||||
notes=(
|
notes=(
|
||||||
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
|
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los {TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere antes de su tratamiento cuenta como no tratada (sesgo de tiempo inmortal): el efecto protector del tratamiento aparece mayor de lo que es.",
|
||||||
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
|
|
||||||
"antes de su tratamiento cuenta como no tratada (sesgo de tiempo inmortal): el "
|
|
||||||
"efecto protector del tratamiento aparece mayor de lo que es.",
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
"recurrence": SiteRecurrence("recurrence"),
|
"recurrence": SiteRecurrence("recurrence"),
|
||||||
|
|||||||
+1
-12
@@ -1,31 +1,20 @@
|
|||||||
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
|
|
||||||
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
|
|
||||||
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
|
|
||||||
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
|
|
||||||
task carries its data (a recording), so a cap paces a slow link."""
|
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from collections.abc import Callable, Iterable
|
from collections.abc import Callable, Iterable
|
||||||
from importlib.util import find_spec
|
from importlib.util import find_spec
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from joblib import Parallel, delayed
|
from joblib import Parallel, delayed
|
||||||
|
|
||||||
|
|
||||||
def jobs() -> int:
|
def jobs() -> int:
|
||||||
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
|
|
||||||
return int(os.environ.get("BATCH_JOBS", "-1"))
|
return int(os.environ.get("BATCH_JOBS", "-1"))
|
||||||
|
|
||||||
|
|
||||||
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
|
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
|
||||||
"""`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
|
|
||||||
drawn as tasks start, so at most `jobs()` of them are held at once."""
|
|
||||||
if find_spec("distributed") is None:
|
if find_spec("distributed") is None:
|
||||||
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
|
return Parallel(n_jobs=jobs())((delayed(task)(*a) for a in arguments))
|
||||||
from distributed import Client, LocalCluster, as_completed
|
from distributed import Client, LocalCluster, as_completed
|
||||||
|
|
||||||
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
|
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||||
# one process per core, no dashboard port to collide with (8787 is often taken)
|
|
||||||
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
|
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
|
||||||
try:
|
try:
|
||||||
with Client(where) as client:
|
with Client(where) as client:
|
||||||
|
|||||||
+26
-51
@@ -1,31 +1,22 @@
|
|||||||
"""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 = 1000000000000.0
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
c = np.bincount(months[~event], minlength=length)
|
c = np.bincount(months[~event], minlength=length)
|
||||||
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
||||||
return d, c, at_risk
|
return (d, c, at_risk)
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -43,7 +34,7 @@ def kaplan_meier(months, event, until: int):
|
|||||||
def _nll(survival, d, c) -> float:
|
def _nll(survival, d, c) -> float:
|
||||||
T = len(d)
|
T = len(d)
|
||||||
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
|
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
|
||||||
S, mid = both[: T + 1], both[T + 1 :]
|
S, mid = (both[: T + 1], both[T + 1 :])
|
||||||
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
|
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
|
||||||
return INVALID
|
return INVALID
|
||||||
p = np.clip(S[:-1] - S[1:], 1e-300, None)
|
p = np.clip(S[:-1] - S[1:], 1e-300, None)
|
||||||
@@ -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):
|
||||||
@@ -63,17 +53,15 @@ def fit_weibull(d, c) -> tuple[float, float]:
|
|||||||
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
|
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
|
||||||
[np.log(k0), np.log(l0)],
|
[np.log(k0), np.log(l0)],
|
||||||
method="Nelder-Mead",
|
method="Nelder-Mead",
|
||||||
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000},
|
options={"xatol": 1e-05, "fatol": 1e-08, "maxiter": 2000},
|
||||||
)
|
)
|
||||||
r = _converged(r, "Weibull")
|
r = _converged(r, "Weibull")
|
||||||
best = r if best is None or r.fun < best.fun else best
|
best = r if best is None or r.fun < best.fun else best
|
||||||
k, lam = np.exp(best.x)
|
k, lam = np.exp(best.x)
|
||||||
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
|
||||||
@@ -105,22 +85,20 @@ def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
|
|||||||
grid = w ** (1 / e)
|
grid = w ** (1 / e)
|
||||||
y = np.ones(STEPS + 1)
|
y = np.ones(STEPS + 1)
|
||||||
kappa = c / np.exp(gammaln(rho))
|
kappa = c / np.exp(gammaln(rho))
|
||||||
b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
|
b0, be = (beta_function(s + 1, rho), beta_function(s + e + 1, rho))
|
||||||
dw = np.diff(w)
|
dw = np.diff(w)
|
||||||
for n in range(1, STEPS + 1):
|
for n in range(1, STEPS + 1):
|
||||||
x = grid[: n + 1] / grid[n]
|
x = grid[: n + 1] / grid[n]
|
||||||
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,32 +108,25 @@ 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),
|
return (beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1))))
|
||||||
with g the Kilbas-Saigo survival of order rho and power s at c = 1."""
|
|
||||||
return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)))
|
|
||||||
|
|
||||||
|
|
||||||
def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
|
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
|
floor = max(0.0, 1.0 - k) + 1e-06
|
||||||
maximum likelihood profiled over lambda: for each (alpha, beta), g is solved once over
|
top = len(d) + 0.5
|
||||||
every z the allowed lambdas (1 to 1e7) reach, and lambda is then fitted exactly on it.
|
|
||||||
(alpha, beta) is the best of a start at the classic fit (alpha = beta = 1, so it is
|
|
||||||
never worse) and a grid of others, each to Nelder-Mead's convergence."""
|
|
||||||
floor = max(0.0, 1.0 - k) + 1e-6
|
|
||||||
top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month)
|
|
||||||
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5])
|
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(10000000.0))
|
||||||
|
|
||||||
def unpack(p):
|
def unpack(p):
|
||||||
return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))
|
return (floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1])))
|
||||||
|
|
||||||
def profile(p) -> tuple[float, float]:
|
def profile(p) -> tuple[float, float]:
|
||||||
a, b = unpack(p)
|
a, b = unpack(p)
|
||||||
if k + a <= 1 or k + a + b <= 2:
|
if k + a <= 1 or k + a + b <= 2:
|
||||||
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)
|
||||||
|
|
||||||
@@ -165,17 +136,21 @@ def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
|
|||||||
|
|
||||||
coarse = np.linspace(*lambdas, 141)
|
coarse = np.linspace(*lambdas, 141)
|
||||||
i = int(np.argmin([nll(x) for x in coarse]))
|
i = int(np.argmin([nll(x) for x in coarse]))
|
||||||
r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
|
r = minimize_scalar(
|
||||||
method="bounded", options={"xatol": 1e-9}) # fmt: skip
|
nll,
|
||||||
return float(r.fun), float(r.x)
|
bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
|
||||||
|
method="bounded",
|
||||||
|
options={"xatol": 1e-09},
|
||||||
|
)
|
||||||
|
return (float(r.fun), float(r.x))
|
||||||
|
|
||||||
starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0]]
|
starts = [[np.log(max(1.0 - floor, 1e-09)), 8.0]]
|
||||||
starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)]
|
starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)]
|
||||||
best = None
|
best = None
|
||||||
for p0 in starts:
|
for p0 in starts:
|
||||||
options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000}
|
options = {"xatol": 1e-05, "fatol": 1e-08, "maxiter": 20000, "maxfev": 20000}
|
||||||
r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
|
r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
|
||||||
r = _converged(r, "fractional Weibull")
|
r = _converged(r, "fractional Weibull")
|
||||||
best = r if best is None or r.fun < best.fun else best
|
best = r if best is None or r.fun < best.fun else best
|
||||||
a, b = unpack(best.x)
|
a, b = unpack(best.x)
|
||||||
return float(a), float(b), float(np.exp(profile(best.x)[1]))
|
return (float(a), float(b), float(np.exp(profile(best.x)[1])))
|
||||||
|
|||||||
+8
-20
@@ -1,27 +1,22 @@
|
|||||||
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
|
||||||
|
|
||||||
import importlib
|
import importlib
|
||||||
import os
|
import os
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import dagster as dg
|
import dagster as dg
|
||||||
|
|
||||||
from models import graph
|
from models import graph
|
||||||
from models.jobs import EmptyCohort
|
from models.jobs import EmptyCohort
|
||||||
from persistance import backup as backups
|
from persistance import backup as backups
|
||||||
from persistance import config_log, silver
|
from persistance import config_log, silver
|
||||||
|
|
||||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
WRITES = {"writes": "platform"}
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -34,7 +29,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:
|
||||||
@@ -43,20 +37,19 @@ 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 but the slow ones
|
models: list[str] = []
|
||||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
as_of: str | 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
|
||||||
found = {}
|
found = {}
|
||||||
for name in config.models or jobs.JOBS.routine():
|
for name in config.models or jobs.JOBS.routine():
|
||||||
try:
|
try:
|
||||||
found[name] = jobs.train(name, as_of)
|
found[name] = jobs.train(name, as_of)
|
||||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
except EmptyCohort as e:
|
||||||
found[name] = None
|
found[name] = None
|
||||||
context.log.warning(f"{e}: not trained")
|
context.log.warning(f"{e}: not trained")
|
||||||
continue
|
continue
|
||||||
@@ -71,12 +64,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.scored()}
|
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()}
|
||||||
for name, version in found.items():
|
for name, version in found.items():
|
||||||
@@ -96,7 +88,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)."""
|
|
||||||
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")
|
||||||
return found
|
return found
|
||||||
@@ -109,26 +100,23 @@ def analyze():
|
|||||||
|
|
||||||
@dg.op
|
@dg.op
|
||||||
def make_backup(context: dg.OpExecutionContext) -> str:
|
def make_backup(context: dg.OpExecutionContext) -> str:
|
||||||
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
|
|
||||||
folder = backups.create()
|
folder = backups.create()
|
||||||
context.log.info(f"backup {folder}")
|
context.log.info(f"backup {folder}")
|
||||||
return str(folder)
|
return str(folder)
|
||||||
|
|
||||||
|
|
||||||
@dg.job(tags=WRITES) # holds the writing slot: nothing writes while it copies
|
@dg.job(tags=WRITES)
|
||||||
def backup():
|
def backup():
|
||||||
make_backup()
|
make_backup()
|
||||||
|
|
||||||
|
|
||||||
# Nightly by default; BACKUP_SCHEDULE is a cron expression (empty: no schedule).
|
|
||||||
nightly = (
|
nightly = (
|
||||||
[
|
[
|
||||||
dg.ScheduleDefinition(
|
dg.ScheduleDefinition(
|
||||||
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
|
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
|
||||||
)
|
)
|
||||||
] # fmt: skip
|
]
|
||||||
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
|
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
|
||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
|
|
||||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
|
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
|
||||||
|
|||||||
+56
-48
@@ -1,25 +1,11 @@
|
|||||||
"""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
|
||||||
from scipy.stats import false_discovery_control
|
from scipy.stats import false_discovery_control
|
||||||
|
|
||||||
from models.curves import life_table
|
from models.curves import life_table
|
||||||
|
|
||||||
ALPHA = 0.05
|
ALPHA = 0.05
|
||||||
FREQ_MIN = 0.80
|
FREQ_MIN = 0.8
|
||||||
Z = 1.96
|
Z = 1.96
|
||||||
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
|
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
|
||||||
ORDER = {
|
ORDER = {
|
||||||
@@ -30,30 +16,25 @@ 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.5, 0.1)
|
||||||
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)
|
||||||
last = min(horizon, len(d) - 1) + 1
|
last = min(horizon, len(d) - 1) + 1
|
||||||
S = float(np.prod(q[:last]))
|
S = float(np.prod(q[:last]))
|
||||||
return S, S * float(np.sqrt(np.sum(v[:last])))
|
return (S, S * float(np.sqrt(np.sum(v[:last]))))
|
||||||
|
|
||||||
|
|
||||||
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]
|
||||||
@@ -71,11 +52,16 @@ 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(
|
||||||
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
|
table: pd.DataFrame,
|
||||||
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
|
variables,
|
||||||
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
|
reference: dict,
|
||||||
survival columns)."""
|
everyone: pd.DataFrame,
|
||||||
|
months,
|
||||||
|
event,
|
||||||
|
horizon: int,
|
||||||
|
names: tuple[str, str, str],
|
||||||
|
) -> pd.DataFrame:
|
||||||
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"] = [
|
||||||
@@ -86,23 +72,46 @@ def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataF
|
|||||||
category, ref, delta_name = names
|
category, ref, delta_name = names
|
||||||
rows = []
|
rows = []
|
||||||
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
|
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
|
||||||
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
|
a, b = ((everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy())
|
||||||
sa, ea = km_at(months[a], event[a], horizon)
|
sa, ea = km_at(months[a], event[a], horizon)
|
||||||
sb, eb = km_at(months[b], event[b], horizon)
|
sb, eb = km_at(months[b], event[b], horizon)
|
||||||
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
|
delta, se = (sa - sb, np.sqrt(ea**2 + eb**2))
|
||||||
rows.append({
|
rows.append(
|
||||||
"n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
|
{
|
||||||
"delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
|
"n_categoria": int(a.sum()),
|
||||||
}) # fmt: skip
|
category: sa,
|
||||||
return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
|
ref: sb,
|
||||||
"delta_IC95_inf", "delta_IC95_sup"])],
|
delta_name: delta,
|
||||||
axis=1) # fmt: skip
|
"delta_IC95_inf": delta - Z * se,
|
||||||
|
"delta_IC95_sup": delta + Z * se,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return pd.concat(
|
||||||
|
[
|
||||||
|
table,
|
||||||
|
pd.DataFrame(
|
||||||
|
rows,
|
||||||
|
columns=[
|
||||||
|
"n_categoria",
|
||||||
|
category,
|
||||||
|
ref,
|
||||||
|
delta_name,
|
||||||
|
"delta_IC95_inf",
|
||||||
|
"delta_IC95_sup",
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
axis=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
|
def classify(
|
||||||
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
|
tab: pd.DataFrame,
|
||||||
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
|
or_name: str,
|
||||||
for the criteria `evaluated`."""
|
delta_name: str,
|
||||||
|
unknown: str,
|
||||||
|
evaluated: tuple[str, ...] = CRITERIA,
|
||||||
|
) -> pd.DataFrame:
|
||||||
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,21 +145,22 @@ 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
|
strength = np.where(
|
||||||
`asociacion`."""
|
part["tipo_efecto"] == "tratamiento",
|
||||||
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
|
"asociacion",
|
||||||
part["clasificacion"].str.split().str[-1]) # fmt: skip
|
part["clasificacion"].str.split().str[-1],
|
||||||
|
)
|
||||||
return "; ".join(
|
return "; ".join(
|
||||||
|
(
|
||||||
f"{v}={c} ({s}, {p:.0%})"
|
f"{v}={c} ({s}, {p:.0%})"
|
||||||
for v, c, s, p in zip(
|
for v, c, s, p in zip(
|
||||||
part["variable"], part["categoria"], strength, part["share"], strict=True
|
part["variable"], part["categoria"], strength, part["share"], strict=True
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
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 +169,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)
|
||||||
|
|||||||
+146
-141
@@ -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
|
||||||
@@ -9,7 +6,6 @@ import unicodedata
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from concurrent.futures import ProcessPoolExecutor
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
from functools import cache
|
from functools import cache
|
||||||
|
|
||||||
import duckdb
|
import duckdb
|
||||||
import ocrmypdf
|
import ocrmypdf
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -21,7 +17,6 @@ from openai import OpenAI, OpenAIError
|
|||||||
from splink import Linker, SettingsCreator, block_on
|
from splink import Linker, SettingsCreator, block_on
|
||||||
from splink.backends.duckdb import DuckDBAPI
|
from splink.backends.duckdb import DuckDBAPI
|
||||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||||
|
|
||||||
from core import catalog, concept_map, fhir_in
|
from core import catalog, concept_map, fhir_in
|
||||||
from core.pipeline import (
|
from core.pipeline import (
|
||||||
HELD,
|
HELD,
|
||||||
@@ -47,9 +42,9 @@ from core.pipeline import (
|
|||||||
)
|
)
|
||||||
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},
|
||||||
@@ -58,9 +53,6 @@ READ_COLUMNS = { # declared, so a load where every file read cleanly still has
|
|||||||
|
|
||||||
|
|
||||||
def file_format(content: bytes) -> str:
|
def file_format(content: bytes) -> str:
|
||||||
"""What kind of file this is, from its first bytes, so a route can tell a PDF from an
|
|
||||||
EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose
|
|
||||||
version is "0"), or other (whatever MarkItDown reads)."""
|
|
||||||
if content.startswith(b"%PDF"):
|
if content.startswith(b"%PDF"):
|
||||||
return "pdf"
|
return "pdf"
|
||||||
head = content[:256]
|
head = content[:256]
|
||||||
@@ -75,42 +67,42 @@ 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,
|
source, scans = (pikepdf.open(io.BytesIO(content)), pikepdf.new())
|
||||||
copied into a PDF of their own: a typed page keeps its own text layer."""
|
|
||||||
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])
|
||||||
pages, sidecar = io.BytesIO(), io.BytesIO()
|
pages, sidecar = (io.BytesIO(), io.BytesIO())
|
||||||
scans.save(pages)
|
scans.save(pages)
|
||||||
pages.seek(0)
|
pages.seek(0)
|
||||||
ocrmypdf.ocr(
|
ocrmypdf.ocr(
|
||||||
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
|
pages,
|
||||||
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
|
io.BytesIO(),
|
||||||
) # fmt: skip
|
language="spa",
|
||||||
found = sidecar.getvalue().decode().split("\f")
|
force_ocr=True,
|
||||||
|
output_type="pdf",
|
||||||
|
optimize=0,
|
||||||
|
progress_bar=False,
|
||||||
|
jobs=1,
|
||||||
|
deskew=True,
|
||||||
|
sidecar=sidecar,
|
||||||
|
)
|
||||||
|
found = sidecar.getvalue().decode().split("\x0c")
|
||||||
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
|
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
|
||||||
|
|
||||||
|
|
||||||
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}
|
||||||
@@ -118,8 +110,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}
|
||||||
@@ -128,33 +118,33 @@ def _read_text(content: bytes) -> dict:
|
|||||||
if scanned:
|
if scanned:
|
||||||
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:
|
||||||
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(
|
||||||
for k in legacy], READ_COLUMNS) # fmt: skip
|
"read_cache",
|
||||||
|
[{"key": k, **{c: found[k][c] for c in READ_COLUMNS}} for k in legacy],
|
||||||
|
READ_COLUMNS,
|
||||||
|
)
|
||||||
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(
|
||||||
strict=True)) # fmt: skip
|
zip(batch, pool.map(read_file, (files.content(k) for k in batch)), strict=True)
|
||||||
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
|
)
|
||||||
READ_COLUMNS) # fmt: skip
|
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
|
||||||
found |= read
|
found |= read
|
||||||
for row in rows:
|
for row in rows:
|
||||||
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
||||||
@@ -163,14 +153,12 @@ def run_read(p: str, node: Read):
|
|||||||
|
|
||||||
|
|
||||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||||
"""The input's rows the route takes; an `otherwise` route, those `others` don't."""
|
|
||||||
rows = nodes.rows(p, node.inputs[0])
|
rows = nodes.rows(p, node.inputs[0])
|
||||||
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
|
taken = [r for r in rows if matches(node, r) and (not any((matches(o, r) for o in others)))]
|
||||||
return nodes.write(p, node.id, taken)
|
return nodes.write(p, node.id, taken)
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -184,7 +172,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]):
|
||||||
@@ -201,7 +188,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)
|
||||||
@@ -209,14 +195,10 @@ def _llm() -> tuple[OpenAI, str] | None:
|
|||||||
client.models.list()
|
client.models.list()
|
||||||
except OpenAIError:
|
except OpenAIError:
|
||||||
return None
|
return None
|
||||||
return client, os.environ["LLM_MODEL"]
|
return (client, os.environ["LLM_MODEL"])
|
||||||
|
|
||||||
|
|
||||||
PROMPT = (
|
PROMPT = "Extract every {entity} record stated in the document. For each field give its value in the schema's terms and `quote`: the exact text of the document it was read from, copied character by character. Leave out fields the document does not state.{hints}"
|
||||||
"Extract every {entity} record stated in the document. For each field give its value "
|
|
||||||
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
|
||||||
"copied character by character. Leave out fields the document does not state.{hints}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _ask_llm(node: Extract, text: str) -> dict:
|
def _ask_llm(node: Extract, text: str) -> dict:
|
||||||
@@ -226,11 +208,15 @@ def _ask_llm(node: Extract, text: str) -> dict:
|
|||||||
if found := nodes.cached("llm_cache", {key}):
|
if found := nodes.cached("llm_cache", {key}):
|
||||||
return json.loads(found[key]["answer"])
|
return json.loads(found[key]["answer"])
|
||||||
reply = client.chat.completions.create(
|
reply = client.chat.completions.create(
|
||||||
model=model, temperature=0, seed=7,
|
model=model,
|
||||||
|
temperature=0,
|
||||||
|
seed=7,
|
||||||
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
||||||
response_format={"type": "json_schema", "json_schema": {
|
response_format={
|
||||||
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
"type": "json_schema",
|
||||||
) # fmt: skip
|
"json_schema": {"name": "answer", "schema": answer_schema(node.entity), "strict": True},
|
||||||
|
},
|
||||||
|
)
|
||||||
answer = reply.choices[0].message.content
|
answer = reply.choices[0].message.content
|
||||||
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
||||||
return json.loads(answer)
|
return json.loads(answer)
|
||||||
@@ -250,9 +236,16 @@ def run_extract(p: str, node: Extract):
|
|||||||
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
||||||
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
|
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
|
||||||
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
||||||
out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
|
out.append(
|
||||||
|
{
|
||||||
|
**values,
|
||||||
|
**taken,
|
||||||
|
RECORD: row[RECORD],
|
||||||
|
"_index": index,
|
||||||
QUOTES: json.dumps(quotes, ensure_ascii=False),
|
QUOTES: json.dumps(quotes, ensure_ascii=False),
|
||||||
HELD: json.dumps(held) if held else None}) # fmt: skip
|
HELD: json.dumps(held) if held else None,
|
||||||
|
}
|
||||||
|
)
|
||||||
return nodes.write(p, node.id, out)
|
return nodes.write(p, node.id, out)
|
||||||
|
|
||||||
|
|
||||||
@@ -267,37 +260,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
|
skip, fixed = (nodes.rejected("identity"), nodes.corrections())
|
||||||
applied, identifiers plain); records rejected for identity are left out. And the input
|
|
||||||
each record came through (its record number's system), and its name as written."""
|
|
||||||
skip, fixed = nodes.rejected("identity"), nodes.corrections()
|
|
||||||
records: dict[str, dict] = {}
|
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:
|
||||||
@@ -306,19 +292,18 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[
|
|||||||
if f == "full_name":
|
if f == "full_name":
|
||||||
written[row[RECORD]] = " ".join(value.split())
|
written[row[RECORD]] = " ".join(value.split())
|
||||||
mine[f] = (
|
mine[f] = (
|
||||||
_plain(value) if f in IDENTIFIERS
|
_plain(value)
|
||||||
else _name(value) if f == "full_name" else value
|
if f in IDENTIFIERS
|
||||||
) # fmt: skip
|
else _name(value)
|
||||||
|
if f == "full_name"
|
||||||
|
else value
|
||||||
|
)
|
||||||
frame = pd.DataFrame(list(records.values()))
|
frame = pd.DataFrame(list(records.values()))
|
||||||
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
|
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
|
||||||
return frame[["unique_id", *present]], sources, written
|
return (frame[["unique_id", *present]], sources, written)
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -328,11 +313,12 @@ def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.S
|
|||||||
if rules:
|
if rules:
|
||||||
con = duckdb.connect()
|
con = duckdb.connect()
|
||||||
con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
|
con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
|
||||||
joins = " or ".join(f"({r})" for r in rules)
|
joins = " or ".join((f"({r})" for r in rules))
|
||||||
joined = set(con.sql(
|
joined = set(
|
||||||
f"select l.unique_id from candidates l join candidates r"
|
con.sql(
|
||||||
f" on l.unique_id = r.unique_id where {joins}"
|
f"select l.unique_id from candidates l join candidates r on l.unique_id = r.unique_id where {joins}"
|
||||||
).df()["unique_id"]) # fmt: skip
|
).df()["unique_id"]
|
||||||
|
)
|
||||||
return stand_in.where(stand_in.isin(joined), records["unique_id"])
|
return stand_in.where(stand_in.isin(joined), records["unique_id"])
|
||||||
|
|
||||||
|
|
||||||
@@ -344,15 +330,13 @@ 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 = [
|
||||||
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
|
r
|
||||||
|
for r in node.rules or node.default_rules()
|
||||||
|
if all((f"l.{f}" not in r or f in fields for f in node.fields))
|
||||||
|
]
|
||||||
comparisons = [_comparison(f) for f in fields]
|
comparisons = [_comparison(f) for f in fields]
|
||||||
decided = nodes.person_decisions()
|
decided = nodes.person_decisions()
|
||||||
stand_in = _distinct(records, rules, set().union(*decided))
|
stand_in = _distinct(records, rules, set().union(*decided))
|
||||||
@@ -360,10 +344,13 @@ def run_link(p: str, node: Link):
|
|||||||
db = DuckDBAPI()
|
db = DuckDBAPI()
|
||||||
linker = Linker(
|
linker = Linker(
|
||||||
db.register(distinct),
|
db.register(distinct),
|
||||||
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
SettingsCreator(
|
||||||
blocking_rules_to_generate_predictions=rules),
|
link_type="dedupe_only",
|
||||||
|
comparisons=comparisons,
|
||||||
|
blocking_rules_to_generate_predictions=rules,
|
||||||
|
),
|
||||||
log_level=None,
|
log_level=None,
|
||||||
) # fmt: skip
|
)
|
||||||
sure = linker.inference.deterministic_link().as_pandas_dataframe()
|
sure = linker.inference.deterministic_link().as_pandas_dataframe()
|
||||||
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
|
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
|
||||||
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
|
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
|
||||||
@@ -373,11 +360,9 @@ def run_link(p: str, node: Link):
|
|||||||
)
|
)
|
||||||
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
|
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
|
||||||
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
|
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
|
||||||
|
|
||||||
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}
|
||||||
@@ -385,16 +370,18 @@ def run_link(p: str, node: Link):
|
|||||||
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
|
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
|
||||||
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
|
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
|
||||||
linked = [
|
linked = [
|
||||||
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
|
{
|
||||||
|
RECORD: r.unique_id,
|
||||||
|
"person_id": stable[r.cluster_id],
|
||||||
|
"_source": sources[r.unique_id],
|
||||||
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
|
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
|
||||||
**{f: getattr(r, f) for f in fields},
|
**{f: getattr(r, f) for f in fields},
|
||||||
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
|
**({"full_name": written[r.unique_id]} if r.unique_id in written else {}),
|
||||||
|
}
|
||||||
for r in persons.itertuples()
|
for r in persons.itertuples()
|
||||||
] # 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:
|
||||||
@@ -414,47 +401,44 @@ def run_link(p: str, node: Link):
|
|||||||
reasons.append("same birth date")
|
reasons.append("same birth date")
|
||||||
model = Linker(
|
model = Linker(
|
||||||
db.register(whole),
|
db.register(whole),
|
||||||
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
SettingsCreator(
|
||||||
blocking_rules_to_generate_predictions=blocks),
|
link_type="dedupe_only",
|
||||||
|
comparisons=comparisons,
|
||||||
|
blocking_rules_to_generate_predictions=blocks,
|
||||||
|
),
|
||||||
log_level=None,
|
log_level=None,
|
||||||
) # fmt: skip
|
)
|
||||||
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
|
model.training.estimate_u_using_random_sampling(max_pairs=1000000.0)
|
||||||
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
|
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
|
||||||
|
|
||||||
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()
|
||||||
lone = set() # persons whose identifier is carried by one record only
|
whose = persons.set_index("unique_id")["cluster_id"].to_dict()
|
||||||
|
answered = {frozenset((whose.get(r, r) for r in e)) for e in decided}
|
||||||
|
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:
|
a, b = (r.unique_id_l, r.unique_id_r)
|
||||||
they contradict each other, or one typo apart is all they share (with sequential
|
|
||||||
record numbers every patient has such neighbours) unless one side has no
|
|
||||||
demographics and the other's identifier stands on a single record. Names one typo
|
|
||||||
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
|
|
||||||
very same identifier on a record that says nothing else (a scan read only in part)."""
|
|
||||||
a, b = r.unique_id_l, r.unique_id_r
|
|
||||||
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||||
if frozenset((a, b)) in decided or any(
|
if frozenset((a, b)) in answered or any(
|
||||||
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
(pd.notna(x) and pd.notna(y) and (x != y) for x, y in sides)
|
||||||
):
|
):
|
||||||
return None
|
return None
|
||||||
reason = reasons[int(r.match_key)]
|
reason = reasons[int(r.match_key)]
|
||||||
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:
|
||||||
return b, a
|
return (b, a)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
side = {r.unique_id: r for r in whole.itertuples()}
|
side = {r.unique_id: r for r in whole.itertuples()}
|
||||||
@@ -476,27 +460,30 @@ 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:
|
link = next((i for i in node.inputs if kinds[i] == "link"))
|
||||||
a clean row becomes one observation per field it has (long), keyed by its study
|
|
||||||
instance (the study's key values); a row a rule held waits for review, whole."""
|
|
||||||
link = next(i for i in node.inputs if kinds[i] == "link")
|
|
||||||
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
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):
|
||||||
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
||||||
values |= {f: v for f, v in fixed.get(row[RECORD], {}).items()
|
values |= {
|
||||||
if f in model.model_fields} # fmt: skip
|
f: v for f, v in fixed.get(row[RECORD], {}).items() if f in model.model_fields
|
||||||
|
}
|
||||||
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
|
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
|
||||||
if row[RECORD] not in person:
|
if row[RECORD] not in person:
|
||||||
held.append("no identity linked to this record")
|
held.append("no identity linked to this record")
|
||||||
else:
|
else:
|
||||||
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
|
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
|
||||||
base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
|
base = {
|
||||||
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
|
"study": node.entity,
|
||||||
|
"person_id": person.get(row[RECORD]),
|
||||||
|
RECORD: row[RECORD],
|
||||||
|
"_index": row.get("_index", 0),
|
||||||
|
QUOTES: row.get(QUOTES),
|
||||||
|
}
|
||||||
if held:
|
if held:
|
||||||
raw = json.dumps(values, default=str, ensure_ascii=False)
|
raw = json.dumps(values, default=str, ensure_ascii=False)
|
||||||
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
|
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
|
||||||
@@ -505,16 +492,28 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
|||||||
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
||||||
for name, field in study.fields.items():
|
for name, field in study.fields.items():
|
||||||
if (value := getattr(clean, name)) is not None:
|
if (value := getattr(clean, name)) is not None:
|
||||||
observations.append({**base, "instance": instance, "field": name,
|
observations.append(
|
||||||
catalog.value_column(field): value}) # fmt: skip
|
{
|
||||||
|
**base,
|
||||||
|
"instance": instance,
|
||||||
|
"field": name,
|
||||||
|
catalog.value_column(field): value,
|
||||||
|
}
|
||||||
|
)
|
||||||
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||||
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||||
|
|
||||||
|
|
||||||
RUNNERS: dict[str, Callable] = {
|
RUNNERS: dict[str, Callable] = {
|
||||||
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
|
"source": nodes.run_source,
|
||||||
"join": run_join, "extract": run_extract, "link": run_link, "fhir": run_fhir,
|
"read": run_read,
|
||||||
} # fmt: skip
|
"route": run_route,
|
||||||
|
"map": run_map,
|
||||||
|
"join": run_join,
|
||||||
|
"extract": run_extract,
|
||||||
|
"link": run_link,
|
||||||
|
"fhir": run_fhir,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
|
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
|
||||||
@@ -523,12 +522,18 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
|||||||
if node.kind == "target":
|
if node.kind == "target":
|
||||||
run_target(pipeline_id, node, kinds)
|
run_target(pipeline_id, node, kinds)
|
||||||
elif node.kind == "route" and node.otherwise:
|
elif node.kind == "route" and node.otherwise:
|
||||||
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
|
others = [
|
||||||
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
|
n
|
||||||
|
for n in pipeline.nodes
|
||||||
|
if n.kind == "route"
|
||||||
|
and n.id != node.id
|
||||||
|
and (n.inputs == node.inputs)
|
||||||
|
and (not n.otherwise)
|
||||||
|
]
|
||||||
run_route(pipeline_id, node, others)
|
run_route(pipeline_id, node, others)
|
||||||
else:
|
else:
|
||||||
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)}")
|
||||||
|
|||||||
+5
-28
@@ -1,29 +1,19 @@
|
|||||||
"""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
|
||||||
|
|
||||||
import mlflow.pyfunc
|
import mlflow.pyfunc
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from joblib.externals.loky import get_reusable_executor
|
from joblib.externals.loky import get_reusable_executor
|
||||||
|
|
||||||
from persistance import gold, registry
|
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)
|
||||||
|
|
||||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||||
return self.spec.predict(self.fitted, model_input)
|
return self.spec.predict(self.fitted, model_input)
|
||||||
@@ -41,24 +31,17 @@ class Jobs:
|
|||||||
return f"{self.domain}_events"
|
return f"{self.domain}_events"
|
||||||
|
|
||||||
def routine(self) -> list[str]:
|
def routine(self) -> list[str]:
|
||||||
"""The models a train run takes when none is named: all but the slow ones."""
|
return list(self.models)
|
||||||
return [n for n, s in self.models.items() if not getattr(s, "slow", False)]
|
|
||||||
|
|
||||||
def scored(self) -> list[str]:
|
def scored(self) -> list[str]:
|
||||||
"""The models a score run takes when none is named: all of them (only training is
|
|
||||||
slow)."""
|
|
||||||
return list(self.models)
|
return list(self.models)
|
||||||
|
|
||||||
def registered(self, name: str) -> str:
|
def registered(self, name: str) -> str:
|
||||||
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
|
spec, as_of = (self.models[name], as_of or date.today())
|
||||||
`as_of` (default: today), with its metrics and its two generated reports."""
|
if getattr(spec, "reports", False):
|
||||||
spec, as_of = self.models[name], as_of or date.today()
|
|
||||||
if spec.cohort is None: # trained on reference data: it writes its own reports
|
|
||||||
fitted, metrics, found = spec.train(None, as_of)
|
|
||||||
elif getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
|
||||||
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}")
|
||||||
@@ -72,18 +55,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."""
|
|
||||||
if self.models[name].cohort is None: # scores no patient
|
|
||||||
return None
|
|
||||||
found = registry.champion(self.registered(name))
|
found = registry.champion(self.registered(name))
|
||||||
if found is None:
|
if found is None:
|
||||||
return None
|
return None
|
||||||
|
|||||||
+180
-174
@@ -1,19 +1,7 @@
|
|||||||
"""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
|
||||||
from itertools import pairwise
|
from itertools import pairwise
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from joblib import Parallel, delayed
|
from joblib import Parallel, delayed
|
||||||
@@ -28,9 +16,7 @@ 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;
|
index, death, end = (pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end))
|
||||||
follow-up is cut at `cap_months` (a later death counts as alive)."""
|
|
||||||
index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
|
|
||||||
died = (death.notna() & (death <= end)).to_numpy()
|
died = (death.notna() & (death <= end)).to_numpy()
|
||||||
last = death.where(died, end)
|
last = death.where(died, end)
|
||||||
days = (last - index).dt.days.to_numpy()
|
days = (last - index).dt.days.to_numpy()
|
||||||
@@ -42,7 +28,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 +35,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,25 +42,26 @@ 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(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
|
np.sum(
|
||||||
|
gammaln(aj) - gammaln(aj + n.sum(1)) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
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:
|
||||||
found = None
|
found = None
|
||||||
for j in range(X.shape[1]):
|
for j in range(X.shape[1]):
|
||||||
if j in parents or q * levels[j] > 200_000:
|
if j in parents or q * levels[j] > 200000:
|
||||||
continue
|
continue
|
||||||
c2 = code * levels[j] + X[:, j]
|
c2 = code * levels[j] + X[:, j]
|
||||||
score = _bdeu(c2, y, w, q * levels[j], ess)
|
score = _bdeu(c2, y, w, q * levels[j], ess)
|
||||||
if score > best + 1e-9 and (found is None or score > found[0]):
|
if score > best + 1e-09 and (found is None or score > found[0]):
|
||||||
found = (score, j, c2, q * levels[j])
|
found = (score, j, c2, q * levels[j])
|
||||||
if found is None:
|
if found is None:
|
||||||
break
|
break
|
||||||
@@ -94,14 +78,17 @@ def _code(X, levels, parents) -> np.ndarray:
|
|||||||
|
|
||||||
|
|
||||||
class IntervalSurvival(BaseEstimator):
|
class IntervalSurvival(BaseEstimator):
|
||||||
"""Survival by intervals (`borders`, months), LR and HBN stacked per interval.
|
def __init__(
|
||||||
|
self,
|
||||||
`fit(X, months, event)` takes the categorical covariates `features`; the HBN's parents
|
features,
|
||||||
are `parents` (feature names) or, when None, learned per interval by the BDeu score.
|
borders=(0, 6, 12, 18),
|
||||||
"""
|
parents=None,
|
||||||
|
ess=1000,
|
||||||
def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
|
max_parents=5,
|
||||||
folds=5, shrink=20, seed=42): # fmt: skip
|
folds=5,
|
||||||
|
shrink=20,
|
||||||
|
seed=42,
|
||||||
|
):
|
||||||
self.features = features
|
self.features = features
|
||||||
self.borders = borders
|
self.borders = borders
|
||||||
self.parents = parents
|
self.parents = parents
|
||||||
@@ -111,8 +98,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)
|
||||||
@@ -126,7 +111,7 @@ class IntervalSurvival(BaseEstimator):
|
|||||||
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
|
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
|
||||||
columns.append(np.where(codes < 0, fallback, codes))
|
columns.append(np.where(codes < 0, fallback, codes))
|
||||||
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
|
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
|
||||||
return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
|
return (dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int))
|
||||||
|
|
||||||
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
|
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
|
||||||
fitted = []
|
fitted = []
|
||||||
@@ -135,42 +120,44 @@ class IntervalSurvival(BaseEstimator):
|
|||||||
if len(at_risk) == 0:
|
if len(at_risk) == 0:
|
||||||
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:
|
||||||
lr = LogisticRegression(C=1e6, max_iter=500)
|
lr = LogisticRegression(C=1000000.0, max_iter=500)
|
||||||
lr.fit(X_dum[at_risk], y, sample_weight=w)
|
lr.fit(X_dum[at_risk], y, sample_weight=w)
|
||||||
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
|
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
|
||||||
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:
|
||||||
parents = [list(self.features).index(p) for p in self.parents]
|
parents = [list(self.features).index(p) for p in self.parents]
|
||||||
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
|
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
|
||||||
n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
|
n = np.bincount(
|
||||||
minlength=q * 2).reshape(q, 2) # fmt: skip
|
_code(X, self.levels_, parents) * 2 + y, weights=w, minlength=q * 2
|
||||||
|
).reshape(q, 2)
|
||||||
aj = self.ess / q
|
aj = self.ess / q
|
||||||
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
|
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
|
||||||
return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
|
return (parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj))
|
||||||
|
|
||||||
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
|
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
|
||||||
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
|
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
|
||||||
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
|
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
|
||||||
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)),
|
||||||
|
)
|
||||||
for k in range(self.folds):
|
for k in range(self.folds):
|
||||||
test, train = np.where(fold == k)[0], np.where(fold != k)[0]
|
test, train = (np.where(fold == k)[0], np.where(fold != k)[0])
|
||||||
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
|
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
|
||||||
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
|
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
|
||||||
weights = []
|
weights = []
|
||||||
@@ -179,14 +166,14 @@ class IntervalSurvival(BaseEstimator):
|
|||||||
if len(at_risk) == 0:
|
if len(at_risk) == 0:
|
||||||
weights.append(0.5)
|
weights.append(0.5)
|
||||||
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)
|
y = np.where(e & (m < b), 0, 1)
|
||||||
w = np.where(~e & (m < b), 0.5, 1.0)
|
w = np.where(~e & (m < b), 0.5, 1.0)
|
||||||
p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
|
p1 = np.clip(oof_lr[at_risk, j], 1e-09, 1 - 1e-09)
|
||||||
p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
|
p2 = np.clip(oof_hbn[at_risk, j], 1e-09, 1 - 1e-09)
|
||||||
|
|
||||||
def loss(x, p1=p1, p2=p2, y=y, w=w):
|
def loss(x, p1=p1, p2=p2, y=y, w=w):
|
||||||
p = np.clip(x * p1 + (1 - x) * p2, 1e-9, 1 - 1e-9)
|
p = np.clip(x * p1 + (1 - x) * p2, 1e-09, 1 - 1e-09)
|
||||||
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
|
||||||
|
|
||||||
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
|
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
|
||||||
@@ -200,7 +187,7 @@ class IntervalSurvival(BaseEstimator):
|
|||||||
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
|
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
|
||||||
X_dum, X_int = self._encode(X)
|
X_dum, X_int = self._encode(X)
|
||||||
self.levels_ = X_int.max(axis=0) + 1
|
self.levels_ = X_int.max(axis=0) + 1
|
||||||
months, event = np.asarray(months, int), np.asarray(event, bool)
|
months, event = (np.asarray(months, int), np.asarray(event, bool))
|
||||||
if len(X) >= 2 * self.folds:
|
if len(X) >= 2 * self.folds:
|
||||||
self.weights_ = self._weights(X_dum, X_int, months, event)
|
self.weights_ = self._weights(X_dum, X_int, months, event)
|
||||||
else:
|
else:
|
||||||
@@ -209,35 +196,34 @@ 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 = [
|
||||||
"scenarios"] # fmt: skip
|
"person_id",
|
||||||
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
|
"index_date",
|
||||||
|
"horizon_years",
|
||||||
|
"probability",
|
||||||
|
"ci_low",
|
||||||
|
"ci_high",
|
||||||
|
"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,41 +231,30 @@ 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
|
||||||
def horizons(self) -> tuple[float, ...]:
|
def horizons(self) -> tuple[float, ...]:
|
||||||
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(
|
||||||
events = events.assign(date=pd.to_datetime(events["date"]),
|
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
|
||||||
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()
|
||||||
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
||||||
found["death_date"] = death.reindex(found.index)
|
found["death_date"] = death.reindex(found.index)
|
||||||
@@ -297,7 +272,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:
|
||||||
@@ -305,15 +280,13 @@ class Spec:
|
|||||||
refit = self._model().fit(sample, sample["months"], sample["event"])
|
refit = self._model().fit(sample, sample["months"], sample["event"])
|
||||||
return 1.0 - refit.survival(frame)
|
return 1.0 - refit.survival(frame)
|
||||||
|
|
||||||
replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
|
replicas = Parallel(n_jobs=-1)((delayed(mortality)(rows) for rows in samples))
|
||||||
tail = 50 * (1 - self.interval_level)
|
tail = 50 * (1 - self.interval_level)
|
||||||
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
|
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
|
||||||
rows = combinations.itertuples(index=False)
|
rows = combinations.itertuples(index=False)
|
||||||
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)
|
||||||
@@ -323,25 +296,30 @@ class Spec:
|
|||||||
model.intervals_ = self._intervals(train) if self.interval_level else {}
|
model.intervals_ = self._intervals(train) if self.interval_level else {}
|
||||||
weights = zip(self.borders[1:], model.weights_, strict=True)
|
weights = zip(self.borders[1:], model.weights_, strict=True)
|
||||||
metrics = {
|
metrics = {
|
||||||
"n_train": float(len(train)), "n_test": float(len(test)),
|
"n_train": float(len(train)),
|
||||||
"events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
|
"n_test": float(len(test)),
|
||||||
|
"events_train": float(train["event"].sum()),
|
||||||
|
"events_test": float(test["event"].sum()),
|
||||||
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
|
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
|
||||||
} # fmt: skip
|
}
|
||||||
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))
|
||||||
empty = ([np.nan] * h, [np.nan] * h)
|
empty = ([np.nan] * h, [np.nan] * h)
|
||||||
ends = [model.intervals_.get(tuple(c), empty)
|
ends = [
|
||||||
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
|
model.intervals_.get(tuple(c), empty)
|
||||||
|
for c in self._combinations(members).itertuples(index=False)
|
||||||
|
]
|
||||||
masks = scenario_masks(members, self.scenarios)
|
masks = scenario_masks(members, self.scenarios)
|
||||||
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
|
scenarios = [
|
||||||
for i in range(n)] # fmt: skip
|
SCENARIO_SEPARATOR.join((name for name, m in masks.items() if m[i])) or None
|
||||||
return pd.DataFrame({
|
for i in range(n)
|
||||||
|
]
|
||||||
|
return pd.DataFrame(
|
||||||
|
{
|
||||||
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||||
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
|
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
|
||||||
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
|
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
|
||||||
@@ -349,11 +327,10 @@ class Spec:
|
|||||||
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
|
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
|
||||||
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
|
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
|
||||||
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
||||||
})[OUTPUT] # fmt: skip
|
}
|
||||||
|
)[OUTPUT]
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- reports (curves)
|
|
||||||
|
|
||||||
BOOTSTRAP = 100
|
BOOTSTRAP = 100
|
||||||
BOOTSTRAP_SEED = 42
|
BOOTSTRAP_SEED = 42
|
||||||
|
|
||||||
@@ -361,16 +338,20 @@ BOOTSTRAP_SEED = 42
|
|||||||
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
|
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
|
||||||
members = pd.concat([data["train"], data["test"]])
|
members = pd.concat([data["train"], data["test"]])
|
||||||
return {
|
return {
|
||||||
"model": spec.name, "method": spec.method, "cohort": spec.cohort,
|
"model": spec.name,
|
||||||
|
"method": spec.method,
|
||||||
|
"cohort": spec.cohort,
|
||||||
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
|
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
|
||||||
"members": len(members),
|
"members": len(members),
|
||||||
"index_dates": [str(members["index_date"].min().date()),
|
"index_dates": [
|
||||||
str(members["index_date"].max().date())],
|
str(members["index_date"].min().date()),
|
||||||
|
str(members["index_date"].max().date()),
|
||||||
|
],
|
||||||
"horizons_months": list(spec.borders[1:]),
|
"horizons_months": list(spec.borders[1:]),
|
||||||
"follow_up_cap_months": spec.cap_months,
|
"follow_up_cap_months": spec.cap_months,
|
||||||
"notes": list(spec.notes),
|
"notes": list(spec.notes),
|
||||||
"metrics": metrics,
|
"metrics": metrics,
|
||||||
} # fmt: skip
|
}
|
||||||
|
|
||||||
|
|
||||||
def _curve(fitter, name: str) -> dict:
|
def _curve(fitter, name: str) -> dict:
|
||||||
@@ -378,17 +359,17 @@ def _curve(fitter, name: str) -> dict:
|
|||||||
return {
|
return {
|
||||||
"months": fitter.survival_function_.index.tolist(),
|
"months": fitter.survival_function_.index.tolist(),
|
||||||
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
|
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
|
||||||
"low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
|
"low": table.iloc[:, 0].tolist(),
|
||||||
} # fmt: skip
|
"high": table.iloc[:, 1].tolist(),
|
||||||
|
"name": name,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -419,36 +400,36 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
|
|||||||
km = curves.kaplan_meier(months, event, observed)
|
km = curves.kaplan_meier(months, event, observed)
|
||||||
return {
|
return {
|
||||||
"observado_hasta": observed,
|
"observado_hasta": observed,
|
||||||
"km": {"months": list(range(observed + 1)),
|
"km": {
|
||||||
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
|
"months": list(range(observed + 1)),
|
||||||
"weibull": {"t": grid.tolist(), "S": curves.weibull(grid, k, lam).tolist(),
|
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)},
|
||||||
"k": k, "lambda": lam},
|
},
|
||||||
"weibull_fractional": {"t": grid.tolist(),
|
"weibull": {
|
||||||
|
"t": grid.tolist(),
|
||||||
|
"S": curves.weibull(grid, k, lam).tolist(),
|
||||||
|
"k": k,
|
||||||
|
"lambda": lam,
|
||||||
|
},
|
||||||
|
"weibull_fractional": {
|
||||||
|
"t": grid.tolist(),
|
||||||
"S": curves.fractional(grid, k, *fractional).tolist(),
|
"S": curves.fractional(grid, k, *fractional).tolist(),
|
||||||
"alpha": fractional[0], "beta": fractional[1],
|
"alpha": fractional[0],
|
||||||
"lambda": fractional[2]},
|
"beta": fractional[1],
|
||||||
} # fmt: skip
|
"lambda": fractional[2],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
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"]
|
||||||
months, event = train["months"].to_numpy(), train["event"].to_numpy()
|
months, event = (train["months"].to_numpy(), train["event"].to_numpy())
|
||||||
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
|
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
|
||||||
if event.any() and (months > 0).all():
|
if event.any() and (months > 0).all():
|
||||||
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
|
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
|
||||||
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)
|
||||||
|
|
||||||
@@ -457,34 +438,47 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
|||||||
refit = spec._model().fit(sample, sample["months"], sample["event"])
|
refit = spec._model().fit(sample, sample["months"], sample["event"])
|
||||||
found = refit.survival(members)
|
found = refit.survival(members)
|
||||||
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
|
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
|
||||||
return found[: len(train)].mean(axis=0), by
|
return (found[: len(train)].mean(axis=0), by)
|
||||||
|
|
||||||
all_months, all_event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
all_months, all_event = (members["months"].to_numpy(), members["event"].to_numpy(bool))
|
||||||
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
|
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
|
||||||
jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
|
jobs = [
|
||||||
for m in drawn.values()] # fmt: skip
|
delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
|
||||||
|
for m in drawn.values()
|
||||||
|
]
|
||||||
jobs += [delayed(mean_survival)(rows) for rows in samples]
|
jobs += [delayed(mean_survival)(rows) for rows in samples]
|
||||||
done = Parallel(n_jobs=-1)(jobs)
|
done = Parallel(n_jobs=-1)(jobs)
|
||||||
drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
|
drawn_curves, replicas = (done[: len(drawn)], done[len(drawn) :])
|
||||||
band = np.stack([r[0] for r in replicas])
|
band = np.stack([r[0] for r in replicas])
|
||||||
point = model.survival(members)
|
point = model.survival(members)
|
||||||
scenarios = []
|
scenarios = []
|
||||||
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
|
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
|
||||||
spread = np.array([r[1][name] for r in replicas])
|
spread = np.array([r[1][name] for r in replicas])
|
||||||
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
|
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
|
||||||
scenarios.append({
|
scenarios.append(
|
||||||
|
{
|
||||||
"escenario": name,
|
"escenario": name,
|
||||||
"condiciones": [list(c) for c in spec.scenarios[name]],
|
"condiciones": [list(c) for c in spec.scenarios[name]],
|
||||||
"n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
|
"n": int(mask.sum()),
|
||||||
"horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
|
"fallecidos": int(all_event[mask].sum()),
|
||||||
|
"horizons_months": list(spec.borders[1:]),
|
||||||
|
"months_max": spec.cap_months,
|
||||||
**found,
|
**found,
|
||||||
"points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
|
"points": {
|
||||||
|
"COMB": {
|
||||||
|
"S": point[mask].mean(axis=0).tolist(),
|
||||||
"low": np.clip(low, 0, 1).tolist(),
|
"low": np.clip(low, 0, 1).tolist(),
|
||||||
"high": np.clip(high, 0, 1).tolist()}},
|
"high": np.clip(high, 0, 1).tolist(),
|
||||||
|
}
|
||||||
|
},
|
||||||
"bootstrap_replicas": len(replicas),
|
"bootstrap_replicas": len(replicas),
|
||||||
}) # fmt: skip
|
}
|
||||||
skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
|
)
|
||||||
for n, m in masks.items() if n not in drawn] # fmt: skip
|
skipped = [
|
||||||
|
{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
|
||||||
|
for n, m in masks.items()
|
||||||
|
if n not in drawn
|
||||||
|
]
|
||||||
combinations = spec._combinations(train).value_counts().reset_index(name="members")
|
combinations = spec._combinations(train).value_counts().reset_index(name="members")
|
||||||
survival = model.survival(combinations.replace(UNKNOWN, None))
|
survival = model.survival(combinations.replace(UNKNOWN, None))
|
||||||
return {
|
return {
|
||||||
@@ -505,39 +499,49 @@ 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",
|
||||||
"IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
|
"variable",
|
||||||
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov",
|
"categoria",
|
||||||
"c4_supervivencia", "criterios_cumplidos", "clasificacion",
|
"referencia",
|
||||||
) # fmt: skip
|
"n_categoria",
|
||||||
|
"OR_muerte",
|
||||||
|
"IC95_inf",
|
||||||
|
"IC95_sup",
|
||||||
|
"p",
|
||||||
|
"p_ajustado_BH",
|
||||||
|
"en_manta_markov",
|
||||||
|
"S_categoria",
|
||||||
|
"S_referencia",
|
||||||
|
"delta_S",
|
||||||
|
"delta_IC95_inf",
|
||||||
|
"delta_IC95_sup",
|
||||||
|
"c1_or",
|
||||||
|
"c3_manta_markov",
|
||||||
|
"c4_supervivencia",
|
||||||
|
"criterios_cumplidos",
|
||||||
|
"clasificacion",
|
||||||
|
)
|
||||||
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]
|
||||||
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
months, event = (members["months"].to_numpy(), members["event"].to_numpy(bool))
|
||||||
died = event & (months < horizon)
|
died = event & (months < horizon)
|
||||||
known = died | (months >= horizon)
|
known = died | (months >= horizon)
|
||||||
data = spec._combinations(members)[known].reset_index(drop=True)
|
data = spec._combinations(members)[known].reset_index(drop=True)
|
||||||
y, months, event = died[known].astype(int), months[known], event[known]
|
y, months, event = (died[known].astype(int), months[known], event[known])
|
||||||
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
|
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
|
||||||
if len(data) == 0 or y.min() == y.max():
|
if len(data) == 0 or y.min() == y.max():
|
||||||
return empty
|
return empty
|
||||||
@@ -548,14 +552,14 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
|
|||||||
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
|
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
|
||||||
|
|
||||||
def complete(table, variables):
|
def complete(table, variables):
|
||||||
return rated.complete(table, variables, reference, data, months, event, horizon,
|
return rated.complete(
|
||||||
SURVIVAL_COLUMNS) # fmt: skip
|
table, variables, reference, data, months, event, horizon, SURVIVAL_COLUMNS
|
||||||
|
)
|
||||||
|
|
||||||
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)
|
||||||
intrinsic) # fmt: skip
|
|
||||||
except (np.linalg.LinAlgError, ValueError):
|
except (np.linalg.LinAlgError, ValueError):
|
||||||
return empty
|
return empty
|
||||||
tab["c2_estabilidad"] = np.nan
|
tab["c2_estabilidad"] = np.nan
|
||||||
@@ -570,9 +574,10 @@ def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) ->
|
|||||||
tr = None
|
tr = None
|
||||||
if tr is not None:
|
if tr is not None:
|
||||||
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||||
tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)],
|
tr = complete(
|
||||||
treatment) # fmt: skip
|
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
||||||
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
|
)
|
||||||
|
tr["tipo"], tr["clasificacion"] = ("tratamiento", TREATMENT_CLASS)
|
||||||
tab = pd.concat([tab, tr], ignore_index=True)
|
tab = pd.concat([tab, tr], ignore_index=True)
|
||||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||||
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
|
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
|
||||||
@@ -581,8 +586,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
|
||||||
@@ -591,17 +594,20 @@ def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) ->
|
|||||||
for name, mask in scenario_masks(members, spec.scenarios).items():
|
for name, mask in scenario_masks(members, spec.scenarios).items():
|
||||||
if not mask.any() or found.empty:
|
if not mask.any() or found.empty:
|
||||||
continue
|
continue
|
||||||
rows.append({
|
rows.append(
|
||||||
"escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
|
{
|
||||||
"n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found),
|
"escenario": name,
|
||||||
}) # fmt: skip
|
"condiciones": [list(c) for c in spec.scenarios[name]],
|
||||||
|
"n_escenario": int(mask.sum()),
|
||||||
|
**rated.scenario_row(data, mask, found),
|
||||||
|
}
|
||||||
|
)
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
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),
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
+25
-55
@@ -1,25 +1,10 @@
|
|||||||
"""The EEG–ADOS-2 association (core.tea.association says what it relates): per biomarker,
|
|
||||||
zone and outcome, how a child's deviation from the age curve (z) goes with an altered
|
|
||||||
ADOS-2 item or a high CSS, adjusted for age and module.
|
|
||||||
|
|
||||||
- An item: Firth's penalised logistic regression of "altered" on z (the principal model; its
|
|
||||||
odds ratio, a 95 % profile-likelihood interval and a likelihood-ratio p), with a
|
|
||||||
cumulative-logit model of the item's level as sensitivity; the CSS the other way round.
|
|
||||||
- q: Benjamini–Hochberg within each biomarker.
|
|
||||||
- A child's probability: the principal model at her z (Firth's with the FLIC intercept, so
|
|
||||||
its probabilities average to the observed rate), and the reference child's (z = 0, the
|
|
||||||
cohort's mean age, the commonest module).
|
|
||||||
The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py)."""
|
|
||||||
|
|
||||||
import warnings
|
import warnings
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from scipy import optimize, stats
|
from scipy import optimize, stats
|
||||||
from scipy.special import expit
|
from scipy.special import expit
|
||||||
from statsmodels.stats.multitest import multipletests
|
from statsmodels.stats.multitest import multipletests
|
||||||
|
|
||||||
from core.tea import association as spec
|
from core.tea import association as spec
|
||||||
|
|
||||||
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
|
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
|
||||||
@@ -28,7 +13,6 @@ TOO_FEW = "too few data or no variation"
|
|||||||
|
|
||||||
|
|
||||||
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
|
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
|
||||||
"""Item `number`'s algorithm score for each child whose module administers it."""
|
|
||||||
name, modules = spec.ITEMS[number]
|
name, modules = spec.ITEMS[number]
|
||||||
if name not in frame or "module" not in frame:
|
if name not in frame or "module" not in frame:
|
||||||
return pd.Series(np.nan, index=frame.index)
|
return pd.Series(np.nan, index=frame.index)
|
||||||
@@ -44,9 +28,6 @@ def has_items(frame: pd.DataFrame) -> bool:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Design:
|
class Design:
|
||||||
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
|
|
||||||
the cohort's mean and each categorical one against its commonest level."""
|
|
||||||
|
|
||||||
predictor: str
|
predictor: str
|
||||||
numeric: dict[str, float] = field(default_factory=dict)
|
numeric: dict[str, float] = field(default_factory=dict)
|
||||||
categorical: dict[str, list[str]] = field(default_factory=dict)
|
categorical: dict[str, list[str]] = field(default_factory=dict)
|
||||||
@@ -64,7 +45,7 @@ class Design:
|
|||||||
commonest = v.value_counts().index[0]
|
commonest = v.value_counts().index[0]
|
||||||
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
|
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
|
||||||
if levels:
|
if levels:
|
||||||
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
|
d.categorical[a], d.reference[a] = ([str(x) for x in levels], str(commonest))
|
||||||
return d
|
return d
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -106,7 +87,6 @@ class Design:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# Firth: the log-likelihood penalised by half the log-determinant of the information.
|
|
||||||
def _penalised(b, X, y) -> float:
|
def _penalised(b, X, y) -> float:
|
||||||
eta = X @ b
|
eta = X @ b
|
||||||
w = expit(eta) * (1 - expit(eta))
|
w = expit(eta) * (1 - expit(eta))
|
||||||
@@ -115,54 +95,49 @@ def _penalised(b, X, y) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def _gradient(b, X, y):
|
def _gradient(b, X, y):
|
||||||
"""The penalised score and the information at `b`."""
|
|
||||||
p = expit(X @ b)
|
p = expit(X @ b)
|
||||||
w = p * (1 - p)
|
w = p * (1 - p)
|
||||||
info = X.T @ (X * w[:, None])
|
info = X.T @ (X * w[:, None])
|
||||||
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||||
return X.T @ (y - p + leverage * (0.5 - p)), info
|
return (X.T @ (y - p + leverage * (0.5 - p)), info)
|
||||||
|
|
||||||
|
|
||||||
def _firth_fit(X, y, max_iter=200, tol=1e-10):
|
def _firth_fit(X, y, max_iter=200, tol=1e-10):
|
||||||
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
|
|
||||||
b = np.zeros(X.shape[1])
|
b = np.zeros(X.shape[1])
|
||||||
best = _penalised(b, X, y)
|
best = _penalised(b, X, y)
|
||||||
for _ in range(max_iter):
|
for _ in range(max_iter):
|
||||||
score, info = _gradient(b, X, y)
|
score, info = _gradient(b, X, y)
|
||||||
step, t = np.linalg.solve(info, score), 1.0
|
step, t = (np.linalg.solve(info, score), 1.0)
|
||||||
while t > 1e-8:
|
while t > 1e-08:
|
||||||
trial = _penalised(b + t * step, X, y)
|
trial = _penalised(b + t * step, X, y)
|
||||||
if trial >= best - 1e-12:
|
if trial >= best - 1e-12:
|
||||||
break
|
break
|
||||||
t /= 2
|
t /= 2
|
||||||
b, best = b + t * step, trial
|
b, best = (b + t * step, trial)
|
||||||
if np.max(np.abs(t * step)) < tol:
|
if np.max(np.abs(t * step)) < tol:
|
||||||
break
|
break
|
||||||
return b, best
|
return (b, best)
|
||||||
|
|
||||||
|
|
||||||
def _firth_profile(value, j, X, y, start) -> float:
|
def _firth_profile(value, j, X, y, start) -> float:
|
||||||
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
|
|
||||||
free = [k for k in range(X.shape[1]) if k != j]
|
free = [k for k in range(X.shape[1]) if k != j]
|
||||||
|
|
||||||
def negative(bf):
|
def negative(bf):
|
||||||
b = np.empty(X.shape[1])
|
b = np.empty(X.shape[1])
|
||||||
b[free], b[j] = bf, value
|
b[free], b[j] = (bf, value)
|
||||||
v = _penalised(b, X, y)
|
v = _penalised(b, X, y)
|
||||||
if not np.isfinite(v):
|
if not np.isfinite(v):
|
||||||
return 1e10, np.zeros(len(free))
|
return (10000000000.0, np.zeros(len(free)))
|
||||||
return -v, -_gradient(b, X, y)[0][free]
|
return (-v, -_gradient(b, X, y)[0][free])
|
||||||
|
|
||||||
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
||||||
|
|
||||||
|
|
||||||
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
||||||
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
|
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95
|
||||||
each side of `centre`, searched in steps of `scale` (infinite if never)."""
|
|
||||||
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
|
||||||
limits = []
|
limits = []
|
||||||
for sign in (-1, 1):
|
for sign in (-1, 1):
|
||||||
previous, limit = centre, sign * np.inf
|
previous, limit = (centre, sign * np.inf)
|
||||||
for k in range(1, 80):
|
for k in range(1, 80):
|
||||||
v = centre + sign * scale * k
|
v = centre + sign * scale * k
|
||||||
if drop(v) > 0:
|
if drop(v) > 0:
|
||||||
@@ -170,7 +145,7 @@ def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
|||||||
break
|
break
|
||||||
previous = v
|
previous = v
|
||||||
limits.append(limit)
|
limits.append(limit)
|
||||||
return limits[0], limits[1]
|
return (limits[0], limits[1])
|
||||||
|
|
||||||
|
|
||||||
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
|
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
|
||||||
@@ -193,23 +168,21 @@ def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
|
|||||||
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
|
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
|
||||||
y = d[outcome].to_numpy(float)
|
y = d[outcome].to_numpy(float)
|
||||||
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
|
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
|
||||||
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
|
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or (d[predictor].std() == 0):
|
||||||
return {**out, "reason": TOO_FEW}
|
return {**out, "reason": TOO_FEW}
|
||||||
design = Design.of(d, predictor)
|
design = Design.of(d, predictor)
|
||||||
X = design.matrix(d)
|
X = design.matrix(d)
|
||||||
b, top = _firth_fit(X, y)
|
b, top = _firth_fit(X, y)
|
||||||
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
|
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
|
||||||
profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731
|
profile = lambda v: _firth_profile(v, 1, X, y, b)
|
||||||
low, high = _interval(profile, b[1], top, max(se, 0.05))
|
low, high = _interval(profile, b[1], top, max(se, 0.05))
|
||||||
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
|
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
|
||||||
# FLIC: the intercept refitted so the probabilities add up to the events.
|
|
||||||
eta = X[:, 1:] @ b[1:]
|
eta = X[:, 1:] @ b[1:]
|
||||||
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||||
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
|
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
|
||||||
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
|
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
|
||||||
|
|
||||||
|
|
||||||
# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing.
|
|
||||||
def _ordinal_nll(par, X, y, K) -> float:
|
def _ordinal_nll(par, X, y, K) -> float:
|
||||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||||
eta = X @ par[K - 1 :]
|
eta = X @ par[K - 1 :]
|
||||||
@@ -224,16 +197,16 @@ def _ordinal_fit(X, y, K, fixed=None):
|
|||||||
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
||||||
if fixed is None:
|
if fixed is None:
|
||||||
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
||||||
return r.x, float(r.fun)
|
return (r.x, float(r.fun))
|
||||||
j, value = fixed
|
j, value = fixed
|
||||||
free = [k for k in range(len(start)) if k != K - 1 + j]
|
free = [k for k in range(len(start)) if k != K - 1 + j]
|
||||||
|
|
||||||
def nll(q):
|
def nll(q):
|
||||||
par = np.empty(len(start))
|
par = np.empty(len(start))
|
||||||
par[free], par[K - 1 + j] = q, value
|
par[free], par[K - 1 + j] = (q, value)
|
||||||
return _ordinal_nll(par, X, y, K)
|
return _ordinal_nll(par, X, y, K)
|
||||||
|
|
||||||
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
|
return (None, float(optimize.minimize(nll, start[free], method="BFGS").fun))
|
||||||
|
|
||||||
|
|
||||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
||||||
@@ -252,7 +225,7 @@ def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
|||||||
beta = par[K - 1 :]
|
beta = par[K - 1 :]
|
||||||
if abs(beta[0]) > 20:
|
if abs(beta[0]) > 20:
|
||||||
return {**out, "reason": "does not converge (separation)"}
|
return {**out, "reason": "does not converge (separation)"}
|
||||||
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731
|
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1]
|
||||||
low, high_ = _interval(profile, beta[0], -nll, 0.1)
|
low, high_ = _interval(profile, beta[0], -nll, 0.1)
|
||||||
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
||||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||||
@@ -267,15 +240,15 @@ def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||||
"""Each child's probability of the outcome under `fit`, and the reference child's."""
|
|
||||||
s = fit["state"]
|
s = fit["state"]
|
||||||
X = Design.from_state(s["design"]).matrix(t)
|
X = Design.from_state(s["design"]).matrix(t)
|
||||||
if fit["model"] == "firth":
|
if fit["model"] == "firth":
|
||||||
return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float(
|
return (
|
||||||
expit(s["intercept"])
|
expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])),
|
||||||
|
float(expit(s["intercept"])),
|
||||||
)
|
)
|
||||||
if s["threshold"] is None:
|
if s["threshold"] is None:
|
||||||
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]
|
return (np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"])
|
||||||
return (
|
return (
|
||||||
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
|
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
|
||||||
float(1 - expit(s["threshold"])),
|
float(1 - expit(s["threshold"])),
|
||||||
@@ -291,7 +264,6 @@ def _guarded(fit, *args) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
|
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
|
||||||
"""Every pair's principal and sensitivity models and its q: what the association is."""
|
|
||||||
if level == "auto":
|
if level == "auto":
|
||||||
level = "item" if has_items(cohort) else "domain"
|
level = "item" if has_items(cohort) else "domain"
|
||||||
rows = []
|
rows = []
|
||||||
@@ -328,11 +300,10 @@ def outcome_code(row: dict) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def associations(fitted: dict) -> list[dict]:
|
def associations(fitted: dict) -> list[dict]:
|
||||||
"""One row per pair: what the governance report and the record show."""
|
|
||||||
out = []
|
out = []
|
||||||
for r in fitted["rows"]:
|
for r in fitted["rows"]:
|
||||||
f, s = r["principal"], r["sensitivity"]
|
f, s = (r["principal"], r["sensitivity"])
|
||||||
ratio, other = f.get("odds_ratio"), s.get("odds_ratio")
|
ratio, other = (f.get("odds_ratio"), s.get("odds_ratio"))
|
||||||
out.append(
|
out.append(
|
||||||
{
|
{
|
||||||
"biomarker": r["biomarker"],
|
"biomarker": r["biomarker"],
|
||||||
@@ -340,7 +311,7 @@ def associations(fitted: dict) -> list[dict]:
|
|||||||
"kind": r["kind"],
|
"kind": r["kind"],
|
||||||
"outcome": r["outcome"],
|
"outcome": r["outcome"],
|
||||||
"outcome_code": outcome_code(r),
|
"outcome_code": outcome_code(r),
|
||||||
"event": f">={spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH}",
|
"event": f">={(spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH)}",
|
||||||
"model": f["model"],
|
"model": f["model"],
|
||||||
"n": f["n"],
|
"n": f["n"],
|
||||||
"odds_ratio": ratio,
|
"odds_ratio": ratio,
|
||||||
@@ -360,7 +331,6 @@ def associations(fitted: dict) -> list[dict]:
|
|||||||
|
|
||||||
|
|
||||||
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]:
|
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]:
|
||||||
"""Each child's probability under every estimated pair, and the reference child's."""
|
|
||||||
out = []
|
out = []
|
||||||
for r in fitted["rows"]:
|
for r in fitted["rows"]:
|
||||||
f = r["principal"]
|
f = r["principal"]
|
||||||
|
|||||||
@@ -1,2 +1 @@
|
|||||||
"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`,
|
pass
|
||||||
`curves.py`)."""
|
|
||||||
|
|||||||
@@ -1,22 +1,7 @@
|
|||||||
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
|
|
||||||
|
|
||||||
analysis = analyze(edf_bytes, birth_date)
|
|
||||||
|
|
||||||
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
|
|
||||||
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are
|
|
||||||
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
|
|
||||||
|
|
||||||
The age is the EDF header's (recording start minus birth date) when it has both dates, else the
|
|
||||||
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
|
|
||||||
`error` set, keeping the verdict and checks when validation finished before it. Missing values
|
|
||||||
are None.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import math
|
import math
|
||||||
import re
|
import re
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
|
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
|
||||||
|
|
||||||
DAYS_PER_MONTH = 30.4375
|
DAYS_PER_MONTH = 30.4375
|
||||||
@@ -27,7 +12,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 +27,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
|
||||||
|
|
||||||
|
|
||||||
@@ -54,7 +38,7 @@ def _number(v) -> float | None:
|
|||||||
|
|
||||||
|
|
||||||
def _error(exc: Exception) -> str:
|
def _error(exc: Exception) -> str:
|
||||||
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
message = re.sub("(/|[A-Za-z]:\\\\)[^\\s'\\\"]*", "<path>", str(exc))[:300]
|
||||||
return f"{type(exc).__name__}: {message}"
|
return f"{type(exc).__name__}: {message}"
|
||||||
|
|
||||||
|
|
||||||
@@ -65,8 +49,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,
|
||||||
@@ -128,5 +110,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:
|
||||||
return Analysis(**out | dict(error=_error(exc)))
|
return Analysis(**out | dict(error=_error(exc)))
|
||||||
|
|||||||
@@ -1,32 +1,33 @@
|
|||||||
"""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
|
||||||
from scipy.stats import theilslopes
|
from scipy.stats import theilslopes
|
||||||
|
|
||||||
from models.tea.eeg import signals, spikes, spindles
|
from models.tea.eeg import signals, spikes, spindles
|
||||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||||
from models.tea.eeg.sleep import POSTERIOR
|
from models.tea.eeg.sleep import POSTERIOR
|
||||||
|
|
||||||
MIN_WINDOWS = 15
|
MIN_WINDOWS = 15
|
||||||
FRONT_BACK = {
|
FRONT_BACK = {
|
||||||
"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
|
"Fp1": 0.95,
|
||||||
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
|
"Fp2": 0.95,
|
||||||
"Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
|
"F7": 0.59,
|
||||||
} # fmt: skip
|
"F3": 0.53,
|
||||||
|
"Fz": 0.5,
|
||||||
|
"F4": 0.53,
|
||||||
|
"F8": 0.59,
|
||||||
|
"T3": 0.0,
|
||||||
|
"C3": 0.0,
|
||||||
|
"Cz": 0.0,
|
||||||
|
"C4": 0.0,
|
||||||
|
"T4": 0.0,
|
||||||
|
"T5": -0.59,
|
||||||
|
"P3": -0.53,
|
||||||
|
"Pz": -0.5,
|
||||||
|
"P4": -0.53,
|
||||||
|
"T6": -0.59,
|
||||||
|
"O1": -0.95,
|
||||||
|
"O2": -0.95,
|
||||||
|
}
|
||||||
CODES = (
|
CODES = (
|
||||||
"posterior_rhythm",
|
"posterior_rhythm",
|
||||||
"spindles_n2",
|
"spindles_n2",
|
||||||
@@ -37,11 +38,10 @@ 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
|
||||||
x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
|
x, n = (prep.data(names), int(round(WINDOW_S * prep.fs)))
|
||||||
found = []
|
found = []
|
||||||
for a in (int(round(float(s) * prep.fs)) for s in starts):
|
for a in (int(round(float(s) * prep.fs)) for s in starts):
|
||||||
if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
|
if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
|
||||||
@@ -77,8 +77,7 @@ 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, {}, {})
|
||||||
features["eeg-posterior-rhythm"] = {"value": rhythm}
|
features["eeg-posterior-rhythm"] = {"value": rhythm}
|
||||||
@@ -110,4 +109,4 @@ def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
|
|||||||
gradient = delta_gradient(prep, states)
|
gradient = delta_gradient(prep, states)
|
||||||
metrics["anteroposterior_gradient"] = (gradient, {}, {})
|
metrics["anteroposterior_gradient"] = (gradient, {}, {})
|
||||||
features["eeg-gradient"] = {"value": gradient}
|
features["eeg-gradient"] = {"value": gradient}
|
||||||
return {code: metrics[code] for code in CODES}, features
|
return ({code: metrics[code] for code in CODES}, features)
|
||||||
|
|||||||
+43
-61
@@ -1,38 +1,32 @@
|
|||||||
"""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
|
||||||
|
|
||||||
from models.tea.eeg import signals
|
from models.tea.eeg import signals
|
||||||
from models.tea.eeg.read import Recording
|
from models.tea.eeg.read import Recording
|
||||||
|
|
||||||
NEIGHBOURS = {
|
NEIGHBOURS = {
|
||||||
"Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"),
|
"Fp1": ("Fp2", "F3", "F7"),
|
||||||
"F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"),
|
"Fp2": ("Fp1", "F4", "F8"),
|
||||||
"Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"),
|
"F7": ("Fp1", "F3", "T3"),
|
||||||
"C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"),
|
"F8": ("Fp2", "F4", "T4"),
|
||||||
"T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"),
|
"F3": ("Fp1", "F7", "Fz", "C3"),
|
||||||
"P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"),
|
"F4": ("Fp2", "F8", "Fz", "C4"),
|
||||||
|
"Fz": ("F3", "F4", "Cz"),
|
||||||
|
"T3": ("F7", "C3", "T5"),
|
||||||
|
"T4": ("F8", "C4", "T6"),
|
||||||
|
"C3": ("F3", "T3", "Cz", "P3"),
|
||||||
|
"C4": ("F4", "T4", "Cz", "P4"),
|
||||||
|
"Cz": ("Fz", "C3", "C4", "Pz"),
|
||||||
|
"T5": ("T3", "P3", "O1"),
|
||||||
|
"T6": ("T4", "P4", "O2"),
|
||||||
|
"P3": ("C3", "T5", "Pz", "O1"),
|
||||||
|
"P4": ("C4", "T6", "Pz", "O2"),
|
||||||
|
"Pz": ("Cz", "P3", "P4"),
|
||||||
|
"O1": ("T5", "P3", "O2"),
|
||||||
"O2": ("T6", "P4", "O1"),
|
"O2": ("T6", "P4", "O1"),
|
||||||
} # fmt: skip
|
}
|
||||||
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
|
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
|
||||||
MIN_CLEAN_PCT = 60.0
|
MIN_CLEAN_PCT = 60.0
|
||||||
MIN_COVERAGE = 0.90
|
MIN_COVERAGE = 0.9
|
||||||
MAX_BAD_SCALP = 2
|
MAX_BAD_SCALP = 2
|
||||||
MIN_SCALP = 12
|
MIN_SCALP = 12
|
||||||
MAX_LINE_DB = 45.0
|
MAX_LINE_DB = 45.0
|
||||||
@@ -43,14 +37,14 @@ 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)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def ears_usable(self) -> bool:
|
def ears_usable(self) -> bool:
|
||||||
return all(ear not in self.bad for ear in ("A1", "A2"))
|
return all((ear not in self.bad for ear in ("A1", "A2")))
|
||||||
|
|
||||||
|
|
||||||
def check(
|
def check(
|
||||||
@@ -88,12 +82,11 @@ 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")]
|
||||||
out = []
|
out = []
|
||||||
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
|
if np.mean(np.abs(np.diff(finite)) < 1e-09) > 0.5:
|
||||||
out.append(("frozen", "frozen"))
|
out.append(("frozen", "frozen"))
|
||||||
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
|
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
|
||||||
out.append(("saturated", "saturated"))
|
out.append(("saturated", "saturated"))
|
||||||
@@ -103,13 +96,11 @@ 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))
|
||||||
if blocks < 6:
|
if blocks < 6:
|
||||||
return low, high
|
return (low, high)
|
||||||
sd = np.full((blocks, y.shape[1]), np.nan)
|
sd = np.full((blocks, y.shape[1]), np.nan)
|
||||||
for b in range(blocks):
|
for b in range(blocks):
|
||||||
block = y[b * size : (b + 1) * size]
|
block = y[b * size : (b + 1) * size]
|
||||||
@@ -123,11 +114,10 @@ def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
|||||||
if len(v) >= 6:
|
if len(v) >= 6:
|
||||||
low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35))
|
low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35))
|
||||||
high[i] = np.mean(v > 4.0)
|
high[i] = np.mean(v > 4.0)
|
||||||
return low, high
|
return (low, high)
|
||||||
|
|
||||||
|
|
||||||
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 {}
|
||||||
@@ -140,13 +130,12 @@ def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str
|
|||||||
if not near:
|
if not near:
|
||||||
continue
|
continue
|
||||||
best = max(near, key=lambda j: r[k, j])
|
best = max(near, key=lambda j: r[k, j])
|
||||||
if r[k, best] > 0.99 and not (far and max(r[k, j] for j in far) > 0.99):
|
if r[k, best] > 0.99 and (not (far and max((r[k, j] for j in far)) > 0.99)):
|
||||||
out[name] = next(n for n, j in index.items() if j == best)
|
out[name] = next((n for n, j in index.items() if j == best))
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
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]
|
||||||
@@ -163,8 +152,7 @@ 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 = {
|
||||||
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
|
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
|
||||||
@@ -181,7 +169,7 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
|||||||
ears = _ears(y40, fs, names)
|
ears = _ears(y40, fs, names)
|
||||||
missing = 1 - np.isfinite(x).mean(axis=0)
|
missing = 1 - np.isfinite(x).mean(axis=0)
|
||||||
for i, name in enumerate(names):
|
for i, name in enumerate(names):
|
||||||
found, k = reasons[name], kinds[name]
|
found, k = (reasons[name], kinds[name])
|
||||||
if missing[i] > missing.min() + 0.02:
|
if missing[i] > missing.min() + 0.02:
|
||||||
excess = 100 * (missing[i] - missing.min())
|
excess = 100 * (missing[i] - missing.min())
|
||||||
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
|
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
|
||||||
@@ -189,9 +177,9 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
|||||||
continue
|
continue
|
||||||
if k == "eeg" and name in bridges:
|
if k == "eeg" and name in bridges:
|
||||||
found.append(("bridge", f"bridge with {bridges[name]}"))
|
found.append(("bridge", f"bridge with {bridges[name]}"))
|
||||||
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
|
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and (ratio[i] > 4.0):
|
||||||
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
|
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
|
||||||
if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
|
if name in ears and ears[name][1] > 0.2 and (ears[name][0] < 0.5 * ears[name][1]):
|
||||||
c, e = ears[name]
|
c, e = ears[name]
|
||||||
found.append(
|
found.append(
|
||||||
(
|
(
|
||||||
@@ -199,19 +187,18 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
|||||||
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
|
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if np.isfinite(low[i]) and low[i] > 0.10:
|
if np.isfinite(low[i]) and low[i] > 0.1:
|
||||||
found.append(
|
found.append(
|
||||||
(
|
(
|
||||||
"intermittent-contact",
|
"intermittent-contact",
|
||||||
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
|
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
|
if k in ("eeg", "ear") and np.isfinite(burst[i]) and (burst[i] > 0.05):
|
||||||
found.append(
|
found.append(
|
||||||
(
|
(
|
||||||
"intermittent-bursts",
|
"intermittent-bursts",
|
||||||
f"intermittent contact by bursts "
|
f"intermittent contact by bursts ({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
|
||||||
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if k in ("eog", "ecg"):
|
if k in ("eog", "ecg"):
|
||||||
@@ -220,16 +207,13 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
|||||||
found.append(
|
found.append(
|
||||||
(
|
(
|
||||||
"aux-amplitude",
|
"aux-amplitude",
|
||||||
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, "
|
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, out of range even for {k.upper()}",
|
||||||
f"out of range even for {k.upper()}",
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return {name: found for name, found in reasons.items() if found}
|
return {name: found for name, found in reasons.items() if found}
|
||||||
|
|
||||||
|
|
||||||
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))
|
||||||
@@ -259,21 +243,20 @@ 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)
|
||||||
rms, flat = {}, {}
|
rms, flat = ({}, {})
|
||||||
for k, i in enumerate(columns):
|
for k, i in enumerate(columns):
|
||||||
v = y[:, k][np.isfinite(y[:, k])]
|
v = y[:, k][np.isfinite(y[:, k])]
|
||||||
rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan
|
rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan
|
||||||
flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-9)) if len(v) > 1 else 1.0
|
flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-09)) if len(v) > 1 else 1.0
|
||||||
scalp = rec.of("eeg")
|
scalp = rec.of("eeg")
|
||||||
median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan
|
median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan
|
||||||
triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5]
|
triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5]
|
||||||
minutes = rec.duration_s * clean_pct / 100 / 60
|
minutes = rec.duration_s * clean_pct / 100 / 60
|
||||||
base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP
|
base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP
|
||||||
if not (base and clean_pct >= 30 and minutes >= 3):
|
if not (base and clean_pct >= 30 and (minutes >= 3)):
|
||||||
level = NOT_ANALYZABLE
|
level = NOT_ANALYZABLE
|
||||||
elif not (clean_pct >= 50 and minutes >= 3):
|
elif not (clean_pct >= 50 and minutes >= 3):
|
||||||
level = "partial"
|
level = "partial"
|
||||||
@@ -281,7 +264,7 @@ def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, covera
|
|||||||
level = "no_ear_reference"
|
level = "no_ear_reference"
|
||||||
else:
|
else:
|
||||||
level = "complete"
|
level = "complete"
|
||||||
return level, triaged
|
return (level, triaged)
|
||||||
|
|
||||||
|
|
||||||
def validate(rec: Recording, mains_hz: float) -> Validation:
|
def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||||
@@ -291,13 +274,12 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
|||||||
qc = usable if len(usable) >= 2 else scalp
|
qc = usable if len(usable) >= 2 else scalp
|
||||||
y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0)
|
y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0)
|
||||||
windows = window_qc(y, rec.fs)
|
windows = window_qc(y, rec.fs)
|
||||||
clean_pct = 100.0 * sum(v == "clean" for *_, v in windows) / max(len(windows), 1)
|
clean_pct = 100.0 * sum((v == "clean" for *_, v in windows)) / max(len(windows), 1)
|
||||||
coverage = float(np.isfinite(rec.x).all(axis=1).mean())
|
coverage = float(np.isfinite(rec.x).all(axis=1).mean())
|
||||||
columns = [rec.names.index(n) for n in scalp] if scalp else slice(None)
|
columns = [rec.names.index(n) for n in scalp] if scalp else slice(None)
|
||||||
db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz)
|
db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz)
|
||||||
line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan
|
line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan
|
||||||
level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage)
|
level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage)
|
||||||
|
|
||||||
rows = [
|
rows = [
|
||||||
check(code, electrode=name, text=reason, abnormal=True)
|
check(code, electrode=name, text=reason, abnormal=True)
|
||||||
for name, found in flagged.items()
|
for name, found in flagged.items()
|
||||||
@@ -344,6 +326,6 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
|||||||
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
|
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP
|
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and (len(usable) >= MIN_SCALP)
|
||||||
bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
|
bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
|
||||||
return Validation(valid, level, bad, clean_pct, line, rows)
|
return Validation(valid, level, bad, clean_pct, line, rows)
|
||||||
|
|||||||
+14
-42
@@ -1,25 +1,5 @@
|
|||||||
"""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
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from scipy import stats
|
from scipy import stats
|
||||||
@@ -35,10 +15,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,15 +34,14 @@ 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))
|
||||||
|
|
||||||
|
|
||||||
def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
|
def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
|
||||||
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
|
ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0)
|
||||||
v, log_age = values[ok], np.log(ages[ok])
|
v, log_age = (values[ok], np.log(ages[ok]))
|
||||||
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
|
curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}}
|
||||||
for a in CURVE_AGES:
|
for a in CURVE_AGES:
|
||||||
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
|
w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2)
|
||||||
@@ -85,11 +64,11 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
|
|||||||
n = np.round(values * exposure)
|
n = np.round(values * exposure)
|
||||||
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
|
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
|
||||||
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
|
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
|
||||||
n, x = n[keep], exposure[keep]
|
n, x = (n[keep], exposure[keep])
|
||||||
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 +80,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 = {}
|
||||||
@@ -124,7 +101,7 @@ def _score_curve(baseline: dict, value: float, age: float) -> dict:
|
|||||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||||
if not len(curve) or not age > 0:
|
if not len(curve) or not age > 0:
|
||||||
return out
|
return out
|
||||||
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0])
|
log_ages, at = (np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0]))
|
||||||
if not log_ages.min() <= at <= log_ages.max():
|
if not log_ages.min() <= at <= log_ages.max():
|
||||||
return out
|
return out
|
||||||
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES}
|
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES}
|
||||||
@@ -142,13 +119,13 @@ def _score_curve(baseline: dict, value: float, age: float) -> dict:
|
|||||||
|
|
||||||
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
|
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
|
||||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||||
rate, k = baseline["rate"], baseline["k"]
|
rate, k = (baseline["rate"], baseline["k"])
|
||||||
lo, hi = baseline["ages"]
|
lo, hi = baseline["ages"]
|
||||||
if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi):
|
if exposure is None or not math.isfinite(rate) or (not (exposure > 0 and lo <= age < hi)):
|
||||||
return out
|
return out
|
||||||
n, mu = float(np.round(value * exposure)), rate * exposure
|
n, mu = (float(np.round(value * exposure)), rate * exposure)
|
||||||
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
|
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
|
||||||
tail, at = law.sf(n - 1), law.pmf(n)
|
tail, at = (law.sf(n - 1), law.pmf(n))
|
||||||
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
|
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
|
||||||
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
|
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
|
||||||
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95}
|
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95}
|
||||||
@@ -157,9 +134,7 @@ 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
|
value, age_months = (_number(value), _number(age_months))
|
||||||
age or the baseline's coverage is missing."""
|
|
||||||
value, age_months = _number(value), _number(age_months)
|
|
||||||
if value is None or age_months is None:
|
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"))
|
||||||
if baseline["kind"] == "count_rate":
|
if baseline["kind"] == "count_rate":
|
||||||
@@ -168,13 +143,10 @@ 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():
|
||||||
model, metric = models.get(name), metrics.get(scenario.metric)
|
model, metric = (models.get(name), metrics.get(scenario.metric))
|
||||||
if model is None or metric is None:
|
if model is None or metric is None:
|
||||||
continue
|
continue
|
||||||
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
|
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
|
||||||
|
|||||||
@@ -1,18 +1,6 @@
|
|||||||
"""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
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from models.tea.eeg import signals
|
from models.tea.eeg import signals
|
||||||
from models.tea.eeg.checks import window_qc
|
from models.tea.eeg.checks import window_qc
|
||||||
from models.tea.eeg.read import Recording
|
from models.tea.eeg.read import Recording
|
||||||
@@ -25,11 +13,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 +25,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,15 +39,13 @@ 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
|
referenced = np.asfortranarray(referenced * 1e-06 * 1000000.0)
|
||||||
# memory (the layout decides the order of float sums along time).
|
|
||||||
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
|
|
||||||
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
|
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
|
||||||
qc[gaps] = np.nan
|
qc[gaps] = np.nan
|
||||||
unclean = tuple(
|
unclean = tuple(
|
||||||
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
|
((float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean")
|
||||||
)
|
)
|
||||||
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
|
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-09, STEP_S)
|
||||||
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
|
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
|
||||||
|
|||||||
+12
-31
@@ -1,19 +1,7 @@
|
|||||||
"""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
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
|
|
||||||
import edfio
|
import edfio
|
||||||
import mne
|
import mne
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -24,21 +12,19 @@ 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
|
||||||
stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0]
|
stem = re.sub("^\\s*(EEG|ECG|EKG|EOG|EMG|POL)\\s+", "", text, flags=re.I).split("-")[0]
|
||||||
key = re.sub(r"[^A-Z0-9]", "", stem.strip().upper())
|
key = re.sub("[^A-Z0-9]", "", stem.strip().upper())
|
||||||
if key in CANONICAL:
|
if key in CANONICAL:
|
||||||
name = CANONICAL[key]
|
name = CANONICAL[key]
|
||||||
return RENAMED.get(name, name)
|
return RENAMED.get(name, name)
|
||||||
@@ -46,7 +32,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:
|
||||||
@@ -56,10 +41,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
|
||||||
|
|
||||||
@@ -71,17 +56,15 @@ 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]
|
||||||
|
|
||||||
|
|
||||||
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."""
|
|
||||||
if len(edf) < 256:
|
if len(edf) < 256:
|
||||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||||
try:
|
try:
|
||||||
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
||||||
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
|
except Exception as exc:
|
||||||
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
|
||||||
if not signals:
|
if not signals:
|
||||||
raise FileNotValid("the EDF declares zero signals")
|
raise FileNotValid("the EDF declares zero signals")
|
||||||
@@ -91,9 +74,9 @@ def _kept(edf: bytes) -> list[tuple[str, str]]:
|
|||||||
raise FileNotValid("no recognised channel")
|
raise FileNotValid("no recognised channel")
|
||||||
rates = [rate for _, _, rate in named]
|
rates = [rate for _, _, rate in named]
|
||||||
fs = max(set(rates), key=rates.count)
|
fs = max(set(rates), key=rates.count)
|
||||||
kept, seen = [], set()
|
kept, seen = ([], set())
|
||||||
for label, name, rate in named:
|
for label, name, rate in named:
|
||||||
if abs(rate - fs) <= 1e-6 and name not in seen:
|
if abs(rate - fs) <= 1e-06 and name not in seen:
|
||||||
seen.add(name)
|
seen.add(name)
|
||||||
kept.append((label, name))
|
kept.append((label, name))
|
||||||
return kept
|
return kept
|
||||||
@@ -104,17 +87,17 @@ 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)
|
||||||
raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name})
|
raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name})
|
||||||
names = [name for name in raw.ch_names if name in {n for _, n in kept}]
|
names = [name for name in raw.ch_names if name in {n for _, n in kept}]
|
||||||
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1e6
|
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1000000.0
|
||||||
start = raw.info.get("meas_date")
|
start = raw.info.get("meas_date")
|
||||||
born = (raw.info.get("subject_info") or {}).get("birthday")
|
born = (raw.info.get("subject_info") or {}).get("birthday")
|
||||||
notes = tuple(
|
notes = tuple(
|
||||||
(float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations
|
((float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations)
|
||||||
)
|
)
|
||||||
return Recording(
|
return Recording(
|
||||||
x=x,
|
x=x,
|
||||||
@@ -127,9 +110,7 @@ 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
|
if start is None or birthday is None or start == UNKNOWN_START or (birthday > start):
|
||||||
unknown-start placeholder, the birth is after the start or the age is over 18 years."""
|
|
||||||
if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
|
|
||||||
return None
|
return None
|
||||||
months = round((start - birthday).days / days_per_month, 1)
|
months = round((start - birthday).days / days_per_month, 1)
|
||||||
return months if months <= 216 else None
|
return months if months <= 216 else None
|
||||||
|
|||||||
@@ -1,17 +1,5 @@
|
|||||||
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
|
|
||||||
children of 16 to 36 months, recorded on 50 Hz mains.
|
|
||||||
|
|
||||||
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
|
||||||
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
|
||||||
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
|
||||||
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
|
|
||||||
from the valid studies.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from models import cluster
|
from models import cluster
|
||||||
from models.tea.eeg.analysis import analyze
|
from models.tea.eeg.analysis import analyze
|
||||||
from models.tea.eeg.curves import SCENARIOS
|
from models.tea.eeg.curves import SCENARIOS
|
||||||
@@ -22,13 +10,12 @@ AGES = (16.0, 36.0)
|
|||||||
|
|
||||||
|
|
||||||
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
|
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
|
||||||
"""(key, path, age in months) of each EDF with an age within `ages`."""
|
|
||||||
table = pd.read_csv(ages_table)
|
table = pd.read_csv(ages_table)
|
||||||
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
|
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
|
||||||
found = []
|
found = []
|
||||||
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
|
for path in sorted((p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf")):
|
||||||
age = round(float(years[path.name] * 12), 1) if path.name in years else None
|
age = round(float(years[path.name] * 12), 1) if path.name in years else None
|
||||||
if age is not None and age == age and ages[0] <= age <= ages[1]:
|
if age is not None and age == age and (ages[0] <= age <= ages[1]):
|
||||||
found.append((path, age))
|
found.append((path, age))
|
||||||
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||||
|
|
||||||
@@ -45,14 +32,10 @@ def _one(key: str, edf: bytes, age: float) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def measure(studies) -> list[dict]:
|
def measure(studies) -> list[dict]:
|
||||||
"""Each study's verdict and features, in listing order, each a task on the cluster
|
|
||||||
(models.cluster)."""
|
|
||||||
# each task carries its recording: workers see no local folder
|
|
||||||
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
|
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
|
||||||
|
|
||||||
|
|
||||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||||
"""Scenario -> its training table: the valid studies' features and `age_months`."""
|
|
||||||
usable = [s for s in measured if s["valid"] and s["error"] is None]
|
usable = [s for s in measured if s["valid"] and s["error"] is None]
|
||||||
return {
|
return {
|
||||||
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
|
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -76,29 +58,23 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
|
|||||||
f = np.fft.rfftfreq(len(run), 1 / fs)
|
f = np.fft.rfftfreq(len(run), 1 / fs)
|
||||||
power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2
|
power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2
|
||||||
peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0)
|
peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0)
|
||||||
around = ((f >= f0 - 6) & (f <= f0 - 2)) | ((f >= f0 + 2) & (f <= f0 + 6))
|
around = (f >= f0 - 6) & (f <= f0 - 2) | (f >= f0 + 2) & (f <= f0 + 6)
|
||||||
near = power[around].mean(axis=0)
|
near = power[around].mean(axis=0)
|
||||||
with np.errstate(divide="ignore", invalid="ignore"):
|
with np.errstate(divide="ignore", invalid="ignore"):
|
||||||
return 10 * np.log10(np.where(near > 0, peak / near, np.nan))
|
return 10 * np.log10(np.where(near > 0, peak / near, np.nan))
|
||||||
|
|
||||||
|
|
||||||
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]
|
||||||
total, count = None, 0
|
total, count = (None, 0)
|
||||||
for a in range(0, len(x) - n + 1, n):
|
for a in range(0, len(x) - n + 1, n):
|
||||||
segment = x[a : a + n]
|
segment = x[a : a + n]
|
||||||
if np.isfinite(segment).all():
|
if np.isfinite(segment).all():
|
||||||
@@ -115,7 +91,7 @@ def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
|
|||||||
found = []
|
found = []
|
||||||
for i in range(1, len(f) - 1):
|
for i in range(1, len(f) - 1):
|
||||||
p = prominence[i]
|
p = prominence[i]
|
||||||
if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or p < prominence[i + 1]:
|
if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or (p < prominence[i + 1]):
|
||||||
continue
|
continue
|
||||||
a = b = i
|
a = b = i
|
||||||
while a > 0 and prominence[a - 1] >= p - 3:
|
while a > 0 and prominence[a - 1] >= p - 3:
|
||||||
@@ -126,15 +102,13 @@ def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
|
|||||||
found.append((round(float(f[i]), 3), round(float(p), 1)))
|
found.append((round(float(f[i]), 3), round(float(p), 1)))
|
||||||
kept = []
|
kept = []
|
||||||
for hz, db_up in sorted(found, key=lambda line: -line[1]):
|
for hz, db_up in sorted(found, key=lambda line: -line[1]):
|
||||||
if all(abs(hz - other) > 0.5 for other, _ in kept):
|
if all((abs(hz - other) > 0.5 for other, _ in kept)):
|
||||||
kept.append((hz, db_up))
|
kept.append((hz, db_up))
|
||||||
return [hz for hz, _ in kept]
|
return [hz for hz, _ in kept]
|
||||||
|
|
||||||
|
|
||||||
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`,
|
band = (f >= lo) & (f <= hi if include_hi else f < hi)
|
||||||
without the bins within 1 Hz of a fixed line, rescaled to the band's full width."""
|
|
||||||
band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
|
|
||||||
clean = band.copy()
|
clean = band.copy()
|
||||||
for line in lines:
|
for line in lines:
|
||||||
clean &= np.abs(f - line) > 1.0
|
clean &= np.abs(f - line) > 1.0
|
||||||
@@ -144,19 +118,17 @@ 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:
|
||||||
return np.nan, np.nan, False
|
return (np.nan, np.nan, False)
|
||||||
line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1)
|
line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1)
|
||||||
residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable])))
|
residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable])))
|
||||||
fu = f[usable]
|
fu = f[usable]
|
||||||
band = (fu >= 3) & (fu <= 14)
|
band = (fu >= 3) & (fu <= 14)
|
||||||
if not band.any():
|
if not band.any():
|
||||||
return np.nan, np.nan, False
|
return (np.nan, np.nan, False)
|
||||||
i = int(np.argmax(residual[band]))
|
i = int(np.argmax(residual[band]))
|
||||||
prominence = float(residual[band][i])
|
prominence = float(residual[band][i])
|
||||||
found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1
|
found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1
|
||||||
return (float(fu[band][i]) if found else np.nan), prominence, bool(found)
|
return (float(fu[band][i]) if found else np.nan, prominence, bool(found))
|
||||||
|
|||||||
+44
-56
@@ -1,28 +1,7 @@
|
|||||||
"""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
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from models.tea.eeg import signals
|
from models.tea.eeg import signals
|
||||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||||
|
|
||||||
@@ -32,36 +11,52 @@ NOTE_WORDS = {
|
|||||||
"hyperventilation": ("hv", "hipervent", "hypervent"),
|
"hyperventilation": ("hv", "hipervent", "hypervent"),
|
||||||
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
|
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
|
||||||
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
|
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
|
||||||
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
|
"sleep": (
|
||||||
"n1", "n2", "n3"),
|
"sueno",
|
||||||
|
"dormido",
|
||||||
|
"sleep",
|
||||||
|
"somnol",
|
||||||
|
"husos",
|
||||||
|
"spindle",
|
||||||
|
"fase i",
|
||||||
|
"fase ii",
|
||||||
|
"n1",
|
||||||
|
"n2",
|
||||||
|
"n3",
|
||||||
|
),
|
||||||
"awake": ("despierta", "despierto", "arousal", "vigilia"),
|
"awake": ("despierta", "despierto", "arousal", "vigilia"),
|
||||||
"crying": ("llanto", "llora", "cry"),
|
"crying": ("llanto", "llora", "cry"),
|
||||||
"movement": ("movimiento", "movement", "artefacto de movimiento"),
|
"movement": ("movimiento", "movement", "artefacto de movimiento"),
|
||||||
"feeding": ("come", "alimenta", "biberon", "lactancia"),
|
"feeding": ("come", "alimenta", "biberon", "lactancia"),
|
||||||
} # fmt: skip
|
}
|
||||||
EXCLUDED = ("crying", "movement", "disconnection")
|
EXCLUDED = ("crying", "movement", "disconnection")
|
||||||
MASKED = (*EXCLUDED, "photic", "hyperventilation")
|
MASKED = (*EXCLUDED, "photic", "hyperventilation")
|
||||||
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
|
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
|
||||||
BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16),
|
BANDS = {
|
||||||
"beta": (16, 30), "high": (20, 40)} # fmt: skip
|
"delta": (0.5, 4),
|
||||||
|
"theta": (4, 8),
|
||||||
|
"alpha": (8, 13),
|
||||||
|
"sigma": (11, 16),
|
||||||
|
"beta": (16, 30),
|
||||||
|
"high": (20, 40),
|
||||||
|
}
|
||||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||||
CENTRAL = ("C3", "C4", "Cz")
|
CENTRAL = ("C3", "C4", "Cz")
|
||||||
FRONTAL = ("F3", "F4", "Fz")
|
FRONTAL = ("F3", "F4", "Fz")
|
||||||
|
|
||||||
|
|
||||||
def note_state(text: str) -> str | None:
|
def note_state(text: str) -> str | None:
|
||||||
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
|
kept = str(text or "").replace("ñ", "\x00").replace("Ñ", "\x01")
|
||||||
plain = "".join(
|
plain = "".join(
|
||||||
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
|
(c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn")
|
||||||
)
|
)
|
||||||
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
|
plain = plain.replace("\x00", "ñ").replace("\x01", "Ñ").lower().strip()
|
||||||
return next(
|
return next(
|
||||||
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
|
(state for state, words in NOTE_WORDS.items() if any((w in plain for w in words))), None
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
|
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):
|
||||||
@@ -76,7 +71,7 @@ def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, s
|
|||||||
if t1 - t0 >= 1:
|
if t1 - t0 >= 1:
|
||||||
found.append((t0, t1, state))
|
found.append((t0, t1, state))
|
||||||
found.sort(key=lambda piece: piece[0])
|
found.sort(key=lambda piece: piece[0])
|
||||||
full, cursor = [], 0.0
|
full, cursor = ([], 0.0)
|
||||||
for t0, t1, state in found:
|
for t0, t1, state in found:
|
||||||
if t0 - cursor >= 1:
|
if t0 - cursor >= 1:
|
||||||
full.append((cursor, t0, "unmarked"))
|
full.append((cursor, t0, "unmarked"))
|
||||||
@@ -89,20 +84,18 @@ 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))
|
||||||
if hi > lo:
|
if hi > lo:
|
||||||
overlap[state] = overlap.get(state, 0) + (hi - lo)
|
overlap[state] = overlap.get(state, 0) + (hi - lo)
|
||||||
if not overlap:
|
if not overlap:
|
||||||
return "unlabelled", False
|
return ("unlabelled", False)
|
||||||
dominant = max(overlap, key=overlap.get)
|
dominant = max(overlap, key=overlap.get)
|
||||||
return dominant, overlap[dominant] < 0.8 * (t1 - t0)
|
return (dominant, overlap[dominant] < 0.8 * (t1 - t0))
|
||||||
|
|
||||||
|
|
||||||
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,16 +104,15 @@ 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 = [
|
||||||
a
|
a
|
||||||
for a in range(0, len(x) - n + 1, step)
|
for a in range(0, len(x) - n + 1, step)
|
||||||
if np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any()
|
if np.isfinite(x[a : a + n]).all() and (not masked[a : a + n].any())
|
||||||
]
|
]
|
||||||
if not starts:
|
if not starts:
|
||||||
return [], {}
|
return ([], {})
|
||||||
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
|
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
|
||||||
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
|
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
|
||||||
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
|
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
|
||||||
@@ -128,7 +120,7 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
|
|||||||
posterior = [names.index(c) for c in POSTERIOR if c in names]
|
posterior = [names.index(c) for c in POSTERIOR if c in names]
|
||||||
delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
|
delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
|
||||||
features = {
|
features = {
|
||||||
"delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)),
|
"delta_beta": np.log10(np.clip(delta_beta, 1e-06, None)),
|
||||||
"sigma": np.median((band["sigma"] / total)[:, central], axis=1),
|
"sigma": np.median((band["sigma"] / total)[:, central], axis=1),
|
||||||
"muscle": np.median(
|
"muscle": np.median(
|
||||||
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
|
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
|
||||||
@@ -140,27 +132,25 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
|
|||||||
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts))
|
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts))
|
||||||
]
|
]
|
||||||
features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
|
features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
|
||||||
return starts, features
|
return (starts, features)
|
||||||
|
|
||||||
|
|
||||||
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:
|
||||||
continue
|
continue
|
||||||
if "slope" in ref and age_months and age_months > 0:
|
if "slope" in ref and age_months and (age_months > 0):
|
||||||
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
|
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
|
||||||
else:
|
else:
|
||||||
median = ref["median"]
|
median = ref["median"]
|
||||||
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9))
|
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-09))
|
||||||
weights.append(ref["weight"])
|
weights.append(ref["weight"])
|
||||||
w = np.array(weights, float)
|
w = np.array(weights, float)
|
||||||
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
|
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
|
||||||
|
|
||||||
|
|
||||||
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
|
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 +162,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
|
||||||
@@ -183,8 +172,8 @@ def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
|
|||||||
continue
|
continue
|
||||||
if j + 2 >= len(crossings):
|
if j + 2 >= len(crossings):
|
||||||
break
|
break
|
||||||
c1, c2 = crossings[j + 1], crossings[j + 2]
|
c1, c2 = (crossings[j + 1], crossings[j + 2])
|
||||||
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
|
negative, total = ((c1 - c0) / fs, (c2 - c0) / fs)
|
||||||
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
|
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
|
||||||
continue
|
continue
|
||||||
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
|
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
|
||||||
@@ -209,15 +198,14 @@ 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)
|
||||||
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
|
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
|
||||||
if label != "sleep":
|
if label != "sleep":
|
||||||
continue
|
continue
|
||||||
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
|
t0, t1 = (start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0)
|
||||||
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
|
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
|
||||||
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
|
coverage = min(overlap.sum() / max(t1 - t0, 1e-09), 1.0) if len(covered) else 0.0
|
||||||
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
|
out[k] = "N3" if round(coverage, 4) >= 0.2 else "N2"
|
||||||
return out
|
return out
|
||||||
|
|||||||
+26
-54
@@ -1,30 +1,6 @@
|
|||||||
"""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
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from models.tea.eeg import signals
|
from models.tea.eeg import signals
|
||||||
from models.tea.eeg.checks import NEIGHBOURS
|
from models.tea.eeg.checks import NEIGHBOURS
|
||||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||||
@@ -43,10 +19,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 +33,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)
|
||||||
@@ -65,7 +40,7 @@ def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
|
|||||||
taper = np.hanning(n)[:, None]
|
taper = np.hanning(n)[:, None]
|
||||||
kept = []
|
kept = []
|
||||||
for a in range(0, len(x) - n + 1, n):
|
for a in range(0, len(x) - n + 1, n):
|
||||||
t0, t1 = a / fs, a / fs + GATE_S
|
t0, t1 = (a / fs, a / fs + GATE_S)
|
||||||
state, mixed = window_note(t0, t1, intervals)
|
state, mixed = window_note(t0, t1, intervals)
|
||||||
segment = x[a : a + n]
|
segment = x[a : a + n]
|
||||||
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
|
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
|
||||||
@@ -75,53 +50,52 @@ def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
|
|||||||
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
||||||
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
||||||
muscle = float(high / max(low, 1e-12))
|
muscle = float(high / max(low, 1e-12))
|
||||||
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
|
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-09))
|
||||||
if not (muscle > 1.5 or frozen > 0.5):
|
if not (muscle > 1.5 or frozen > 0.5):
|
||||||
kept.append((round(t0, 2), round(t1, 2)))
|
kept.append((round(t0, 2), round(t1, 2)))
|
||||||
return kept
|
return kept
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
w = int(500 * fs / 1000)
|
w = int(500 * fs / 1000)
|
||||||
base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
|
base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
|
||||||
peak = float(y[i]) - base
|
peak = float(y[i]) - base
|
||||||
if peak == 0.0:
|
if peak == 0.0:
|
||||||
return np.nan, np.nan
|
return (np.nan, np.nan)
|
||||||
sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)
|
sign, half, reach = (np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000))
|
||||||
a, low = i, max(0, i - reach)
|
a, low = (i, max(0, i - reach))
|
||||||
while a > low and sign * (y[a] - base) >= half:
|
while a > low and sign * (y[a] - base) >= half:
|
||||||
a -= 1
|
a -= 1
|
||||||
b, high = i, min(n - 1, i + reach)
|
b, high = (i, min(n - 1, i + reach))
|
||||||
while b < high and sign * (y[b] - base) >= half:
|
while b < high and sign * (y[b] - base) >= half:
|
||||||
b += 1
|
b += 1
|
||||||
if b <= a:
|
if b <= a:
|
||||||
return np.nan, np.nan
|
return (np.nan, np.nan)
|
||||||
rise, fall = half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)
|
rise, fall = (half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs))
|
||||||
return float(min(rise, fall)), float((b - a) / fs * 1000.0)
|
return (float(min(rise, fall)), float((b - a) / fs * 1000.0))
|
||||||
|
|
||||||
|
|
||||||
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
|
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
|
||||||
y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel()
|
y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel()
|
||||||
if np.isfinite(y).sum() < fs * 2:
|
if np.isfinite(y).sum() < fs * 2:
|
||||||
return []
|
return []
|
||||||
slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y)
|
slope_mad, amplitude_mad = (_mad(np.diff(y) * fs), _mad(y))
|
||||||
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
|
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
|
||||||
return []
|
return []
|
||||||
v = np.abs(y)
|
v = np.abs(y)
|
||||||
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else []
|
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else []
|
||||||
after = int(100 * fs / 1000), int(500 * fs / 1000)
|
after = (int(100 * fs / 1000), int(500 * fs / 1000))
|
||||||
out = []
|
out = []
|
||||||
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
|
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
|
||||||
slope, width = _flanks(y, int(i), fs)
|
slope, width = _flanks(y, int(i), fs)
|
||||||
if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0):
|
if not (np.isfinite(slope) and np.isfinite(width) and (20.0 <= width <= 200.0)):
|
||||||
continue
|
continue
|
||||||
if slope < 6.0 * slope_mad:
|
if slope < 6.0 * slope_mad:
|
||||||
continue
|
continue
|
||||||
a, b = int(i) + after[0], min(int(i) + after[1], len(y))
|
a, b = (int(i) + after[0], min(int(i) + after[1], len(y)))
|
||||||
post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
|
post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
|
||||||
out.append(
|
out.append(
|
||||||
dict(
|
dict(
|
||||||
@@ -137,7 +111,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 +125,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 = []
|
||||||
@@ -161,10 +133,12 @@ def _merge(c: pd.DataFrame) -> pd.DataFrame:
|
|||||||
top = c.loc[part["size"].idxmax()]
|
top = c.loc[part["size"].idxmax()]
|
||||||
asleep = top.state in ASLEEP
|
asleep = top.state in ASLEEP
|
||||||
signs = dict(zip(part.channel, part.sign, strict=True))
|
signs = dict(zip(part.channel, part.sign, strict=True))
|
||||||
frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR)
|
frontal_only = top.channel in OCULAR and (not set(part.channel) & POSTERIOR)
|
||||||
opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT)
|
opposite = any(
|
||||||
vertex = asleep and top.channel in VERTEX and float(part.post.max()) > 3.0
|
(a in signs and b in signs and (signs[a] * signs[b] < 0) for a, b in LEFT_RIGHT)
|
||||||
posts = asleep and top.channel in POSTS and top.sign > 0 and top.width > 80.0
|
)
|
||||||
|
vertex = asleep and top.channel in VERTEX and (float(part.post.max()) > 3.0)
|
||||||
|
posts = asleep and top.channel in POSTS and (top.sign > 0) and (top.width > 80.0)
|
||||||
rows.append(
|
rows.append(
|
||||||
dict(
|
dict(
|
||||||
channel=top.channel,
|
channel=top.channel,
|
||||||
@@ -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,11 +163,10 @@ 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)
|
||||||
out[hit], open_ = label, open_ & ~hit
|
out[hit], open_ = (label, open_ & ~hit)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
gate = _gate(x, fs, intervals)
|
gate = _gate(x, fs, intervals)
|
||||||
@@ -202,7 +174,7 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
|||||||
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
|
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
|
||||||
for (t0, t1), state in zip(gate, middles, strict=True):
|
for (t0, t1), state in zip(gate, middles, strict=True):
|
||||||
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
|
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
|
||||||
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
|
sleep_minutes = float(sum((minutes.get(s, 0.0) for s in ("sleep",))))
|
||||||
counts = dict.fromkeys(channels, 0)
|
counts = dict.fromkeys(channels, 0)
|
||||||
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
|
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
|
||||||
if candidates and gate:
|
if candidates and gate:
|
||||||
@@ -227,6 +199,6 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
|||||||
zones = {}
|
zones = {}
|
||||||
for zone, members in ZONES.items():
|
for zone, members in ZONES.items():
|
||||||
present = [e for e in members if e in counts]
|
present = [e for e in members if e in counts]
|
||||||
total = sum(counts[e] for e in present)
|
total = sum((counts[e] for e in present))
|
||||||
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
|
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
|
||||||
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
|
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
|
||||||
|
|||||||
+10
-34
@@ -1,25 +1,6 @@
|
|||||||
"""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
|
||||||
from scipy.signal import hilbert, welch
|
from scipy.signal import hilbert, welch
|
||||||
|
|
||||||
from models.tea.eeg import signals
|
from models.tea.eeg import signals
|
||||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||||
|
|
||||||
@@ -39,9 +20,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]:
|
||||||
@@ -52,7 +33,7 @@ def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
|||||||
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
|
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
|
||||||
)
|
)
|
||||||
envelope[~np.isfinite(y)] = np.nan
|
envelope[~np.isfinite(y)] = np.nan
|
||||||
return y, envelope
|
return (y, envelope)
|
||||||
|
|
||||||
|
|
||||||
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
|
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
|
||||||
@@ -73,13 +54,12 @@ 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))
|
||||||
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
|
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
|
||||||
inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
|
inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
|
||||||
flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
|
flanks = (f >= 5) & (f < SIGMA[0]) | (f > SIGMA[1]) & (f <= 30)
|
||||||
if not inside.any() or not flanks.any():
|
if not inside.any() or not flanks.any():
|
||||||
return False
|
return False
|
||||||
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
|
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
|
||||||
@@ -93,8 +73,7 @@ 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):
|
||||||
if s == stage:
|
if s == stage:
|
||||||
@@ -112,7 +91,7 @@ def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
|
|||||||
values = in_stage[np.isfinite(in_stage)]
|
values = in_stage[np.isfinite(in_stage)]
|
||||||
if len(values) < fs * 30:
|
if len(values) < fs * 30:
|
||||||
continue
|
continue
|
||||||
median = float(np.median(values)) or 1e-9
|
median = float(np.median(values)) or 1e-09
|
||||||
core = max(float(np.percentile(values, 95)), 3 * median)
|
core = max(float(np.percentile(values, 95)), 3 * median)
|
||||||
extent = max(float(np.percentile(values, 70)), 1.6 * median)
|
extent = max(float(np.percentile(values, 70)), 1.6 * median)
|
||||||
finite = np.isfinite(in_stage)
|
finite = np.isfinite(in_stage)
|
||||||
@@ -123,20 +102,19 @@ 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)
|
||||||
counts = {}
|
counts = {}
|
||||||
for _, _, channel in found.events:
|
for _, _, channel in found.events:
|
||||||
counts[channel] = counts.get(channel, 0) + 1
|
counts[channel] = counts.get(channel, 0) + 1
|
||||||
for zone, electrodes in ZONES.items():
|
for zone, electrodes in ZONES.items():
|
||||||
searched = [e for e in electrodes if e in found.channels]
|
searched = [e for e in electrodes if e in found.channels]
|
||||||
if searched:
|
if searched:
|
||||||
total = sum(counts.get(e, 0) for e in searched)
|
total = sum((counts.get(e, 0) for e in searched))
|
||||||
zones[zone] = total / (found.minutes * len(searched))
|
zones[zone] = total / (found.minutes * len(searched))
|
||||||
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
|
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
|
||||||
return round(per_channel, 3), zones
|
return (round(per_channel, 3), zones)
|
||||||
|
|
||||||
|
|
||||||
def _episodes(events) -> list[list[float]]:
|
def _episodes(events) -> list[list[float]]:
|
||||||
@@ -155,8 +133,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)
|
||||||
@@ -172,7 +148,7 @@ def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str
|
|||||||
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
|
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
|
||||||
peaks = np.full((len(episodes), len(use)), np.nan)
|
peaks = np.full((len(episodes), len(use)), np.nan)
|
||||||
for k, (t0, t1) in enumerate(episodes):
|
for k, (t0, t1) in enumerate(episodes):
|
||||||
a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))
|
a, b = (max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs)))
|
||||||
if b - a >= 3:
|
if b - a >= 3:
|
||||||
peaks[k] = np.nanmax(envelope[a:b], axis=0)
|
peaks[k] = np.nanmax(envelope[a:b], axis=0)
|
||||||
for j, name in enumerate(use):
|
for j, name in enumerate(use):
|
||||||
|
|||||||
+101
-68
@@ -1,16 +1,8 @@
|
|||||||
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
|
|
||||||
(models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the
|
|
||||||
children whose diagnosis ruled TEA out, persistance.eeg.ruled_out) and scoring every
|
|
||||||
analysed EEG against the child's age. The math is the old platform's, proved on its HK1K
|
|
||||||
cohort by models/tests/test_eeg.py."""
|
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import mlflow.pyfunc
|
import mlflow.pyfunc
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from core.tea import ados2
|
from core.tea import ados2
|
||||||
from core.tea import association as relation
|
from core.tea import association as relation
|
||||||
from models import cluster
|
from models import cluster
|
||||||
@@ -20,32 +12,31 @@ from models.tea.eeg import analysis, curves, reference
|
|||||||
from persistance import eeg, registry, silver
|
from persistance import eeg, registry, silver
|
||||||
|
|
||||||
CURVES = curves.SCENARIOS
|
CURVES = curves.SCENARIOS
|
||||||
ASSOCIATION = "eeg-ados2" # trained on the champion curves' z: after they are promoted
|
ASSOCIATION = "eeg-ados2"
|
||||||
MODELS = [*CURVES, ASSOCIATION]
|
MODELS = [*CURVES, ASSOCIATION]
|
||||||
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
|
GOLD = "tea_eeg_metrics"
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||||
feature = (params or {}).get("feature", "value")
|
feature = (params or {}).get("feature", "value")
|
||||||
rows = model_input.to_dict("records")
|
rows = model_input.to_dict("records")
|
||||||
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
|
return pd.DataFrame(
|
||||||
r.get("age_months"), r.get("exposure"))
|
[
|
||||||
for r in rows]) # fmt: skip
|
curves.score(
|
||||||
|
self.baseline[feature], r.get("value"), r.get("age_months"), r.get("exposure")
|
||||||
|
)
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def analyze() -> int:
|
def analyze() -> int:
|
||||||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
|
||||||
pending = eeg.pending()
|
pending = eeg.pending()
|
||||||
done = cluster.run(
|
done = cluster.run(analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending))
|
||||||
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
|
|
||||||
) # one task per EEG
|
|
||||||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||||||
eeg.save_analyses(found)
|
eeg.save_analyses(found)
|
||||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||||
@@ -54,13 +45,11 @@ def analyze() -> int:
|
|||||||
|
|
||||||
@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)
|
||||||
|
|
||||||
def scored(self) -> list[str]:
|
def scored(self) -> list[str]:
|
||||||
return list(MODELS) # the curves, then the association on their scores
|
return list(MODELS)
|
||||||
|
|
||||||
|
|
||||||
JOBS = Jobs()
|
JOBS = Jobs()
|
||||||
@@ -77,23 +66,25 @@ def train(name: str, as_of: date | None = None) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def _train_curve(name: str, as_of: date | None = None) -> int:
|
def _train_curve(name: str, as_of: date | None = None) -> int:
|
||||||
"""A new version of one age curve, trained on the site's reference group as known on
|
|
||||||
`as_of` (today by default), with its two reports: the group it learned from, and its
|
|
||||||
centile curves."""
|
|
||||||
day = as_of or date.today()
|
day = as_of or date.today()
|
||||||
measured = eeg.ruled_out(day)
|
measured = eeg.ruled_out(day)
|
||||||
if not measured:
|
if not measured:
|
||||||
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
|
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
|
||||||
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
|
digest = hashlib.sha256("\n".join((m["key"] for m in measured)).encode()).hexdigest()
|
||||||
table = reference.tables(measured)[name]
|
table = reference.tables(measured)[name]
|
||||||
baseline = curves.train(table, name)
|
baseline = curves.train(table, name)
|
||||||
ages = [m["age_months"] for m in measured]
|
ages = [m["age_months"] for m in measured]
|
||||||
technical = {
|
technical = {
|
||||||
"model": name, "method": "age curves (weighted centiles on log age)",
|
"model": name,
|
||||||
"cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day),
|
"method": "age curves (weighted centiles on log age)",
|
||||||
"studies": len(measured), "valid_studies": len(measured),
|
"cohort": "site: children with TEA ruled out",
|
||||||
"ages_months": [min(ages), max(ages)], "features": sorted(baseline),
|
"cohort_sha256": digest,
|
||||||
} # fmt: skip
|
"as_of": str(day),
|
||||||
|
"studies": len(measured),
|
||||||
|
"valid_studies": len(measured),
|
||||||
|
"ages_months": [min(ages), max(ages)],
|
||||||
|
"features": sorted(baseline),
|
||||||
|
}
|
||||||
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
||||||
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
|
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
|
||||||
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
|
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
|
||||||
@@ -108,14 +99,12 @@ def score(name: str) -> int | None:
|
|||||||
|
|
||||||
|
|
||||||
def _score_curve(name: str) -> int | None:
|
def _score_curve(name: str) -> int | None:
|
||||||
"""The champion curve's scores of every analysed EEG: the metric's value, and each
|
|
||||||
electrode and zone it measures; None without a champion."""
|
|
||||||
found = registry.champion(registered(name))
|
found = registry.champion(registered(name))
|
||||||
if found is None:
|
if found is None:
|
||||||
return None
|
return None
|
||||||
version, model = found
|
version, model = found
|
||||||
baseline = model.unwrap_python_model().baseline
|
baseline = model.unwrap_python_model().baseline
|
||||||
scenario, label = CURVES[name], f"{registered(name)}/{version}"
|
scenario, label = (CURVES[name], f"{registered(name)}/{version}")
|
||||||
rows = []
|
rows = []
|
||||||
for one in eeg.analysed():
|
for one in eeg.analysed():
|
||||||
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
|
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
|
||||||
@@ -132,16 +121,23 @@ def _score_curve(name: str) -> int | None:
|
|||||||
if feature not in baseline:
|
if feature not in baseline:
|
||||||
continue
|
continue
|
||||||
s = curves.score(baseline[feature], value, one["age_months"], exposure)
|
s = curves.score(baseline[feature], value, one["age_months"], exposure)
|
||||||
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
|
rows.append(
|
||||||
"scenario": name, "model": label, "metric": scenario.metric,
|
{
|
||||||
"part": part, "site": site or None, **s}) # fmt: skip
|
"key": f"{one['edf']}|{name}|{part}|{site}",
|
||||||
|
"edf": one["edf"],
|
||||||
|
"scenario": name,
|
||||||
|
"model": label,
|
||||||
|
"metric": scenario.metric,
|
||||||
|
"part": part,
|
||||||
|
"site": site or None,
|
||||||
|
**s,
|
||||||
|
}
|
||||||
|
)
|
||||||
eeg.save_scores(name, rows)
|
eeg.save_scores(name, rows)
|
||||||
return version
|
return version
|
||||||
|
|
||||||
|
|
||||||
class Association(mlflow.pyfunc.PythonModel):
|
class Association(mlflow.pyfunc.PythonModel):
|
||||||
"""The fitted association as MLflow serves it: a cohort in, each child's probabilities."""
|
|
||||||
|
|
||||||
def __init__(self, fitted: dict):
|
def __init__(self, fitted: dict):
|
||||||
self.fitted = fitted
|
self.fitted = fitted
|
||||||
|
|
||||||
@@ -150,9 +146,6 @@ class Association(mlflow.pyfunc.PythonModel):
|
|||||||
|
|
||||||
|
|
||||||
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
|
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||||
"""(fit, scored): every valid EEG of a child with an ADOS-2 (known by `as_of`), her age,
|
|
||||||
module, items, CSS and the z of each biomarker; fitted on each child's first EEG with
|
|
||||||
any z, every EEG scored."""
|
|
||||||
day = str(as_of) if as_of else None
|
day = str(as_of) if as_of else None
|
||||||
rows = []
|
rows = []
|
||||||
for r in eeg.association_inputs(relation.BIOMARKERS):
|
for r in eeg.association_inputs(relation.BIOMARKERS):
|
||||||
@@ -164,22 +157,27 @@ def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.Data
|
|||||||
if evaluated and r["birth_date"]:
|
if evaluated and r["birth_date"]:
|
||||||
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
|
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
|
||||||
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
|
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
|
||||||
rows.append({"key": r["edf"], "person": r["person_id"], "age_months": r["age_months"],
|
rows.append(
|
||||||
"module": a.get("module"), "css": css,
|
{
|
||||||
|
"key": r["edf"],
|
||||||
|
"person": r["person_id"],
|
||||||
|
"age_months": r["age_months"],
|
||||||
|
"module": a.get("module"),
|
||||||
|
"css": css,
|
||||||
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
|
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
|
||||||
**{k: v for k, v in r.items() if k.startswith("z_")}}) # fmt: skip
|
**{k: v for k, v in r.items() if k.startswith("z_")},
|
||||||
|
}
|
||||||
|
)
|
||||||
scored = pd.DataFrame(rows)
|
scored = pd.DataFrame(rows)
|
||||||
if scored.empty:
|
if scored.empty:
|
||||||
return scored, scored
|
return (scored, scored)
|
||||||
predictors = [c for c in scored.columns if c.startswith("z_")]
|
predictors = [c for c in scored.columns if c.startswith("z_")]
|
||||||
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
|
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
|
||||||
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
|
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
|
||||||
return fit.drop(columns=["person"]), scored.drop(columns=["person"])
|
return (fit.drop(columns=["person"]), scored.drop(columns=["person"]))
|
||||||
|
|
||||||
|
|
||||||
def _train_association(as_of: date | None = None) -> int:
|
def _train_association(as_of: date | None = None) -> int:
|
||||||
"""A new version of the association, fitted on the site's children, with its reports:
|
|
||||||
the cohort and pairs it estimated, and the pairs themselves."""
|
|
||||||
fit, _ = association_cohort(as_of)
|
fit, _ = association_cohort(as_of)
|
||||||
if fit.empty:
|
if fit.empty:
|
||||||
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
|
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
|
||||||
@@ -187,15 +185,23 @@ def _train_association(as_of: date | None = None) -> int:
|
|||||||
pairs = association.associations(fitted)
|
pairs = association.associations(fitted)
|
||||||
estimated = [p for p in pairs if p["odds_ratio"] is not None]
|
estimated = [p for p in pairs if p["odds_ratio"] is not None]
|
||||||
technical = {
|
technical = {
|
||||||
"model": ASSOCIATION, "method": "Firth logistic (items) / cumulative logit (CSS), "
|
"model": ASSOCIATION,
|
||||||
"adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
|
"method": "Firth logistic (items) / cumulative logit (CSS), adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
|
||||||
"cohort": "site: children with an ADOS-2 and a valid EEG",
|
"cohort": "site: children with an ADOS-2 and a valid EEG",
|
||||||
"as_of": str(as_of or date.today()),
|
"as_of": str(as_of or date.today()),
|
||||||
"children": int(fitted["n"]), "level": fitted["level"], "pairs": len(pairs),
|
"children": int(fitted["n"]),
|
||||||
"estimated": len(estimated), "clear": sum(1 for p in estimated if (p["q"] or 1) < 0.05),
|
"level": fitted["level"],
|
||||||
} # fmt: skip
|
"pairs": len(pairs),
|
||||||
interpretability = {"model": ASSOCIATION, "kind": "associations", "level": fitted["level"],
|
"estimated": len(estimated),
|
||||||
"children": int(fitted["n"]), "rows": pairs} # fmt: skip
|
"clear": sum((1 for p in estimated if (p["q"] or 1) < 0.05)),
|
||||||
|
}
|
||||||
|
interpretability = {
|
||||||
|
"model": ASSOCIATION,
|
||||||
|
"kind": "associations",
|
||||||
|
"level": fitted["level"],
|
||||||
|
"children": int(fitted["n"]),
|
||||||
|
"rows": pairs,
|
||||||
|
}
|
||||||
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
|
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
|
||||||
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
|
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
|
||||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||||
@@ -203,7 +209,6 @@ def _train_association(as_of: date | None = None) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def _score_association() -> int | None:
|
def _score_association() -> int | None:
|
||||||
"""The champion association's probabilities for every scored EEG; None without one."""
|
|
||||||
found = registry.champion(registered(ASSOCIATION))
|
found = registry.champion(registered(ASSOCIATION))
|
||||||
if found is None:
|
if found is None:
|
||||||
return None
|
return None
|
||||||
@@ -211,14 +216,35 @@ def _score_association() -> int | None:
|
|||||||
fitted = model.unwrap_python_model().fitted
|
fitted = model.unwrap_python_model().fitted
|
||||||
label = f"{registered(ASSOCIATION)}/{version}"
|
label = f"{registered(ASSOCIATION)}/{version}"
|
||||||
_, scored = association_cohort()
|
_, scored = association_cohort()
|
||||||
kept = ("biomarker", "zone", "kind", "outcome_code", "event", "n", "odds_ratio", "ci_low",
|
kept = (
|
||||||
"ci_high", "p", "q", "sens_odds_ratio", "same_direction", "reason") # fmt: skip
|
"biomarker",
|
||||||
pairs = [{**{k: p[k] for k in kept}, "model": label,
|
"zone",
|
||||||
|
"kind",
|
||||||
|
"outcome_code",
|
||||||
|
"event",
|
||||||
|
"n",
|
||||||
|
"odds_ratio",
|
||||||
|
"ci_low",
|
||||||
|
"ci_high",
|
||||||
|
"p",
|
||||||
|
"q",
|
||||||
|
"sens_odds_ratio",
|
||||||
|
"same_direction",
|
||||||
|
"reason",
|
||||||
|
)
|
||||||
|
pairs = [
|
||||||
|
{
|
||||||
|
**{k: p[k] for k in kept},
|
||||||
|
"model": label,
|
||||||
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
|
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
|
||||||
"metric": relation.BIOMARKERS[p["biomarker"]], "principal": p["model"],
|
"metric": relation.BIOMARKERS[p["biomarker"]],
|
||||||
"sensitivity": p["sens_model"]}
|
"principal": p["model"],
|
||||||
for p in association.associations(fitted) if p["odds_ratio"] is not None] # fmt: skip
|
"sensitivity": p["sens_model"],
|
||||||
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, or the CSS
|
}
|
||||||
|
for p in association.associations(fitted)
|
||||||
|
if p["odds_ratio"] is not None
|
||||||
|
]
|
||||||
|
observed: dict[str, dict] = {}
|
||||||
if not scored.empty:
|
if not scored.empty:
|
||||||
keys = scored["key"].tolist()
|
keys = scored["key"].tolist()
|
||||||
for n in relation.ITEMS:
|
for n in relation.ITEMS:
|
||||||
@@ -230,7 +256,14 @@ def _score_association() -> int | None:
|
|||||||
seen = observed.get(one["outcome_code"], {}).get(one["key"])
|
seen = observed.get(one["outcome_code"], {}).get(one["key"])
|
||||||
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
|
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
|
||||||
shown = None if seen is None or seen != seen else float(seen)
|
shown = None if seen is None or seen != seen else float(seen)
|
||||||
scores.append({**one, "edf": one["key"], "model": label, "key": f"{one['key']}|{pair}",
|
scores.append(
|
||||||
"observed": shown}) # fmt: skip
|
{
|
||||||
|
**one,
|
||||||
|
"edf": one["key"],
|
||||||
|
"model": label,
|
||||||
|
"key": f"{one['key']}|{pair}",
|
||||||
|
"observed": shown,
|
||||||
|
}
|
||||||
|
)
|
||||||
eeg.save_association(label, pairs, scores)
|
eeg.save_association(label, pairs, scores)
|
||||||
return version
|
return version
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
# Where a Dask cluster runs the long batches (testing here); the product runs without it.
|
|
||||||
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
|
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
"""The CaCu models compute what the current ones compute: fed the timelines the current
|
|
||||||
platform built for its cohorts (the reference fixtures, in its codes), each rewritten model
|
|
||||||
gives the current model's predictions.
|
|
||||||
|
|
||||||
Fixed on purpose, so left out of the comparison:
|
|
||||||
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
|
|
||||||
(1970-01-01 for everyone); the rewrite returns the index sample's date.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from models.cacu.specs import MODELS
|
|
||||||
|
|
||||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
|
||||||
RTOL = 1e-6 # as captured (models.json)
|
|
||||||
# The current platform's cohort cutoff, where the logistic model's follow-up ends.
|
|
||||||
REFERENCE_CUTOFF = "2026-11-23"
|
|
||||||
|
|
||||||
TYPES = {
|
|
||||||
"citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv",
|
|
||||||
"vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy",
|
|
||||||
"orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history",
|
|
||||||
"diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth",
|
|
||||||
"defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order",
|
|
||||||
} # fmt: skip
|
|
||||||
CODES = {
|
|
||||||
"bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"},
|
|
||||||
"biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"},
|
|
||||||
"hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"},
|
|
||||||
"cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"},
|
|
||||||
}
|
|
||||||
COHORTS = {
|
|
||||||
"cacu_cohort_surveillance": "cohorte_vigilancia",
|
|
||||||
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def timelines(cohort: str) -> pd.DataFrame:
|
|
||||||
"""A reference cohort's timelines in the platform's names and codes."""
|
|
||||||
found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet")
|
|
||||||
found = found.rename(columns={
|
|
||||||
"pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type",
|
|
||||||
"valor_codigo": "value_code", "valor_numerico": "value_num",
|
|
||||||
"fuente_tabla": "source_table", "fuente_id": "source_id",
|
|
||||||
}) # fmt: skip
|
|
||||||
found["type"] = found["type"].map(TYPES)
|
|
||||||
for kind, codes in CODES.items():
|
|
||||||
rows = found["type"] == kind
|
|
||||||
found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
|
|
||||||
"cin2_logistic"]) # fmt: skip
|
|
||||||
def test_predictions_match_the_current_models(name):
|
|
||||||
spec = MODELS[name]
|
|
||||||
events = timelines(COHORTS[spec.cohort])
|
|
||||||
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
|
|
||||||
model, metrics, _ = spec.train(events, *args)
|
|
||||||
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
|
||||||
current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"]
|
|
||||||
assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"]
|
|
||||||
|
|
||||||
found = spec.predict(model, events)
|
|
||||||
both = found.merge(
|
|
||||||
reference,
|
|
||||||
left_on=["person_id", "horizon_years"],
|
|
||||||
right_on=["pac_id", "horizonte_anios"],
|
|
||||||
how="outer",
|
|
||||||
indicator=True,
|
|
||||||
)
|
|
||||||
assert (both["_merge"] == "both").all(), "the same patients and horizons are scored"
|
|
||||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
|
||||||
("ci_high", "ic_alto")]: # fmt: skip
|
|
||||||
if theirs in both:
|
|
||||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
|
|
||||||
if spec.method != "logistic regression":
|
|
||||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
|
||||||
|
|
||||||
|
|
||||||
def test_survival_matches_the_current_model_with_its_index_fixed():
|
|
||||||
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
|
|
||||||
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
|
|
||||||
that fixed); out: no birth date, a death by the biopsy."""
|
|
||||||
spec = MODELS["survival"]
|
|
||||||
events = timelines("cohorte_total").drop(columns="index_date")
|
|
||||||
events["date"] = pd.to_datetime(events["date"])
|
|
||||||
events["record_number"] = "CACU" + events["person_id"].astype(str).str.zfill(4)
|
|
||||||
cases = events[(events["type"] == "biopsy") & events["value_code"].isin(["CIS", "carcinoma"])]
|
|
||||||
index = cases.groupby("person_id")["date"].min().rename("index_date")
|
|
||||||
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
|
|
||||||
born = set(events.loc[events["type"] == "birth", "person_id"])
|
|
||||||
died = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
|
||||||
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
|
|
||||||
events = events.merge(index, left_on="person_id", right_index=True)
|
|
||||||
|
|
||||||
model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
|
||||||
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
|
||||||
for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m",
|
|
||||||
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
|
|
||||||
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
|
|
||||||
found = spec.predict(model, events)
|
|
||||||
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
|
||||||
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
|
||||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
|
||||||
assert len(both) == len(reference) == len(found)
|
|
||||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
|
||||||
("ci_high", "ic_alto")]: # fmt: skip
|
|
||||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch):
|
|
||||||
"""A site with no colposcopies has nobody in the post-colposcopy cohort: training that
|
|
||||||
model says so (and the train job goes on with the others) instead of failing inside it."""
|
|
||||||
from models import jobs
|
|
||||||
from models.cacu.jobs import JOBS
|
|
||||||
|
|
||||||
monkeypatch.setattr(jobs.gold, "timelines", lambda *a: pd.DataFrame())
|
|
||||||
with pytest.raises(jobs.EmptyCohort, match="cacu_cohort_post_colposcopy"):
|
|
||||||
JOBS.train("cin2_pim_post_colposcopy")
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
"""CaMa's models give the current platform's predictions on its own cohort (the reference
|
|
||||||
fixtures), read in the platform's timeline shape."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
from models.cama.specs import MODELS
|
|
||||||
|
|
||||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama"
|
|
||||||
TRAINED_ON = "2026-11-24" # the day the reference was trained: its follow-up ends there
|
|
||||||
TYPES = {"nacimiento": "birth", "defuncion": "death", "biopsia": "biopsy"}
|
|
||||||
CODES = {"CARCINOMA_INVASOR": "invasive", "CARCINOMA_IN_SITU": "in_situ", "BENIGNO": "benign"}
|
|
||||||
|
|
||||||
|
|
||||||
def _timelines() -> pd.DataFrame:
|
|
||||||
"""The reference cohort's members (first invasive biopsy report in the window) with their
|
|
||||||
events, as gold.cama_events gives them."""
|
|
||||||
old = pd.read_parquet(REFERENCE / "cohorts" / "cama" / "cohorte_total" / "dbt" / "1.parquet")
|
|
||||||
old = old[old["tipo"].isin(TYPES)]
|
|
||||||
events = pd.DataFrame({
|
|
||||||
"person_id": old["pac_id"].astype(str), "date": pd.to_datetime(old["fecha"]),
|
|
||||||
"type": old["tipo"].map(TYPES), "value_code": old["valor_codigo"].map(CODES),
|
|
||||||
"value_num": old["valor_numerico"], "source_table": old["fuente_tabla"],
|
|
||||||
"source_id": old["fuente_id"],
|
|
||||||
"record_number": "CAMA" + old["pac_id"].astype(str).str.zfill(4),
|
|
||||||
}) # fmt: skip
|
|
||||||
invasive = events[(events["type"] == "biopsy") & (events["value_code"] == "invasive")]
|
|
||||||
index = invasive.groupby("person_id")["date"].min().rename("index_date")
|
|
||||||
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
|
|
||||||
return events.merge(index, left_on="person_id", right_index=True)
|
|
||||||
|
|
||||||
|
|
||||||
def test_survival_matches_the_current_model():
|
|
||||||
spec = MODELS["survival"]
|
|
||||||
events = _timelines()
|
|
||||||
model, metrics, _ = spec.train(events, pd.Timestamp(TRAINED_ON).date())
|
|
||||||
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
|
||||||
for name in ("n_train", "n_test", "stack_w_lr_6m", "stack_w_lr_12m", "stack_w_lr_18m"):
|
|
||||||
assert metrics[name] == current["metrics"][name], name
|
|
||||||
ours = spec.predict(model, events)
|
|
||||||
ref = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
|
||||||
ref = ref.assign(person_id=ref["pac_id"].astype(str), horizon_years=ref["horizonte_anios"])
|
|
||||||
both = ours.merge(ref, on=["person_id", "horizon_years"], validate="1:1")
|
|
||||||
assert len(both) == len(ref) == len(ours)
|
|
||||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
|
||||||
np.testing.assert_allclose(both["probability"], both["probabilidad"], rtol=1e-6)
|
|
||||||
@@ -1,342 +0,0 @@
|
|||||||
"""The rewritten TEA EEG analysis computes what the current one computes: for every hospital
|
|
||||||
EEG with an EDF, the same verdict, checks, metric values and per-electrode / per-zone values
|
|
||||||
(the reference tables, in the current platform's codes); and age baselines trained on our own
|
|
||||||
features of the HK1K reference cohort score each EEG as the current registered baselines did
|
|
||||||
(z, outside, p5, median, p95 of each metric, z of each electrode and zone).
|
|
||||||
|
|
||||||
Tolerance: RTOL = 1e-9 relative (absolute below 1). Values are compared after the reference's
|
|
||||||
own storage (floats as captured); counts, texts, flags and levels exactly. The report at the
|
|
||||||
end of each test says how many compared fields are bit-identical.
|
|
||||||
|
|
||||||
Needs the hospital database (`~/isssteleon-data/hospital_tea.db`), and for the curves the
|
|
||||||
Helsinki EDFs (`/mnt/drive/eeg-helsinki`) unless their features are cached
|
|
||||||
(`~/isssteleon-data/cache/eeg_hk1k_features.json`; `EEG_REBUILD_REFERENCE=1` measures the 223
|
|
||||||
studies again: 10-20 min on 4 workers). The 78 hospital EEGs take about 40 s on 4 workers.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
from concurrent.futures import ProcessPoolExecutor
|
|
||||||
from multiprocessing import get_context
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
pytest.importorskip("mne")
|
|
||||||
pytest.importorskip("edfio")
|
|
||||||
|
|
||||||
from models.tea.eeg import curves, reference # noqa: E402
|
|
||||||
from models.tea.eeg.analysis import analyze # noqa: E402
|
|
||||||
|
|
||||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "tea"
|
|
||||||
DATA = Path.home() / "isssteleon-data"
|
|
||||||
HOSPITAL = DATA / "hospital_tea.db"
|
|
||||||
HELSINKI = Path("/mnt/drive/eeg-helsinki")
|
|
||||||
CACHE = DATA / "cache" / "eeg_hk1k_features.json"
|
|
||||||
OLD_FEATURES = DATA / "specs" / "eeg" / "hk1k_features.json" # only to check our own features
|
|
||||||
RTOL = 1e-9
|
|
||||||
WORKERS = 4
|
|
||||||
|
|
||||||
pytestmark = pytest.mark.skipif(not HOSPITAL.exists(), reason="no hospital database")
|
|
||||||
|
|
||||||
CODES = {
|
|
||||||
"RITMO_POSTERIOR": "posterior_rhythm",
|
|
||||||
"HUSOS_SUENO_N2": "spindles_n2",
|
|
||||||
"HUSOS_SUENO_N3": "spindles_n3",
|
|
||||||
"PICOS_PAROXISTICOS": "paroxysmal_spikes",
|
|
||||||
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient",
|
|
||||||
}
|
|
||||||
LEVELS = {
|
|
||||||
"completo": "complete",
|
|
||||||
"sin_referencia_auricular": "no_ear_reference",
|
|
||||||
"parcial": "partial",
|
|
||||||
"no_analizable": "not_analyzable",
|
|
||||||
}
|
|
||||||
ZONES = {
|
|
||||||
"frontal_izq": "frontal_left",
|
|
||||||
"frontal_der": "frontal_right",
|
|
||||||
"frontal_media": "frontal_midline",
|
|
||||||
"temporal_izq": "temporal_left",
|
|
||||||
"temporal_der": "temporal_right",
|
|
||||||
}
|
|
||||||
# The current platform's features of the HK1K studies, by our scenario's feature names.
|
|
||||||
OLD_SCENARIOS = {
|
|
||||||
"eeg-posterior-rhythm": ("posterior_rhythm|", {"value": "posterior_rhythm_hz"}),
|
|
||||||
"eeg-gradient": ("gradient|", {"value": "gradient_delta_sueno"}),
|
|
||||||
"eeg-spikes": (
|
|
||||||
"spikes|",
|
|
||||||
{
|
|
||||||
"value": "spike_rate_nrem",
|
|
||||||
"minutes": "spike_minutes_nrem",
|
|
||||||
"electrode_": "spike_density_nrem_",
|
|
||||||
"zone_": "spike_zone_rate_nrem_",
|
|
||||||
},
|
|
||||||
),
|
|
||||||
**{
|
|
||||||
f"eeg-spindles-{s}": (
|
|
||||||
f"spindles|{s.upper()}",
|
|
||||||
{"value": "spindle_density_per_min_channel", "zone_": "spindle_zone_"},
|
|
||||||
)
|
|
||||||
for s in ("n2", "n3")
|
|
||||||
},
|
|
||||||
**{
|
|
||||||
f"eeg-spindle-topography-{s}": (
|
|
||||||
f"spindle_topography|{s.upper()}",
|
|
||||||
{"electrode_": "topo_enh_"},
|
|
||||||
)
|
|
||||||
for s in ("n2", "n3")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class Tally:
|
|
||||||
"""Compared fields: bit-identical, within RTOL, and the mismatches."""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.exact, self.close, self.wrong = 0, 0, []
|
|
||||||
|
|
||||||
def __call__(self, where, ours, theirs):
|
|
||||||
if isinstance(ours, bool):
|
|
||||||
ours = int(ours)
|
|
||||||
if ours is None or theirs is None or isinstance(ours, str) or isinstance(theirs, str):
|
|
||||||
ok = ours == theirs
|
|
||||||
self.exact += ok
|
|
||||||
else:
|
|
||||||
a, b = float(ours), float(theirs)
|
|
||||||
ok = a == b or abs(a - b) <= RTOL * max(1.0, abs(a), abs(b))
|
|
||||||
self.exact += a == b
|
|
||||||
self.close += ok and a != b
|
|
||||||
if not ok:
|
|
||||||
self.wrong.append((where, ours, theirs))
|
|
||||||
|
|
||||||
def report(self, name):
|
|
||||||
total = self.exact + self.close + len(self.wrong)
|
|
||||||
print(
|
|
||||||
f"{name}: {total} fields, {self.exact} identical, {self.close} within {RTOL:g}, "
|
|
||||||
f"{len(self.wrong)} different"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _table(name):
|
|
||||||
return json.loads((FIXTURES / "tables" / f"{name}.json").read_text())
|
|
||||||
|
|
||||||
|
|
||||||
def _edfs():
|
|
||||||
with sqlite3.connect(f"file:{HOSPITAL}?mode=ro", uri=True) as con:
|
|
||||||
rows = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
|
|
||||||
return {key: bytes(edf) for key, edf in rows}
|
|
||||||
|
|
||||||
|
|
||||||
def _analysed(key_edf):
|
|
||||||
key, edf = key_edf
|
|
||||||
return key, analyze(edf)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def analyses():
|
|
||||||
edfs = _edfs()
|
|
||||||
with ProcessPoolExecutor(WORKERS, mp_context=get_context("spawn")) as pool:
|
|
||||||
return dict(pool.map(_analysed, [(k, edfs[k]) for k in sorted(edfs)]))
|
|
||||||
|
|
||||||
|
|
||||||
def test_verdicts_and_checks(analyses):
|
|
||||||
eeg = {r["eeg_id"]: r for r in _table("eeg")}
|
|
||||||
criteria = _table("eeg_criterio")
|
|
||||||
tally = Tally()
|
|
||||||
for key, a in analyses.items():
|
|
||||||
ref = eeg[key]
|
|
||||||
assert a.error is None, (key, a.error)
|
|
||||||
pairs = {
|
|
||||||
"eeg_valido": a.valid,
|
|
||||||
"eeg_nivel": a.level,
|
|
||||||
"eeg_edad_meses": a.age_months,
|
|
||||||
"eeg_fraccion_limpia": a.clean_fraction,
|
|
||||||
"eeg_canales_malos": a.bad_channels,
|
|
||||||
"eeg_canales": a.channels,
|
|
||||||
"eeg_duracion_min": a.duration_min,
|
|
||||||
"eeg_ruido_linea_db": a.line_noise_db,
|
|
||||||
"eeg_con_sueno": a.sleep,
|
|
||||||
"eeg_error": a.error,
|
|
||||||
}
|
|
||||||
for field, ours in pairs.items():
|
|
||||||
theirs = LEVELS[ref[field]] if field == "eeg_nivel" else ref[field]
|
|
||||||
tally((key, field), ours, theirs)
|
|
||||||
theirs = sorted(
|
|
||||||
(
|
|
||||||
(
|
|
||||||
r["cri_codigo"],
|
|
||||||
r["cri_electrodo"] or "",
|
|
||||||
r["cri_valor"],
|
|
||||||
LEVELS.get(r["cri_valor_texto"], r["cri_valor_texto"]),
|
|
||||||
r["cri_unidad"],
|
|
||||||
r["cri_bajo"],
|
|
||||||
r["cri_alto"],
|
|
||||||
r["cri_decisivo"],
|
|
||||||
r["cri_anormal"],
|
|
||||||
)
|
|
||||||
for r in criteria
|
|
||||||
if r["cri_eeg_id"] == key
|
|
||||||
),
|
|
||||||
key=lambda t: (t[0], t[1], str(t[3])),
|
|
||||||
)
|
|
||||||
ours = sorted(
|
|
||||||
(
|
|
||||||
(
|
|
||||||
c["code"],
|
|
||||||
c["electrode"] or "",
|
|
||||||
c["value"],
|
|
||||||
c["text"],
|
|
||||||
c["unit"],
|
|
||||||
c["low"],
|
|
||||||
c["high"],
|
|
||||||
c["decisive"],
|
|
||||||
c["abnormal"],
|
|
||||||
)
|
|
||||||
for c in a.checks
|
|
||||||
),
|
|
||||||
key=lambda t: (t[0], t[1], str(t[3])),
|
|
||||||
)
|
|
||||||
tally((key, "checks"), len(ours), len(theirs))
|
|
||||||
for o, t in zip(ours, theirs, strict=False):
|
|
||||||
for name, x, y in zip(
|
|
||||||
(
|
|
||||||
"code",
|
|
||||||
"electrode",
|
|
||||||
"value",
|
|
||||||
"text",
|
|
||||||
"unit",
|
|
||||||
"low",
|
|
||||||
"high",
|
|
||||||
"decisive",
|
|
||||||
"abnormal",
|
|
||||||
),
|
|
||||||
o,
|
|
||||||
t,
|
|
||||||
strict=True,
|
|
||||||
):
|
|
||||||
tally((key, o[0], o[1], name), x, y)
|
|
||||||
tally.report("eeg + eeg_criterio")
|
|
||||||
assert not tally.wrong, tally.wrong[:20]
|
|
||||||
|
|
||||||
|
|
||||||
def _reference_metrics():
|
|
||||||
"""(eeg, our code) -> (metric row, {electrode: row}, {our zone: row})."""
|
|
||||||
electrodes, zones = {}, {}
|
|
||||||
for r in _table("eeg_metrica_electrodo"):
|
|
||||||
electrodes.setdefault(r["mel_met_id"], {})[r["mel_electrodo"]] = r
|
|
||||||
for r in _table("eeg_metrica_zona"):
|
|
||||||
zones.setdefault(r["mez_met_id"], {})[ZONES.get(r["mez_zona"], r["mez_zona"])] = r
|
|
||||||
return {
|
|
||||||
(r["met_eeg_id"], CODES[r["met_codigo"]]): (
|
|
||||||
r,
|
|
||||||
electrodes.get(r["met_id"], {}),
|
|
||||||
zones.get(r["met_id"], {}),
|
|
||||||
)
|
|
||||||
for r in _table("eeg_metrica")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_metric_values(analyses):
|
|
||||||
reference_rows = _reference_metrics()
|
|
||||||
tally = Tally()
|
|
||||||
for key, a in analyses.items():
|
|
||||||
expected = sorted(code for k, code in reference_rows if k == key)
|
|
||||||
tally((key, "metrics"), ",".join(sorted(m.code for m in a.metrics)), ",".join(expected))
|
|
||||||
for m in a.metrics:
|
|
||||||
row, electrodes, zones = reference_rows[key, m.code]
|
|
||||||
tally((key, m.code), m.value, row["met_valor"])
|
|
||||||
tally(
|
|
||||||
(key, m.code, "electrodes"),
|
|
||||||
",".join(sorted(m.electrodes)),
|
|
||||||
",".join(sorted(electrodes)),
|
|
||||||
)
|
|
||||||
tally((key, m.code, "zones"), ",".join(sorted(m.zones)), ",".join(sorted(zones)))
|
|
||||||
for e, v in m.electrodes.items():
|
|
||||||
tally((key, m.code, e), v, electrodes[e]["mel_valor"])
|
|
||||||
for z, v in m.zones.items():
|
|
||||||
tally((key, m.code, z), v, zones[z]["mez_valor"])
|
|
||||||
tally.report("eeg_metrica + electrodes + zones, values")
|
|
||||||
assert not tally.wrong, tally.wrong[:20]
|
|
||||||
|
|
||||||
|
|
||||||
def _measure_reference():
|
|
||||||
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
|
|
||||||
measured = reference.measure(studies)
|
|
||||||
CACHE.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
|
|
||||||
return measured
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def hk1k():
|
|
||||||
if CACHE.exists() and os.environ.get("EEG_REBUILD_REFERENCE") != "1":
|
|
||||||
return json.loads(CACHE.read_text())["studies"]
|
|
||||||
if not HELSINKI.exists():
|
|
||||||
pytest.skip("no cached HK1K features and no Helsinki EDFs")
|
|
||||||
return _measure_reference()
|
|
||||||
|
|
||||||
|
|
||||||
def _old_feature(feature: str, names: dict[str, str]) -> str:
|
|
||||||
"""`electrode_Fp1` -> `topo_enh_Fp1`, `zone_frontal_left` -> `spindle_zone_frontal_izq`."""
|
|
||||||
if feature in names:
|
|
||||||
return names[feature]
|
|
||||||
prefix, rest = feature.split("_", 1)
|
|
||||||
return names[prefix + "_"] + {ours: old for old, ours in ZONES.items()}.get(rest, rest)
|
|
||||||
|
|
||||||
|
|
||||||
def test_reference_features(hk1k):
|
|
||||||
"""Our HK1K features are the current platform's (as it measured them for its baselines)."""
|
|
||||||
if not OLD_FEATURES.exists():
|
|
||||||
pytest.skip("no captured HK1K features")
|
|
||||||
old = {s["key"]: s for s in json.loads(OLD_FEATURES.read_text())["studies"]}
|
|
||||||
tally = Tally()
|
|
||||||
assert len(hk1k) == len(old) == 223
|
|
||||||
for study in hk1k:
|
|
||||||
theirs = old[study["key"]]
|
|
||||||
tally((study["key"], "age"), study["age_months"], theirs["age_months"])
|
|
||||||
tally((study["key"], "valid"), study["valid"], theirs["valid"])
|
|
||||||
for scenario, (old_name, names) in OLD_SCENARIOS.items():
|
|
||||||
for feature, v in study["features"][scenario].items():
|
|
||||||
old_feature = _old_feature(feature, names)
|
|
||||||
tally((study["key"], feature), v, theirs["features"][old_name][old_feature])
|
|
||||||
tally.report("HK1K features")
|
|
||||||
assert not tally.wrong, tally.wrong[:20]
|
|
||||||
|
|
||||||
|
|
||||||
def test_curves(analyses, hk1k):
|
|
||||||
"""Baselines trained on our HK1K features score each EEG as the registered ones did."""
|
|
||||||
tables = reference.tables(hk1k)
|
|
||||||
assert all(len(t) == 223 for t in tables.values())
|
|
||||||
models = {name: curves.train(table, name) for name, table in tables.items()}
|
|
||||||
json.dumps(models, allow_nan=False) # plain JSON, as MLflow logs it
|
|
||||||
reference_rows = _reference_metrics()
|
|
||||||
tally = Tally()
|
|
||||||
for key, a in analyses.items():
|
|
||||||
for code, scored in curves.deviations(models, a).items():
|
|
||||||
row, electrodes, zones = reference_rows[key, code]
|
|
||||||
value = scored["value"]
|
|
||||||
for ours, theirs in (
|
|
||||||
("z", "met_z"),
|
|
||||||
("outside", "met_fuera"),
|
|
||||||
("p5", "met_p5"),
|
|
||||||
("median", "met_mediana"),
|
|
||||||
("p95", "met_p95"),
|
|
||||||
):
|
|
||||||
tally((key, code, ours), value[ours], row[theirs])
|
|
||||||
for e, s in scored.get("electrodes", {}).items():
|
|
||||||
tally((key, code, e, "z"), s["z"], electrodes[e]["mel_z"])
|
|
||||||
for z, s in scored.get("zones", {}).items():
|
|
||||||
tally((key, code, z, "z"), s["z"], zones[z]["mez_z"])
|
|
||||||
tally.report("eeg_metrica z/outside/p5/median/p95 + electrode and zone z")
|
|
||||||
assert not tally.wrong, tally.wrong[:20]
|
|
||||||
|
|
||||||
|
|
||||||
def test_score_without_value_or_coverage():
|
|
||||||
"""No value, or an age the curve doesn't cover (too few studies anywhere): all None."""
|
|
||||||
table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]})
|
|
||||||
baseline = curves.train(table, "eeg-gradient")["value"]
|
|
||||||
empty = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
|
||||||
assert curves.score(baseline, None, 25.0) == empty
|
|
||||||
assert curves.score(baseline, 2.0, 25.0) == empty
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
|
|
||||||
the rules point at is read into text (scanned ones through OCR). The site: the synthetic
|
|
||||||
hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs)."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import sqlite3
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
|
|
||||||
|
|
||||||
|
|
||||||
def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict:
|
|
||||||
"""What an operator would draw for this site: one Source per table, and a Read on each
|
|
||||||
column that holds documents."""
|
|
||||||
|
|
||||||
def table(node_id, credentials, name, **args):
|
|
||||||
args = {"credentials": credentials, "table": name, **args}
|
|
||||||
return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args}
|
|
||||||
|
|
||||||
nodes = [
|
|
||||||
table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t)
|
|
||||||
for name, tables in hospital_tables.items()
|
|
||||||
for t in tables
|
|
||||||
]
|
|
||||||
return {
|
|
||||||
"nodes": nodes
|
|
||||||
+ [
|
|
||||||
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
|
|
||||||
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
SQL_TABLE = "dlt.sources.sql_database:sql_table"
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path):
|
|
||||||
count, query = platform.count, platform.query
|
|
||||||
tables = {}
|
|
||||||
for name in ("cacu", "cama"):
|
|
||||||
shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db")
|
|
||||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
|
||||||
found = con.execute("select name from sqlite_master where type = 'table'")
|
|
||||||
tables[name] = [t for (t,) in found]
|
|
||||||
truth = site.truth
|
|
||||||
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url)))
|
|
||||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
|
||||||
|
|
||||||
by_place = {}
|
|
||||||
for r in truth:
|
|
||||||
by_place.setdefault(r["where"].split(":")[0], []).append(r)
|
|
||||||
documents = len(truth)
|
|
||||||
expected = {"resultados": documents, "text": documents}
|
|
||||||
for name, names in tables.items():
|
|
||||||
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
|
||||||
for t in names:
|
|
||||||
expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0]
|
|
||||||
|
|
||||||
def counts():
|
|
||||||
return {node: count(f"bronze.n__site__{node}") for node in expected}
|
|
||||||
|
|
||||||
for _ in range(2): # loading the same site again changes nothing
|
|
||||||
platform.ingest()
|
|
||||||
assert counts() == expected
|
|
||||||
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
|
|
||||||
assert len(read_once) == documents # each file read once
|
|
||||||
|
|
||||||
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
|
|
||||||
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
|
|
||||||
platform.ingest()
|
|
||||||
assert counts() == expected
|
|
||||||
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
|
|
||||||
assert query(corrected) == [("64000",)]
|
|
||||||
|
|
||||||
space = re.compile(r"\s+")
|
|
||||||
for table in ("ResultadoSubrogado",):
|
|
||||||
read = query("select id, text, ocr, error from bronze.n__site__text")
|
|
||||||
assert [error for *_, error in read if error is not None] == []
|
|
||||||
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
|
||||||
for r in by_place[table]:
|
|
||||||
txt, ocr = by_id[int(r["where"].split(":")[1])]
|
|
||||||
assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans
|
|
||||||
if "record_number" in r["identity"]: # even scanned, the number reads back exactly
|
|
||||||
assert r["identity"]["record_number"] in txt, (r["where"], txt)
|
|
||||||
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
|
|
||||||
read_once
|
|
||||||
) # reruns never read a file again
|
|
||||||
@@ -1,283 +0,0 @@
|
|||||||
"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two
|
|
||||||
published datasets, loaded by the platform's `cama_reference` pipeline (the files are in
|
|
||||||
`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia).
|
|
||||||
|
|
||||||
Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's
|
|
||||||
constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes
|
|
||||||
and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal
|
|
||||||
cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull
|
|
||||||
curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value
|
|
||||||
on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence;
|
|
||||||
v1 stopped its fit on a 60-second wall clock, short of it, so its curve is v1's within
|
|
||||||
FRACTIONAL_TOLERANCE, not equal. The fractional curve itself is a solver's, within
|
|
||||||
SOLVER_TOLERANCE of the exact series.
|
|
||||||
|
|
||||||
The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to
|
|
||||||
convergence, a few minutes each) are marked `slow` and run only with RECURRENCE_SLOW=1
|
|
||||||
(about an hour); the default set takes about two minutes.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
import pytest
|
|
||||||
from joblib.externals.loky import get_reusable_executor
|
|
||||||
from scipy.special import gammaln
|
|
||||||
|
|
||||||
from conftest import _platform
|
|
||||||
from models import curves
|
|
||||||
from models.cama import recurrence
|
|
||||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
|
||||||
|
|
||||||
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
|
|
||||||
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1"
|
|
||||||
# Max |S| difference to v1's fractional Weibull curve: v1 stopped its fit on a 60 s clock,
|
|
||||||
# short of the optimum this fit converges to (largest gap measured: 0.053).
|
|
||||||
FRACTIONAL_TOLERANCE = 0.06
|
|
||||||
SOLVER_TOLERANCE = 1e-6 # max |S| error of the fractional Weibull's solver (~1e-7 measured)
|
|
||||||
FACTOR_TOLERANCE = 1.01e-4
|
|
||||||
|
|
||||||
FILES = ("brca_metabric_clinical_data.tsv", "scanb_clinical_metadata.txt")
|
|
||||||
PIPELINE = Path(__file__).parents[2] / "tests" / "fixtures" / "pipelines" / "cama_reference.json"
|
|
||||||
pytestmark = pytest.mark.skipif(
|
|
||||||
not all((RAW / f).exists() for f in FILES), reason="no reference raw files"
|
|
||||||
)
|
|
||||||
slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset")
|
|
||||||
|
|
||||||
|
|
||||||
def _json(path: str):
|
|
||||||
return json.loads((V1 / path).read_text())
|
|
||||||
|
|
||||||
|
|
||||||
VERSION = _json("version.json") if V1.exists() else {}
|
|
||||||
DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exists() else {}
|
|
||||||
FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else []
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
|
|
||||||
"""Both datasets as the platform loads them: the `cama_reference` pipeline into a fresh
|
|
||||||
platform, read back from its tables."""
|
|
||||||
folder = tmp_path_factory.mktemp("platform")
|
|
||||||
platform = _platform("sqlite", folder)
|
|
||||||
drawn = folder / "pipeline.json"
|
|
||||||
drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW)))
|
|
||||||
platform.save("pipelines", "cama_reference", drawn)
|
|
||||||
platform.ingest("cama_reference")
|
|
||||||
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
|
||||||
out = folder / "datasets.pkl"
|
|
||||||
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
|
||||||
"from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows("
|
|
||||||
f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip
|
|
||||||
return pd.read_pickle(out)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def prepared(raws):
|
|
||||||
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def fits(prepared):
|
|
||||||
found = modeling.fit(prepared, {})
|
|
||||||
get_reusable_executor().shutdown(wait=True)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- comparisons
|
|
||||||
|
|
||||||
|
|
||||||
# v1 read SCAN-B's clinical stage as a number, so its categories print as 0.0, 1.0...; the
|
|
||||||
# platform keeps the dataset's text (0, 1...). Same categories, in the same order.
|
|
||||||
STAGES = {f"{n}.0": str(n) for n in range(5)}
|
|
||||||
|
|
||||||
|
|
||||||
def _stages(table: dict) -> dict:
|
|
||||||
"""v1's summary with the stages as the dataset writes them."""
|
|
||||||
text = re.sub(r"Estadio_clinico=(\d)\.0", r"Estadio_clinico=\1", json.dumps(table))
|
|
||||||
return json.loads(text)
|
|
||||||
|
|
||||||
|
|
||||||
def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0):
|
|
||||||
ref = [{**r, **{k: STAGES.get(r[k], r[k]) for k in ("categoria", "referencia") if k in r}}
|
|
||||||
if r.get("variable") == "Estadio_clinico" else r for r in ref] # fmt: skip
|
|
||||||
assert len(mine) == len(ref)
|
|
||||||
for i, (a, b) in enumerate(zip(mine, ref, strict=True)):
|
|
||||||
assert a.keys() == b.keys(), i
|
|
||||||
for c, z in b.items():
|
|
||||||
x = a[c]
|
|
||||||
if isinstance(z, float) and not isinstance(z, bool) and x is not None:
|
|
||||||
assert abs(x - z) <= tolerance, (i, c, x, z)
|
|
||||||
else:
|
|
||||||
assert x == z, (i, c, x, z)
|
|
||||||
|
|
||||||
|
|
||||||
def _auc_rows(rows: list[dict], with_bootstrap: bool) -> list[dict]:
|
|
||||||
keep = slice(None) if with_bootstrap else slice(0, 6)
|
|
||||||
return [dict(list(r.items())[keep]) for r in rows]
|
|
||||||
|
|
||||||
|
|
||||||
def _reference_selection(source: str) -> dict:
|
|
||||||
"""v1's bootstrap selection shares, as its risk-factor table published them."""
|
|
||||||
found = {}
|
|
||||||
for r in DEVELOPMENT["factores_riesgo"]["filas"]:
|
|
||||||
if r["cohorte"] == source and r["tipo"] == "factor de riesgo":
|
|
||||||
found.setdefault(r["horizonte_meses"], {})[r["variable"]] = r[
|
|
||||||
"freq_seleccion_bootstrap"
|
|
||||||
]
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def _check_figures(records: list[dict], fractional_tolerance: float):
|
|
||||||
assert [(r["cohorte"], r["escenario"]) for r in records] == [
|
|
||||||
(r["cohorte"], r["escenario"]) for r in FIGURES
|
|
||||||
]
|
|
||||||
for mine, ref in zip(records, FIGURES, strict=True):
|
|
||||||
fixed = ("condiciones", "n", "recaidas", "observado_hasta", "months_max", "cohorte_nombre")
|
|
||||||
assert {k: mine[k] for k in fixed} == {k: ref[k] for k in fixed}
|
|
||||||
assert mine["bootstrap_replicas"] == ref["bootstrap_replicas"]
|
|
||||||
assert mine["km"]["months"] == ref["km"]["months"]
|
|
||||||
for part in ("S", "low", "high"):
|
|
||||||
np.testing.assert_allclose(mine["km"][part], ref["km"][part], rtol=0, atol=1e-12)
|
|
||||||
got, want = mine["points"]["COMB"][part], ref["points"]["COMB"][part]
|
|
||||||
np.testing.assert_allclose(got, want, rtol=0, atol=1e-12)
|
|
||||||
np.testing.assert_allclose(mine["weibull"]["t"], ref["weibull"]["t"], rtol=0, atol=0)
|
|
||||||
np.testing.assert_allclose(mine["weibull"]["S"], ref["weibull"]["S"], rtol=0, atol=1e-12)
|
|
||||||
gap = np.nanmax(np.abs(np.subtract(mine["weibull_fractional"]["S"],
|
|
||||||
ref["weibull_fractional"]["S"]))) # fmt: skip
|
|
||||||
assert gap <= fractional_tolerance, (mine["escenario"], gap)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- fast
|
|
||||||
|
|
||||||
|
|
||||||
def test_cohorts(prepared, raws):
|
|
||||||
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
|
|
||||||
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
|
|
||||||
for source, c in prepared.items():
|
|
||||||
assert len(c.frame) == sampling[source]["pacientes"]
|
|
||||||
assert int(c.frame["evento"].sum()) == sampling[source]["recaidas"]
|
|
||||||
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
|
||||||
assert c.covariates == list(missing[source])
|
|
||||||
assert cohorts.unknown_shares(c) == missing[source]
|
|
||||||
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
|
|
||||||
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_routines(prepared):
|
|
||||||
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
|
|
||||||
for name, record in found.items():
|
|
||||||
assert record == _json(f"rutinas/{name}.json"), name
|
|
||||||
|
|
||||||
|
|
||||||
def test_c_index_and_internal_auc(fits):
|
|
||||||
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
|
|
||||||
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
|
||||||
metrics = reports.metrics(rows)
|
|
||||||
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
|
||||||
|
|
||||||
|
|
||||||
def test_saved_model(fits):
|
|
||||||
"""METABRIC's terms (in order of entry), parents, and their whole-cohort refits."""
|
|
||||||
tables = modeling.tables(fits["metabric"])
|
|
||||||
for h, mine in tables.items():
|
|
||||||
ref = VERSION["model"]["tables"][str(h)]
|
|
||||||
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
|
|
||||||
assert {**mine, "hbn_cpt": cpt} == ref, h
|
|
||||||
frame, covariates = fits["metabric"].cohort.frame, fits["metabric"].cohort.covariates
|
|
||||||
model = recurrence.Recurrence("metabric", recurrence.HORIZONS, covariates, tables)
|
|
||||||
found = model.predict(frame.iloc[:5])
|
|
||||||
assert list(found.columns) == ["recurrence_12m", "recurrence_36m", "recurrence_60m"]
|
|
||||||
t = tables[36]
|
|
||||||
row = frame.iloc[0]
|
|
||||||
x = np.array([float(f"{v}_{row[v]}" == term) for term in t["lr_terms"]
|
|
||||||
for v in [modeling.variable_of(term, model.covariates)]]) # fmt: skip
|
|
||||||
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + x @ np.array(t["lr_coefficients"]))))
|
|
||||||
p_hbn = t["hbn_cpt"][tuple(row[p] for p in t["hbn_parents"])]
|
|
||||||
assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.slow
|
|
||||||
@slow
|
|
||||||
def test_calculator(fits):
|
|
||||||
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
|
||||||
records, rows = [], []
|
|
||||||
for source in recurrence.SOURCES:
|
|
||||||
found = calculator.calculator(fits[source])
|
|
||||||
records += found[0]
|
|
||||||
rows += found[1]
|
|
||||||
get_reusable_executor().shutdown(wait=True)
|
|
||||||
table = reports.table(pd.DataFrame(rows).round(4))
|
|
||||||
assert table["columnas"] == DEVELOPMENT["calculadora"]["columnas"]
|
|
||||||
_same_rows(table["filas"], DEVELOPMENT["calculadora"]["filas"])
|
|
||||||
_check_figures(records, FRACTIONAL_TOLERANCE)
|
|
||||||
|
|
||||||
|
|
||||||
def test_risk_factors(fits):
|
|
||||||
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
|
||||||
table = pd.concat(
|
|
||||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
|
|
||||||
ignore_index=True,
|
|
||||||
)
|
|
||||||
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
|
||||||
FACTOR_TOLERANCE) # fmt: skip
|
|
||||||
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
|
||||||
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
|
||||||
|
|
||||||
|
|
||||||
def test_fractional_weibull_reproduces_the_classic_one():
|
|
||||||
"""With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's."""
|
|
||||||
t = np.linspace(0, 300, 61)
|
|
||||||
for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)):
|
|
||||||
found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam)
|
|
||||||
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
|
|
||||||
|
|
||||||
|
|
||||||
def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741
|
|
||||||
"""E_{rho,m,l}(z) by its defining series, in floats: exact where |z| is small."""
|
|
||||||
j = np.arange(terms - 1)
|
|
||||||
log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1)
|
|
||||||
- gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip
|
|
||||||
return (np.exp(log_c)[None, :] * z[:, None] ** np.arange(terms)[None, :]).sum(axis=1)
|
|
||||||
|
|
||||||
|
|
||||||
def test_fractional_weibull_solver_matches_the_series():
|
|
||||||
"""Where the series is exact in floats (|z| < 2), the solver gives it within its error."""
|
|
||||||
t = np.linspace(0, 72, 289)
|
|
||||||
for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)):
|
|
||||||
s = k + a - 2
|
|
||||||
z = -np.exp(gammaln(k + 1) - gammaln(k + a - 1)) * (t / lam) ** (k + a + b - 2)
|
|
||||||
assert np.abs(z).max() < 2
|
|
||||||
found, want = curves.fractional(t, k, a, b, lam), _series(z, b, s / b + 1, s / b)
|
|
||||||
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- slow: the whole v1 run
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.slow
|
|
||||||
@slow
|
|
||||||
def test_train_reproduces_v1(raws):
|
|
||||||
model, metrics, found = recurrence.train(raws, bootstrap=True)
|
|
||||||
assert metrics == VERSION["metrics"]
|
|
||||||
for h in recurrence.HORIZONS:
|
|
||||||
mine = model.tables[h]
|
|
||||||
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
|
|
||||||
assert {**mine, "hbn_cpt": cpt} == VERSION["model"]["tables"][str(h)]
|
|
||||||
technical = found["technical_validation"]
|
|
||||||
for name, record in technical["rutinas"].items():
|
|
||||||
assert record == _json(f"rutinas/{name}.json"), name
|
|
||||||
tables = technical["recurrencia_desarrollo"]["tablas"]
|
|
||||||
_same_rows(tables["auc"]["filas"], DEVELOPMENT["auc"]["filas"])
|
|
||||||
_same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"])
|
|
||||||
_same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
|
||||||
FACTOR_TOLERANCE) # fmt: skip
|
|
||||||
assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"])
|
|
||||||
figures = found["interpretability"]["recurrencia"]
|
|
||||||
assert figures["horizons_months"] == [12, 36, 60]
|
|
||||||
_check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE)
|
|
||||||
json.dumps(found, allow_nan=False) # JSON-able as it is
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst
|
|
||||||
can trust, and everything the platform can't decide alone is put in front of a reviewer.
|
|
||||||
|
|
||||||
The source hides its answers the way the real one does (synthetic.site): one PDF per study in
|
|
||||||
one SQL Server table, the institute's forms beside what outsourced labs send back; an HPV result
|
|
||||||
is a document of its own on its cytology's order; pathology comes scanned, the name surname
|
|
||||||
first and no birth date; some forms say "MA." for María or misspell the name and leave the
|
|
||||||
employee number out; some HPV reports were re-issued the other way; two women share a name.
|
|
||||||
Medical notes (the colposcopy clinic's, oncology's, neurology's), death notes and TEA's
|
|
||||||
M-CHAT, ADOS-2 and EEG reports are the institute's forms.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
from collections import Counter
|
|
||||||
from datetime import date
|
|
||||||
|
|
||||||
from core import catalog
|
|
||||||
|
|
||||||
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
|
|
||||||
GYN = (
|
|
||||||
"gyn_puerperium",
|
|
||||||
"gyn_pregnancy",
|
|
||||||
"gyn_iud",
|
|
||||||
"gyn_hormonal_treatment",
|
|
||||||
"gyn_other_treatment",
|
|
||||||
"gyn_postmenopause",
|
|
||||||
"gyn_hysterectomy",
|
|
||||||
"gyn_not_applicable",
|
|
||||||
)
|
|
||||||
PRESENTS = (
|
|
||||||
"presents_discharge",
|
|
||||||
"presents_vulvar_pruritus",
|
|
||||||
"presents_abnormal_bleeding",
|
|
||||||
"presents_none",
|
|
||||||
)
|
|
||||||
CYTO = (
|
|
||||||
"cyto_inflammation",
|
|
||||||
"cyto_reactive_changes",
|
|
||||||
"cyto_bacterial_vaginosis_flora",
|
|
||||||
"cyto_candida",
|
|
||||||
"cyto_bacillary_flora_cytolysis",
|
|
||||||
"cyto_intermediate_cytolysis",
|
|
||||||
"cyto_trichomonas",
|
|
||||||
"cyto_leptothrix",
|
|
||||||
"cyto_actinomyces_organisms",
|
|
||||||
"cyto_actinomyces_changes",
|
|
||||||
"cyto_herpes_simplex_changes",
|
|
||||||
"cyto_squamous_tubular_metaplasia",
|
|
||||||
"cyto_keratotic_changes",
|
|
||||||
"cyto_pregnancy_changes",
|
|
||||||
"cyto_atrophy",
|
|
||||||
"cyto_hypoestrogenism",
|
|
||||||
"cyto_radiotherapy_effect",
|
|
||||||
"cyto_iud_changes",
|
|
||||||
"cyto_post_hysterectomy_glandular_cells",
|
|
||||||
"cyto_bacteria",
|
|
||||||
"cyto_herpes_image",
|
|
||||||
"cyto_fungi",
|
|
||||||
"cyto_radiation",
|
|
||||||
"cyto_repair",
|
|
||||||
"cyto_iud_effect",
|
|
||||||
"cyto_endometrial_cells_40_plus",
|
|
||||||
"cyto_findings_none",
|
|
||||||
)
|
|
||||||
FIELDS = {
|
|
||||||
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
|
|
||||||
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
|
||||||
"hpv_18", "cyto_findings_text", *CYTO),
|
|
||||||
"cervical_biopsy": ("request_date", "report_date", "histology"),
|
|
||||||
"mammography": ("exam_date", "report_date", "adequacy", "birads"),
|
|
||||||
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
|
|
||||||
"er", "pr", "her2", "ki67_pct", "size_mm", "positive_nodes", "stage"),
|
|
||||||
"breast_treatment": ("start_date", "kind"),
|
|
||||||
"breast_recurrence": ("diagnosis_date", "site"),
|
|
||||||
"clinical_note": ("note_date", "specialty", "icd10"),
|
|
||||||
"death": ("death_date",),
|
|
||||||
"mchat": ("screening_date", "score"),
|
|
||||||
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
|
||||||
"eeg": ("study_date", "lab_record_id", "edf"),
|
|
||||||
} # fmt: skip
|
|
||||||
BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS, *CYTO}
|
|
||||||
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
|
||||||
|
|
||||||
|
|
||||||
def value(field, v):
|
|
||||||
if v is None:
|
|
||||||
return None
|
|
||||||
if field in BOOLS:
|
|
||||||
return bool(v) if not isinstance(v, str) else v == "true"
|
|
||||||
if field in NUMBERS:
|
|
||||||
return float(v)
|
|
||||||
return v.isoformat() if isinstance(v, date) else str(v)
|
|
||||||
|
|
||||||
|
|
||||||
def said(record: dict, entity: str) -> dict | None:
|
|
||||||
"""What a document says of one study (an oncology note: its treatment and the note)."""
|
|
||||||
if entity == "clinical_note":
|
|
||||||
return record.get("clinical_note")
|
|
||||||
return record["values"] if record["entity"] == entity else None
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path):
|
|
||||||
truth = site.truth
|
|
||||||
(tmp_path / "pipeline.json").write_text(site.drawn)
|
|
||||||
platform.save("concept_maps", "erick_site", site.concept_map)
|
|
||||||
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
|
||||||
platform.ingest()
|
|
||||||
q = platform.query
|
|
||||||
of = site.patients(q)
|
|
||||||
|
|
||||||
# Persons: nobody is merged with somebody else, except the two women of one name, joined
|
|
||||||
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
|
|
||||||
# whose report it is.
|
|
||||||
# A person nothing names (a scan whose name line wasn't read) is held as well: there is
|
|
||||||
# nobody to join her to.
|
|
||||||
members: dict[str, set] = {}
|
|
||||||
held, nameless, named, person_of = set(), set(), set(), {}
|
|
||||||
for record, person, why, *identifiers in q(
|
|
||||||
"select _record, person_id, _held, full_name, birth_date, record_number "
|
|
||||||
"from bronze.n__site__persons"
|
|
||||||
):
|
|
||||||
members.setdefault(person, set()).add(of[record])
|
|
||||||
person_of[record] = person
|
|
||||||
if any(identifiers):
|
|
||||||
named.add(person)
|
|
||||||
if why and "no name" in why:
|
|
||||||
nameless.add(person)
|
|
||||||
elif why:
|
|
||||||
held.add(person)
|
|
||||||
assert nameless == set(members) - named, nameless
|
|
||||||
torn = {p for p, who in members.items() if len(who) > 1}
|
|
||||||
assert len(torn) == 1 and torn == held, (torn, held)
|
|
||||||
assert members[next(iter(torn))] == set(site.meta["namesakes"])
|
|
||||||
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless}
|
|
||||||
|
|
||||||
# Every woman split into several persons (a misspelled form, say) is in the review
|
|
||||||
# queue, joined by candidates.
|
|
||||||
parts: dict[str, set] = {}
|
|
||||||
for p, x in patient.items():
|
|
||||||
parts.setdefault(x, set()).add(p)
|
|
||||||
queued = {
|
|
||||||
frozenset(person_of[r] for r in pair)
|
|
||||||
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
|
||||||
}
|
|
||||||
split = {x: persons for x, persons in parts.items() if len(persons) > 1}
|
|
||||||
assert split # the misspelled forms, at least
|
|
||||||
for x, persons in split.items():
|
|
||||||
reached, frontier = set(), {next(iter(persons))}
|
|
||||||
while frontier:
|
|
||||||
reached |= frontier
|
|
||||||
frontier = {b for a in frontier for pair in queued if a in pair for b in pair}
|
|
||||||
frontier -= reached
|
|
||||||
assert persons <= reached, (x, persons)
|
|
||||||
|
|
||||||
# Every value accepted from a typed document is what the document says; and most of what
|
|
||||||
# the documents say is read (a scan's columns can come back out of order, and a value its
|
|
||||||
# pattern doesn't find is left out, never guessed). A scan can misread one valid code as
|
|
||||||
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
|
|
||||||
# values (one, on a site too small for a rate), each listed.
|
|
||||||
at = {r["where"]: r for r in truth}
|
|
||||||
place = {r: f"ResultadoSubrogado:{i}"
|
|
||||||
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
|
|
||||||
record_of = {w: r for r, w in place.items()}
|
|
||||||
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
|
|
||||||
for entity in FIELDS:
|
|
||||||
mine = accepted[entity] = {}
|
|
||||||
for record, field, *values in q(
|
|
||||||
"select _record, field, value_text, value_num, value_bool, value_date "
|
|
||||||
f"from bronze.staged__observation where study = '{entity}'"
|
|
||||||
):
|
|
||||||
got = next((v for v in values if v is not None), None)
|
|
||||||
mine.setdefault(record, {})[field] = value(field, got)
|
|
||||||
assert mine or not any(said(r, entity) for r in truth), entity
|
|
||||||
stated = read = scanned = 0
|
|
||||||
missed: Counter = Counter()
|
|
||||||
wrong = []
|
|
||||||
for record, got in mine.items():
|
|
||||||
t = at[place[record]]
|
|
||||||
if not t.get("flipped"):
|
|
||||||
truly = {f: v for f, v in said(t, entity).items() if v is not None}
|
|
||||||
differ = {f: (v, value(f, truly.get(f))) for f, v in got.items()
|
|
||||||
if v != value(f, truly.get(f))} # fmt: skip
|
|
||||||
assert t.get("scanned") or not differ, (t["where"], differ)
|
|
||||||
wrong += [(t["where"], differ)] if differ else []
|
|
||||||
scanned += len(got) if t.get("scanned") else 0
|
|
||||||
stated, read = stated + len(truly), read + len(got)
|
|
||||||
missed.update(set(truly) - set(got))
|
|
||||||
assert read >= 0.95 * stated, (entity, read, stated, missed)
|
|
||||||
assert len(wrong) <= max(1, 0.01 * scanned), (entity, wrong)
|
|
||||||
|
|
||||||
# A row a rule held because of a value (a scan misread) is held because it is wrong:
|
|
||||||
# never loaded, and a reviewer sees it.
|
|
||||||
misread = set()
|
|
||||||
for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"):
|
|
||||||
if record in place and person_of.get(record) not in torn | nameless:
|
|
||||||
t, got = at[place[record]], json.loads(raw)
|
|
||||||
truly = said(t, entity)
|
|
||||||
assert {f: value(f, got.get(f)) for f in truly} != {
|
|
||||||
f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip
|
|
||||||
misread.add(record)
|
|
||||||
|
|
||||||
# Silver: each person's studies, the records of one study key merged (a cytology form and
|
|
||||||
# its HPV report are one cytology), but for the torn person's, the misreads, and a study
|
|
||||||
# whose reports contradict each other (until review says which is right).
|
|
||||||
for entity, fields in FIELDS.items():
|
|
||||||
key = catalog.studies()[entity].key
|
|
||||||
merged: dict[tuple, dict] = {}
|
|
||||||
disputed = set()
|
|
||||||
for r in truth:
|
|
||||||
record = record_of[r["where"]]
|
|
||||||
got = accepted[entity].get(record)
|
|
||||||
if got is None or person_of[record] in torn | nameless or record in misread:
|
|
||||||
continue
|
|
||||||
at_key = (person_of[record], *(got.get(k) for k in key))
|
|
||||||
merged.setdefault(at_key, {}).update(got)
|
|
||||||
if r.get("conflict"):
|
|
||||||
disputed.add(at_key)
|
|
||||||
expected = {(k[0], *(row.get(f) for f in fields))
|
|
||||||
for k, row in merged.items() if k not in disputed} # fmt: skip
|
|
||||||
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
|
||||||
got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True)))
|
|
||||||
for p, *values in rows if p not in torn | nameless} # fmt: skip
|
|
||||||
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
|
|
||||||
sorted(expected - got, key=str)[:4]) # fmt: skip
|
|
||||||
@@ -1,211 +0,0 @@
|
|||||||
"""CaMa survival measured against the SEER-trained original (Luis's pipeline,
|
|
||||||
`05_curvas_supervivencia.py`): the same model, trained on the same SEER patients, gives each
|
|
||||||
clinical scenario the same patients and deaths, the same observed curves (Kaplan-Meier,
|
|
||||||
Weibull, fractional Weibull), and model points close to the original's.
|
|
||||||
|
|
||||||
SEER is real registry data under NCI's use agreement: it is read from outside git
|
|
||||||
(SEER_FILE) and nothing of it is kept. The original's outputs are read from where it ran
|
|
||||||
(LUIS_RUN: its `subgrupos_*.csv`). Both missing: the test is skipped.
|
|
||||||
|
|
||||||
Each SEER case becomes a timeline: a first invasive biopsy at diagnosis with its report's
|
|
||||||
results, its first course of treatment a month later, and its death or last contact placed so
|
|
||||||
the platform's whole months of follow-up are SEER's survival months.
|
|
||||||
|
|
||||||
The model points are not the original's: it trains on every case, the platform on the
|
|
||||||
earliest 70% by index date (and validates on the rest), and SEER's latest diagnoses carry few
|
|
||||||
recorded deaths yet. They are checked against the survival of the cases the model learned
|
|
||||||
from; their distance to the original's is printed. Slow (a quarter of an hour): SEER_SLOW=1."""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from models import curves, survival
|
|
||||||
from models.cama.specs import MODELS
|
|
||||||
from models.survival import DAYS_PER_MONTH, DAYS_PER_YEAR, TRAIN_FRACTION, scenario_masks
|
|
||||||
|
|
||||||
SEER = Path(
|
|
||||||
os.environ.get("SEER_FILE", Path.home() / "camaSupervivencia" / "dataframe_recodificado.csv")
|
|
||||||
)
|
|
||||||
RUN = Path(os.environ.get("LUIS_RUN", Path.home() / "isssteleon-data" / "luis-run"))
|
|
||||||
AS_OF = pd.Timestamp("2023-12-31") # SEER's follow-up cutoff: survivors are followed to it
|
|
||||||
|
|
||||||
pytestmark = [
|
|
||||||
pytest.mark.skipif(
|
|
||||||
not (SEER.exists() and (RUN / "subgrupos_KM_Weibull_fraccional.csv").exists()),
|
|
||||||
reason="SEER and the original's outputs are outside git",
|
|
||||||
),
|
|
||||||
pytest.mark.skipif(not os.environ.get("SEER_SLOW"), reason="slow: SEER_SLOW=1"),
|
|
||||||
]
|
|
||||||
CURVE = 1e-3 # the fits' agreement (maximum distance to Kaplan-Meier, shape k relative)
|
|
||||||
CALIBRATION = 0.01 # the model's mean survival against its training cases' Kaplan-Meier
|
|
||||||
|
|
||||||
STAGE = {"0 (in situ)": "0", "I": "I", "II": "II", "III": "III", "IV": "IV"}
|
|
||||||
GRADE = {"G1": "1", "G2": "2", "G3": "3"}
|
|
||||||
RECEPTOR = {"Positivo": "positive", "Negativo": "negative"}
|
|
||||||
SURGERY = {"Conservadora": "breast_conserving_surgery", "Mastectomía": "mastectomy"}
|
|
||||||
|
|
||||||
|
|
||||||
def _her2(subtype: str) -> str | None:
|
|
||||||
return "positive" if "HER2+" in subtype else "negative" if "HER2-" in subtype else None
|
|
||||||
|
|
||||||
|
|
||||||
def _age(recode: str) -> float:
|
|
||||||
"""The age band's lower bound, as the original reads it ("65-69 years": 65)."""
|
|
||||||
found = re.search(r"\d+", str(recode))
|
|
||||||
return float(found.group()) if found else np.nan
|
|
||||||
|
|
||||||
|
|
||||||
def seer_events(frame: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
"""SEER cases as CaMa timelines (gold `cama_events` shape, indexed at diagnosis)."""
|
|
||||||
months = pd.to_numeric(frame["Survival_months"], errors="coerce")
|
|
||||||
frame, months = frame[months.notna()], months[months.notna()]
|
|
||||||
dead = frame["Vital_status_recode_study_cutoff_used"].str.lower().str.contains("dead")
|
|
||||||
person = frame["Patient_ID"].to_numpy()
|
|
||||||
# Whole months from the index are SEER's. A survivor's index is months + 1/2 before the
|
|
||||||
# cutoff; a death's is in its year of diagnosis (spread over the year by its id, never so
|
|
||||||
# late that the death would pass the cutoff), and she dies months + 1/4 after it. So the
|
|
||||||
# index dates keep SEER's calendar, which the model's split by index date reads.
|
|
||||||
latest = AS_OF - pd.to_timedelta((months + 0.5) * DAYS_PER_MONTH, "D")
|
|
||||||
year = pd.to_datetime(frame["Year_of_diagnosis"] + "-01-01")
|
|
||||||
spread = pd.to_timedelta(frame["Patient_ID"].astype(int) % 365, "D")
|
|
||||||
index = latest.where(~dead, (year + spread).where(year + spread < latest, latest))
|
|
||||||
death = index + pd.to_timedelta((months + 0.25) * DAYS_PER_MONTH, "D")
|
|
||||||
birth = index - pd.to_timedelta((frame["Age_recode_with_1_year_olds_and_90"].map(_age) + 0.5)
|
|
||||||
* DAYS_PER_YEAR, "D") # fmt: skip
|
|
||||||
base = pd.DataFrame({"person_id": person, "index_date": index.to_numpy(),
|
|
||||||
"record_number": person}) # fmt: skip
|
|
||||||
rows = [base.assign(date=birth.to_numpy(), type="birth", value_code=None)]
|
|
||||||
rows.append(base[dead.to_numpy()].assign(date=death[dead].to_numpy(), type="death",
|
|
||||||
value_code=None)) # fmt: skip
|
|
||||||
hr_negative = frame["Subtipo_molecular_cat"].str.startswith("HR-")
|
|
||||||
hr_positive = frame["Subtipo_molecular_cat"].str.startswith("HR+")
|
|
||||||
er = frame["Receptor_estrogeno_cat"].map(RECEPTOR)
|
|
||||||
pr = frame["Receptor_progesterona_cat"].map(RECEPTOR)
|
|
||||||
both_negative = er.eq("negative") & pr.eq("negative")
|
|
||||||
results = {
|
|
||||||
"biopsy": pd.Series("invasive", index=frame.index),
|
|
||||||
"stage": frame["Estadio_cat"].map(STAGE),
|
|
||||||
"grade": frame["Grado_histologico_cat"].map(GRADE),
|
|
||||||
# Hormone receptors as SEER's subtype states them, which the original's scenarios read:
|
|
||||||
# SEER's own columns disagree in a few cases (HR+ with both recodes negative, likely
|
|
||||||
# borderline results): HR- makes both negative; HR+ with both negative leaves ER unknown.
|
|
||||||
"er": er.mask(hr_negative, "negative").mask(hr_positive & both_negative, None),
|
|
||||||
"pr": pr.mask(hr_negative, "negative"),
|
|
||||||
"her2": frame["Subtipo_molecular_cat"].map(_her2),
|
|
||||||
"histologic_type": frame["Histologic_Type_ICD_O_3"].astype(str) + "/3",
|
|
||||||
}
|
|
||||||
for kind, values in results.items():
|
|
||||||
rows.append(base.assign(date=index.to_numpy(), type=kind, value_code=values.to_numpy()))
|
|
||||||
size = pd.to_numeric(frame["Tumor_Size_Over_Time_Recode_1988"], errors="coerce")
|
|
||||||
rows.append(base.assign(date=index.to_numpy(), type="size_mm", value_code=None,
|
|
||||||
value_num=size.where(size < 990).to_numpy())) # fmt: skip
|
|
||||||
course = {
|
|
||||||
"surgery": frame["Tratamiento_quirurgico_cat"].map(SURGERY),
|
|
||||||
"chemotherapy": frame["Quimioterapia_cat"].map({"Sí": "chemotherapy"}),
|
|
||||||
"radiotherapy": frame["Radioterapia_cat"].map({"Sí": "radiotherapy"}),
|
|
||||||
}
|
|
||||||
month_later = index + pd.Timedelta(days=30)
|
|
||||||
for values in course.values():
|
|
||||||
rows.append(base.assign(date=month_later.to_numpy(), type="treatment",
|
|
||||||
value_code=values.to_numpy())) # fmt: skip
|
|
||||||
events = pd.concat(rows, ignore_index=True)
|
|
||||||
events = events[events["type"].isin(["birth", "death"]) | events["value_code"].notna()
|
|
||||||
| events.get("value_num", pd.Series(np.nan)).notna()] # fmt: skip
|
|
||||||
events["value_num"] = events.get("value_num")
|
|
||||||
events["source_table"], events["source_id"] = "seer", events["person_id"]
|
|
||||||
return events.reset_index(drop=True)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def trained():
|
|
||||||
events = seer_events(pd.read_csv(SEER, dtype=str))
|
|
||||||
spec = MODELS["survival"]
|
|
||||||
model, metrics, data = spec.train(events, AS_OF)
|
|
||||||
return spec, model, metrics, data
|
|
||||||
|
|
||||||
|
|
||||||
def _original(name: str) -> pd.DataFrame:
|
|
||||||
return pd.read_csv(RUN / name)
|
|
||||||
|
|
||||||
|
|
||||||
def test_each_scenario_takes_the_originals_patients_and_deaths(trained):
|
|
||||||
spec, _, _, data = trained
|
|
||||||
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
|
|
||||||
masks = scenario_masks(members, spec.scenarios)
|
|
||||||
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
|
|
||||||
for name, row in theirs.iterrows():
|
|
||||||
mask = masks[name]
|
|
||||||
assert (int(mask.sum()), int(members["event"][mask].sum())) == (
|
|
||||||
row["n"],
|
|
||||||
row["fallecidos"],
|
|
||||||
), name
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def report(trained):
|
|
||||||
spec, model, _, data = trained
|
|
||||||
return survival.interpretability(spec, model, data)
|
|
||||||
|
|
||||||
|
|
||||||
def test_each_scenarios_observed_curves_are_the_originals(report):
|
|
||||||
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
|
|
||||||
assert {e["escenario"] for e in report["escenarios"]} == set(theirs.index)
|
|
||||||
for e in report["escenarios"]:
|
|
||||||
row, km = theirs.loc[e["escenario"]], np.array(e["km"]["S"])
|
|
||||||
months = np.arange(len(km))
|
|
||||||
weibull = np.interp(months, e["weibull"]["t"], e["weibull"]["S"])
|
|
||||||
fractional = np.interp(months, e["weibull_fractional"]["t"], e["weibull_fractional"]["S"])
|
|
||||||
assert e["weibull"]["k"] == pytest.approx(row["k Weibull"], rel=CURVE), e["escenario"]
|
|
||||||
assert np.abs(weibull - km).max() == pytest.approx(row["máx|KM−Weibull|"], abs=CURVE)
|
|
||||||
assert np.abs(fractional - km).max() <= row["máx|KM−fracc.|"] + CURVE, e["escenario"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained, report):
|
|
||||||
spec, _, _, data = trained
|
|
||||||
train = data["train"].reset_index(drop=True)
|
|
||||||
masks = scenario_masks(train, spec.scenarios)
|
|
||||||
theirs = _original("subgrupos_puntos_LR_HBN.csv")
|
|
||||||
horizons = list(spec.borders[1:])
|
|
||||||
for e in report["escenarios"]:
|
|
||||||
mask = masks[e["escenario"]]
|
|
||||||
months, event = train["months"][mask].to_numpy(), train["event"][mask].to_numpy(bool)
|
|
||||||
km, _, _ = curves.kaplan_meier(months, event, horizons[-1])
|
|
||||||
ours = np.array(e["points"]["COMB"]["S"])
|
|
||||||
assert ours == pytest.approx(km[horizons], abs=CALIBRATION), e["escenario"]
|
|
||||||
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
|
|
||||||
gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max()
|
|
||||||
print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}")
|
|
||||||
|
|
||||||
|
|
||||||
# The original's names for the categories both rate alike (stage, grade, receptors).
|
|
||||||
SAME = {
|
|
||||||
("Estadio", "IV"): ("stage", "IV"), ("Estadio", "III"): ("stage", "III"),
|
|
||||||
("Estadio", "II"): ("stage", "II"), ("Estadio", "0 (in situ)"): ("stage", "0"),
|
|
||||||
("Grado_histologico", "G3"): ("grade", "3"), ("Grado_histologico", "G1"): ("grade", "1"),
|
|
||||||
("Receptor_progesterona", "Negativo"): ("pr", "negative"),
|
|
||||||
} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def test_risk_factors_rate_as_the_originals(trained):
|
|
||||||
"""The risk factors of death by 18 months (models.factors, as `06_factores_riesgo.py`)
|
|
||||||
on the same SEER cases: the same direction for every category both rate, the same class
|
|
||||||
for stage and grade, odds ratios within 20 % and 18-month survival within 0.05. The
|
|
||||||
original also rates the stability of its stepwise selection and reads the Markov blanket
|
|
||||||
of a learned network; the platform's model has neither stepwise selection nor PR among
|
|
||||||
its network's parents, so PR negative is "sugerente" here and "robusto" there."""
|
|
||||||
spec, model, _, data = trained
|
|
||||||
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
|
|
||||||
ours = survival.risk_factors(spec, model, members).set_index(["variable", "categoria"])
|
|
||||||
theirs = _original("factores_riesgo.csv").set_index(["variable", "categoria"])
|
|
||||||
for key, mine in SAME.items():
|
|
||||||
a, b = theirs.loc[key], ours.loc[mine]
|
|
||||||
assert b["clasificacion"].split()[0] == a["clasificacion"].split()[0], key
|
|
||||||
if key[0] != "Receptor_progesterona":
|
|
||||||
assert b["clasificacion"] == a["clasificacion"], key
|
|
||||||
assert b["OR_muerte"] == pytest.approx(a["OR_muerte"], rel=0.2), key
|
|
||||||
assert b["S_categoria"] == pytest.approx(a["S18_categoria"], abs=0.05), key
|
|
||||||
Reference in New Issue
Block a user