commit 41508efeb69b36e2e09f366bd2439ca10086126c Author: Roberto Treviño Date: Sun Nov 29 18:11:48 2026 -0600 ISSSTELEON models diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c26bd1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +node_modules/ +dist/ +.angular/ diff --git a/models/__init__.py b/models/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/models/__init__.py @@ -0,0 +1 @@ + diff --git a/models/cacu/__init__.py b/models/cacu/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/models/cacu/__init__.py @@ -0,0 +1 @@ + diff --git a/models/cacu/features.py b/models/cacu/features.py new file mode 100644 index 0000000..dad6a73 --- /dev/null +++ b/models/cacu/features.py @@ -0,0 +1,157 @@ +import numpy as np +import pandas as pd +from core import cacu + +RESULTS = ("bethesda", "glandular", "hpv") +REFERRED = ("colposcopy", "biopsy") +MISSING = "(none)" + + +def prepared(events: pd.DataFrame) -> pd.DataFrame: + return events.assign( + date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"]) + ) + + +def days(events: pd.DataFrame) -> pd.Series: + return (events["date"] - events["index_date"]).dt.days + + +def _worst(codes: pd.Series, cytology: dict) -> pd.Series: + rank = {code: i for i, values in enumerate(cytology.values()) for code in values} + names = list(cytology) + worst = codes.map(rank).groupby(level=0).max() + return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object) + + +def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series: + first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min() + before = (events["person_id"].map(first) - events["date"]).dt.days + near = events[before.between(0, history["lookback_days"])] + codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"] + worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy() + hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")] + positive = persons.isin(hpv["person_id"]) + grade = np.where( + np.isin(worst, history["high"]), + "high", + np.where( + np.isin(worst, history["low"]) + | np.isin(worst, history["low_if_hpv_positive"]) & positive.to_numpy(), + "low", + None, + ), + ) + return pd.Series(grade, index=persons.index, dtype=object) + + +def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None): + near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)] + wide = near.sort_values("date", kind="stable").pivot_table( + index="person_id", columns="type", values="value_code", aggfunc="first" + ) + members = events.groupby("person_id", as_index=False)["index_date"].first() + wide = wide.reindex(index=members["person_id"], columns=list(RESULTS)) + codes = wide[["bethesda", "glandular"]].stack() + members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy() + members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy() + if history: + members[history["feature"]] = _referral_grade(events, members["person_id"], history) + return members + + +def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame: + timed = events.assign(days=d.astype(float))[d >= 0] + biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)] + visits = None + for kind, values in cacu.KNOWN_NEGATIVE.items(): + found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)] + found = found[["person_id", "days"]] + if visits is None: + visits = found + continue + paired = pd.merge_asof( + visits.sort_values("days"), + found.rename(columns={"days": kind}).sort_values(kind), + left_on="days", + right_on=kind, + by="person_id", + direction="nearest", + tolerance=float(cacu.INDEX_SAMPLE_DAYS), + ).dropna(subset=[kind]) + visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]] + return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True) + + +def interval_coded( + events: pd.DataFrame, grades: list[str], cytology: dict, history: dict | None = None +) -> pd.DataFrame: + d = days(events) + outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0) + first = d[outcome].groupby(events.loc[outcome, "person_id"]).min() + negatives = _negatives(events, d, grades) + before = ~(negatives["days"] >= negatives["person_id"].map(first)) + last_negative = negatives[before].groupby("person_id")["days"].max() + coded = index_results(events, cytology, history) + window = cacu.PREVALENT_WINDOW_DAYS + event_days, free_until = (coded["person_id"].map(first), coded["person_id"].map(last_negative)) + prevalent = event_days <= window + free = free_until.notna() & ~prevalent + later = event_days.notna() & ~prevalent + coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999)) + coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0) + coded["r"] = np.where(prevalent, 0.0, np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) + return coded + + +def last_screening_cytology(events: pd.DataFrame) -> pd.Series: + referred = set(events.loc[events["type"].isin(REFERRED), "person_id"]) + key = ["person_id", "source_table", "source_id"] + samples = events.loc[ + (events["type"] == "cytology") & ~events["person_id"].isin(referred), [*key, "date"] + ] + results = events[events["type"].isin(RESULTS) & events["value_code"].notna()] + has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first") + has = has.reindex(columns=list(RESULTS)) + complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()] + samples = samples.set_index(key) + samples = samples[samples.index.isin(complete.index)].reset_index() + latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last() + return latest["date"] + + +def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]: + ordered = members.sort_values(["index_date", "person_id"], kind="stable") + cut = int(len(ordered) * train_fraction) + return (ordered.iloc[:cut], ordered.iloc[cut:]) + + +def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame: + members = events.groupby(["person_id", "index_date"], as_index=False).size() + members = members[["person_id", "index_date"]] + sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])] + sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first() + results = events.merge(sample, on=["person_id", "source_table", "source_id"]) + genotype = results["type"] == "hpv_16_18" + results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map( + {1.0: "positive", 0.0: "negative"} + ) + wide = results[results["type"].isin(predictors)].pivot_table( + index="person_id", columns="type", values="value_code", aggfunc="first" + ) + wide = wide.reindex(columns=list(predictors)).astype(object) + found = members.merge(wide, left_on="person_id", right_index=True, how="left") + return found.fillna(dict.fromkeys(predictors, MISSING)) + + +def windowed_outcome( + events: pd.DataFrame, grades: list[str], years: float, follow_up_end: pd.Timestamp +) -> pd.DataFrame: + window = years * cacu.DAYS_PER_YEAR + outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) + outcome &= days(events).between(0, window) + members = events.groupby(["person_id", "index_date"], as_index=False).size() + members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int) + followed = (follow_up_end - members["index_date"]).dt.days + members["known"] = (members["y"] == 1) | (followed >= window) + return members[["person_id", "y", "known"]] diff --git a/models/cacu/jobs.py b/models/cacu/jobs.py new file mode 100644 index 0000000..fb7a48e --- /dev/null +++ b/models/cacu/jobs.py @@ -0,0 +1,6 @@ +from models.cacu import reports +from models.cacu.specs import MODELS +from models.jobs import Jobs + +JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability) +train, score = (JOBS.train, JOBS.score) diff --git a/models/cacu/pim.py b/models/cacu/pim.py new file mode 100644 index 0000000..51a1442 --- /dev/null +++ b/models/cacu/pim.py @@ -0,0 +1,256 @@ +from dataclasses import dataclass +import numpy as np +import pandas as pd +from scipy.interpolate import BSpline +from scipy.optimize import minimize +from scipy.special import expit +from scipy.stats import norm +from sklearn.base import BaseEstimator + +UNKNOWN = -999 +TINY = 1e-12 +FROZEN = 15.0 +HESSIAN_STEP = 0.0001 + + +def ispline_basis(t, degree: int, knots) -> np.ndarray: + t, knots = (np.asarray(t, dtype=float), np.asarray(knots, dtype=float)) + full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)] + inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1]) + bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray() + basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:] + basis[t >= knots[-1]] = 1.0 + basis[t <= knots[0]] = 0.0 + return basis + + +@dataclass(frozen=True) +class ISpline: + knots: tuple[float, ...] + degree: int + + @classmethod + def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline": + times = np.unique(np.r_[l, r[np.isfinite(r)]]) + return cls( + tuple((float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))), degree + ) + + @property + def n_params(self) -> int: + return len(self.knots) + self.degree - 2 + + def cumulative_hazard(self, t, params) -> np.ndarray: + return ispline_basis(t, self.degree, self.knots) @ np.exp(params) + + def start(self, c, l, r) -> np.ndarray: + at_risk, finite = (c != 1, np.isfinite(r)) + exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum() + events = (at_risk & finite & (r > 0)).sum() + rate = np.exp(-np.log(max(exposure, 1e-06) / (events + 0.5))) + return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-06) / self.n_params)) + + +def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray: + t = np.asarray(t, dtype=float) + with np.errstate(over="ignore", invalid="ignore"): + found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta)) + found = np.where(t <= 0, 1.0, found) + return np.where(np.isinf(t), 0.0, found) + + +def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float: + n_x, n_z = (X.shape[1], Z.shape[1]) + theta, beta, rest = (params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]) + pi = expit(X @ theta) + interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z) + interval = np.maximum(interval, TINY) + row = np.zeros(len(c)) + prevalent, free, unknown = (c == 1, c == 0, c == UNKNOWN) + row[prevalent] = np.log(pi[prevalent] + TINY) + row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free]) + row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY) + return -np.sum(w * row) + + +def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray: + p = len(x) + out = np.zeros((p, p)) + for i in range(p): + for j in range(i, p): + ei, ej = (np.zeros(p), np.zeros(p)) + ei[i], ej[j] = (step, step) + value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / ( + 4 * step * step + ) + out[i, j] = out[j, i] = value + return out + + +def _ridge_logistic(c, X, ridge: float = 0.001) -> np.ndarray: + known = c != UNKNOWN + if not known.any(): + return np.zeros(X.shape[1]) + y, Xk = ((c[known] == 1).astype(float), X[known]) + + def loss(theta): + eta = Xk @ theta + return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta + + return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x + + +@dataclass(frozen=True) +class Fit: + n_x: int + n_z: int + baseline: ISpline + params: np.ndarray + covariance: np.ndarray + neg_loglik: float + converged: bool + + def risk(self, X, Z, years, params=None) -> np.ndarray: + p = self.params if params is None else params + theta, beta, rest = ( + p[: self.n_x], + p[self.n_x : self.n_x + self.n_z], + p[self.n_x + self.n_z :], + ) + pi = expit(X @ theta) + return np.column_stack( + [ + pi + + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z)) + for t in years + ] + ) + + def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]: + gradient = np.empty((len(self.params), len(X), len(years))) + for k, value in enumerate(self.params): + step = 1e-05 * max(1.0, abs(value)) + up, down = (self.params.copy(), self.params.copy()) + up[k] += step + down[k] -= step + gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step) + covariance = np.nan_to_num(self.covariance, nan=0.0) + variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient) + return (self.risk(X, Z, years), np.maximum(variance, 0.0)) + + +def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: + n_x, n_z = (X.shape[1], Z.shape[1]) + start = baseline.start(c, l, r) + starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]] + args = (c, l, r, X, Z, baseline, w) + results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts] + best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf) + free = np.abs(best.x) < FROZEN + covariance = np.full((len(best.x), len(best.x)), np.nan) + h = hessian(lambda p: neg_loglik(p, *args), best.x) + try: + covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)]) + except np.linalg.LinAlgError: + pass + converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 0.001) + return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged) + + +class Mixture(BaseEstimator): + def __init__( + self, + horizons_years, + incidence_features, + strata, + levels, + knots=3, + degree=4, + interval_level=0.95, + ): + self.horizons_years = horizons_years + self.incidence_features = incidence_features + self.strata = strata + self.levels = levels + self.knots = knots + self.degree = degree + self.interval_level = interval_level + + def _seen(self, X: pd.DataFrame) -> dict: + return { + f: [v for v in values if (X[f] == v).any()] + for f, values in self.levels.items() + if f in X.columns and f not in self.strata + } + + def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray: + if not seen: + return np.ones(len(X), dtype=bool) + return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0) + + def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray: + columns = [] + for f in features: + if f in self.strata: + continue + if f in seen: + columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]] + else: + columns.append(X[f].to_numpy(dtype=float)) + return np.column_stack(columns) if columns else np.zeros((len(X), 0)) + + def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]: + prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)]) + return (prevalence, self._columns(X, self.incidence_features, seen)) + + def _groups(self, X: pd.DataFrame): + if not self.strata: + return [((), np.arange(len(X)))] + groups = X.groupby(list(self.strata), sort=True).indices.items() + return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups] + + def fit(self, X: pd.DataFrame, y: pd.DataFrame): + rows = pd.concat( + [X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1 + ).assign(w=1.0) + self.fits_, self.seen_ = ({}, {}) + for key, index in self._groups(X): + group = rows.iloc[index] + seen = self._seen(group) + group = group[self._placed(group, seen)] + group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum() + prevalence, incidence = self._design(group[X.columns], seen) + c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r")) + baseline = ISpline.at_quantiles(l, r, self.knots, self.degree) + self.seen_[key] = seen + self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy()) + self.neg_loglik_ = float(sum((f.neg_loglik for f in self.fits_.values()))) + self.converged_ = all((f.converged for f in self.fits_.values())) + return self + + def predict(self, X: pd.DataFrame) -> np.ndarray: + h = len(self.horizons_years) + out = np.full((len(X), 3 * h), np.nan) + z = norm.ppf(0.5 + self.interval_level / 2) + for key, index in self._groups(X): + if key not in self.fits_: + continue + members = X.iloc[index] + placed = self._placed(members, self.seen_[key]) + prevalence, incidence = self._design(members[placed], self.seen_[key]) + design = np.column_stack([prevalence, incidence]) + unique, inverse = np.unique(design, axis=0, return_inverse=True) + n_x = prevalence.shape[1] + point, variance = self.fits_[key].risk_with_variance( + unique[:, :n_x], unique[:, n_x:], self.horizons_years + ) + relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) + band = np.column_stack( + [ + point, + np.clip(point * np.exp(-z * relative), 0, 1), + np.clip(point * np.exp(z * relative), 0, 1), + ] + ) + out[index[placed]] = band[inverse.ravel()] + return out diff --git a/models/cacu/reports.py b/models/cacu/reports.py new file mode 100644 index 0000000..062c95f --- /dev/null +++ b/models/cacu/reports.py @@ -0,0 +1,186 @@ +import numpy as np +import pandas as pd +from scipy.stats import norm +from sklearn.metrics import brier_score_loss +from models import survival +from models.cacu.pim import Mixture +from models.cacu.specs import Logistic, Pim + +GRID_STEP = 0.1 +BOOTSTRAP = 200 +SEED = 20261122 +Z = norm.ppf(0.975) + + +def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict: + if isinstance(spec, survival.Spec): + return survival.technical_validation(spec, metrics, data) + members = data.get("coded", data.get("labelled")) + return { + "model": spec.name, + "method": spec.method, + "cohort": spec.cohort, + "split": "temporal: the earliest 70% of index dates train, the latest 30% test", + "members": len(members), + "index_dates": [str(members["index_date"].min()), str(members["index_date"].max())], + "metrics": metrics, + } + + +def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10): + finite = r[np.isfinite(r)] + support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]])) + low, high = (np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)) + inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None]) + patterns, counts = np.unique(inside, axis=0, return_counts=True) + p = np.full(len(support), 1 / len(support)) + for _ in range(iters): + weighted = patterns * p + new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum() + done = np.max(np.abs(new - p)) < tol + p = new + if done: + break + return (support, np.cumsum(p)) + + +def _at(support, cumulative, t) -> np.ndarray: + i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1 + return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)]) + + +def _label(feature: str, value) -> str: + if value is None or (isinstance(value, float) and np.isnan(value)): + return "NA" + if feature == "hpv_positive": + return "positive" if float(value) == 1.0 else "negative" + return str(value) + + +def _band(curve, variance) -> tuple[list, list]: + relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) + return ( + np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), + np.clip(curve * np.exp(Z * relative), 0, 1).tolist(), + ) + + +def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None: + key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else () + if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all(): + return None + prevalence, incidence = mixture._design(row, mixture.seen_[key]) + point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years) + return (point[0], variance[0]) + + +def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict: + if isinstance(spec, survival.Spec): + return survival.interpretability(spec, model, data) + if isinstance(spec, Logistic): + return _logistic(model, data["test"]) + coded = data["coded"] + full = Mixture(spec.horizons, spec.incidence_features, spec.strata, model.levels).fit( + coded[spec.features], coded[["c", "l", "r"]] + ) + members = coded.reset_index(drop=True) + labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features}) + horizons = np.asarray(spec.horizons, dtype=float) + grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6) + rng = np.random.default_rng(SEED) + groups = [] + for _, combination in labels.drop_duplicates().iterrows(): + mask = (labels == combination).all(axis=1).to_numpy() + group = members[mask] + c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r")) + support, cumulative = turnbull(c, l, r) + boot_grid, boot_h = ([], []) + for _ in range(BOOTSTRAP): + pick = rng.integers(0, len(group), len(group)) + s, cum = turnbull(c[pick], l[pick], r[pick]) + boot_grid.append(_at(s, cum, grid)) + boot_h.append(_at(s, cum, horizons)) + observed, var_observed = ( + _at(support, cumulative, horizons), + np.var(boot_h, axis=0, ddof=1), + ) + entry = { + "combination": combination.to_dict(), + "n": int(mask.sum()), + "prevalent": int((c == 1).sum()), + "incident": int(((c != 1) & np.isfinite(r)).sum()), + "observed": { + "years": grid.tolist(), + "risk": _at(support, cumulative, grid).tolist(), + "low": np.percentile(boot_grid, 2.5, axis=0).tolist(), + "high": np.percentile(boot_grid, 97.5, axis=0).tolist(), + }, + "predicted": None, + "expected_over_observed": [], + } + probe = group.iloc[[0]][spec.features] + at_grid, at_h = (_mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)) + if at_grid is not None: + low, high = _band(*at_grid) + entry["predicted"] = { + "years": grid.tolist(), + "risk": at_grid[0].tolist(), + "low": low, + "high": high, + } + for k, h in enumerate(horizons): + e = None if at_h is None else float(at_h[0][k]) + ratio = { + "years": float(h), + "expected": e, + "observed": float(observed[k]), + "ratio": None, + "low": None, + "high": None, + } + if e and observed[k] > 0 and np.isfinite(var_observed[k]): + se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2) + value = e / observed[k] + ratio |= { + "ratio": value, + "low": value * np.exp(-Z * se), + "high": value * np.exp(Z * se), + } + entry["expected_over_observed"].append(ratio) + groups.append(entry) + groups.sort(key=lambda g: (-g["n"], list(g["combination"].values()))) + return { + "model": spec.name, + "kind": "subgroups", + "bootstrap": BOOTSTRAP, + "seed": SEED, + "groups": groups, + } + + +def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict: + classifier, encoder = (model.named_steps["classify"], model.named_steps["encode"]) + names = encoder.get_feature_names_out() + p = test["p"] + deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop") + table = test.groupby(deciles, observed=True).agg( + n=("y", "size"), predicted=("p", "mean"), observed=("y", "mean") + ) + return { + "model": "logistic regression", + "kind": "coefficients", + "intercept": float(classifier.intercept_[0]), + "coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)), + "calibration": { + "brier": float(brier_score_loss(test["y"], p)), + "bins": [ + { + "range": str(k), + "n": int(v.n), + "predicted": float(v.predicted), + "observed": float(v.observed), + } + for k, v in table.iterrows() + ], + }, + } diff --git a/models/cacu/specs.py b/models/cacu/specs.py new file mode 100644 index 0000000..8527271 --- /dev/null +++ b/models/cacu/specs.py @@ -0,0 +1,224 @@ +from dataclasses import dataclass, field +from typing import Literal +import numpy as np +import pandas as pd +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import OneHotEncoder +from core import cacu +from models.cacu import features as f +from models.cacu.pim import Mixture +from models.survival import Spec, age_group + +HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0) +TRAIN_FRACTION = 0.7 +OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"] + + +def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame: + h = len(horizons) + scored = ~np.isnan(risks[:, :h]).any(axis=1) + members, risks = (members[scored], risks[scored]) + n = len(members) + frame = pd.DataFrame( + { + "person_id": np.repeat(members["person_id"].to_numpy(), h), + "index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h), + "horizon_years": np.tile(np.asarray(horizons, dtype=float), n), + "probability": risks[:, :h].ravel(), + } + ) + if risks.shape[1] == 3 * h: + frame["ci_low"], frame["ci_high"] = (risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()) + else: + frame["ci_low"] = frame["ci_high"] = np.nan + return frame[OUTPUT] + + +@dataclass(frozen=True) +class Pim: + name: str + cohort: str + grades: list[str] + cytology: dict[str, list[str]] + strata: tuple[str, ...] + incidence_features: tuple[str, ...] + history: dict | None = None + predict_at: Literal["index", "last_screening_cytology"] = "index" + horizons: tuple[float, ...] = HORIZONS + method: str = field(default="prevalence-incidence mixture", init=False) + + @property + def features(self) -> list[str]: + return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else []) + + def _history(self) -> dict | None: + return self.history and {**self.history, "cytology": self.cytology} + + def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]: + events = f.prepared(events) + coded = f.interval_coded(events, self.grades, self.cytology, self._history()) + train, test = f.split(coded, TRAIN_FRACTION) + levels = {"cytology": list(self.cytology)} + if self.history: + levels[self.history["feature"]] = list(self.history["levels"]) + mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels) + mixture.fit(train[self.features], train[["c", "l", "r"]]) + return (mixture, self.metrics(mixture, train, test), {"coded": coded}) + + def metrics(self, mixture: Mixture, train, test) -> dict: + found = { + "n_train": len(train), + "n_test": len(test), + "events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()), + "events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()), + "neg_loglik": mixture.neg_loglik_, + "converged": float(mixture.converged_), + } + risks = mixture.predict(test[self.features]) + for column, horizon in enumerate(self.horizons): + case = (test["c"] == 1) | (test["c"] != 1) & (test["r"] <= horizon) + free = (test["c"] == 0) & (test["l"] >= horizon) & ~case + status = np.where(case, 1.0, np.where(free, 0.0, np.nan)) + known = ~np.isnan(status) & ~np.isnan(risks[:, column]) + y, p, tag = (status[known], risks[known, column], f"{horizon:g}y") + found[f"n_known_{tag}"] = int(known.sum()) + if known.any(): + found[f"observed_{tag}"] = float(y.mean()) + found[f"expected_{tag}"] = float(p.mean()) + found[f"brier_{tag}"] = float(np.mean((p - y) ** 2)) + if len(np.unique(y)) == 2: + found[f"auc_{tag}"] = float(roc_auc_score(y, p)) + return found + + def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame: + events = f.prepared(events) + if self.predict_at == "last_screening_cytology": + chosen = f.last_screening_cytology(events) + events = events[events["person_id"].isin(chosen.index)] + events = events.assign(index_date=events["person_id"].map(chosen)) + members = f.index_results(events, self.cytology, self._history()) + members = members.sort_values("person_id", kind="stable").reset_index(drop=True) + return _rows(members, mixture.predict(members[self.features]), self.horizons) + + +@dataclass(frozen=True) +class Logistic: + name: str + cohort: str + grades: list[str] + predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18") + years: float = 1.0 + method: str = field(default="logistic regression", init=False) + + def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]: + events = f.prepared(events) + found = f.index_sample(events, list(self.predictors)) + outcome = f.windowed_outcome(events, self.grades, self.years, pd.Timestamp(follow_up_end)) + labelled = found.merge(outcome, on="person_id") + labelled = labelled[labelled["known"]].reset_index(drop=True) + train, test = f.split(labelled, TRAIN_FRACTION) + X = list(self.predictors) + model = Pipeline( + [ + ("encode", OneHotEncoder(handle_unknown="ignore")), + ("classify", LogisticRegression(max_iter=1000)), + ] + ) + model.fit(train[X], train["y"]) + p = model.predict_proba(test[X])[:, 1] + metrics = { + "n_train": len(train), + "n_test": len(test), + "events_train": float(train["y"].sum()), + "events_test": float(test["y"].sum()), + "auc": float(roc_auc_score(test["y"], p)), + "brier": float(brier_score_loss(test["y"], p)), + "positive_rate_train": float(train["y"].mean()), + "positive_rate_test": float(test["y"].mean()), + "mean_probability_test": float(p.mean()), + } + return (model, metrics, {"labelled": labelled, "test": test.assign(p=p)}) + + def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame: + members = f.index_sample(f.prepared(events), list(self.predictors)) + members = members.sort_values("person_id", kind="stable").reset_index(drop=True) + p = model.predict_proba(members[list(self.predictors)])[:, 1] + return _rows(members, p[:, None], (self.years,)) + + +def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: + found = pd.DataFrame(index=members.index) + found["age_group"] = age_group(events, members, (35, 45, 55)) + prior = events[events["date"] <= events["index_date"]] + names = list(cacu.KPNC) + severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes} + results = prior[(prior["type"] == "bethesda") & prior["value_code"].notna()] + latest = results[results["date"] == results.groupby("person_id")["date"].transform("max")] + ranks = latest["value_code"].map(severity).groupby(latest["person_id"]).max() + found["cytology"] = ranks.map(lambda r: None if pd.isna(r) else names[int(r)]) + hpv = prior[(prior["type"] == "hpv") & prior["value_code"].notna()] + hpv = hpv.sort_values(["date", "source_id"]) + found["hpv"] = hpv.groupby("person_id")["value_code"].last() + return found.astype(object) + + +_REFERRAL = { + "feature": "referral_grade", + "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS, + "levels": ["low", "high"], + "low": ["ASC-US/LSIL"], + "low_if_hpv_positive": ["NILM"], + "high": ["High Grade"], +} +MODELS = { + m.name: m + for m in [ + Pim( + "cin2_pim", + "cacu_cohort_surveillance", + cacu.CIN2_PLUS, + cacu.KPNC, + strata=("hpv_positive",), + incidence_features=("cytology",), + predict_at="last_screening_cytology", + ), + Pim( + "cancer_pim", + "cacu_cohort_surveillance", + cacu.CANCER, + cacu.KPNC, + strata=("hpv_positive",), + incidence_features=("cytology",), + predict_at="last_screening_cytology", + ), + Pim( + "cin2_pim_post_colposcopy", + "cacu_cohort_post_colposcopy", + cacu.CIN2_PLUS, + cacu.KPNC_3, + strata=("referral_grade",), + incidence_features=("cytology", "hpv_positive"), + history=_REFERRAL, + ), + Pim( + "cin2_pim_post_treatment", + "cacu_cohort_post_treatment", + cacu.CIN2_PLUS, + cacu.KPNC_3, + strata=(), + incidence_features=("cytology", "hpv_positive"), + ), + Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS), + Spec( + "survival", + "cacu_cohort_survival", + ("age_group", "cytology", "hpv"), + survival_covariates, + borders=(0, 12, 36, 60), + cap_months=60, + interval_level=0.95, + ), + ] +} diff --git a/models/cama/__init__.py b/models/cama/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/models/cama/__init__.py @@ -0,0 +1 @@ + diff --git a/models/cama/jobs.py b/models/cama/jobs.py new file mode 100644 index 0000000..cc01762 --- /dev/null +++ b/models/cama/jobs.py @@ -0,0 +1,6 @@ +from models import survival +from models.cama.specs import MODELS +from models.jobs import Jobs + +JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability) +train, score = (JOBS.train, JOBS.score) diff --git a/models/cama/recurrence/__init__.py b/models/cama/recurrence/__init__.py new file mode 100644 index 0000000..166a492 --- /dev/null +++ b/models/cama/recurrence/__init__.py @@ -0,0 +1,83 @@ +from dataclasses import dataclass +import joblib +import numpy as np +import pandas as pd +from models.cama.recurrence import calculator, cohorts, factors, modeling, reports + +SOURCES = ("metabric", "scanb") +HORIZONS = modeling.HORIZONS +SAVED = "metabric" + + +def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame: + return cohorts.prepare(source, rows).frame + + +@dataclass +class Recurrence: + cohort: str + horizons: tuple[int, ...] + covariates: list[str] + tables: dict[int, dict] + + def predict(self, X: pd.DataFrame) -> pd.DataFrame: + found = X[self.covariates].astype(object) + found = found.where(found.notna(), cohorts.UNKNOWN).astype(str) + dummies = pd.get_dummies(found).astype(float) + out = {} + for h in self.horizons: + t = self.tables[h] + p_lr = np.full(len(found), t["lr_prior"]) + if t["lr_terms"]: + x = dummies.reindex(columns=t["lr_terms"], fill_value=0.0).to_numpy() + logit = t["lr_constant"] + x @ np.asarray(t["lr_coefficients"]) + p_lr = 1 / (1 + np.exp(-logit)) + p_hbn = np.full(len(found), t["hbn_prior"]) + if t["hbn_parents"]: + keys = map(tuple, found[t["hbn_parents"]].to_numpy()) + p_hbn = np.array([t["hbn_cpt"].get(k, t["hbn_prior"]) for k in keys]) + out[f"recurrence_{h}m"] = (p_lr + p_hbn) / 2 + return pd.DataFrame(out, index=X.index) + + +def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: + 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]: + from models.cama.recurrence import site + + return fit({"site": site.prepare(rows)}, "site", "site", bootstrap) + + +def fit( + found: dict, saved: str, label: str, bootstrap: bool = True +) -> tuple[Recurrence, dict, dict]: + sources = list(found) + n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {} + try: + fits = modeling.fit(found, n_bootstrap) + drawn = {s: calculator.calculator(fits[s]) for s in sources} + finally: + joblib.externals.loky.get_reusable_executor().shutdown(wait=True) + table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True) + summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)] + auc = [row for s in sources for row in reports.auc_rows(fits[s])] + points = [row for s in sources for row in drawn[s][1]] + kept = fits[saved] + model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept)) + technical = { + "model": "recurrence", + "cohort": label, + "method": "stepwise logistic regression + Bayesian network (BDeu), averaged", + "rutinas": reports.routines(found, n_bootstrap), + "recurrencia_desarrollo": reports.development(auc, table, points, summary), + } + interpretability = { + "model": "recurrence", + "kind": "scenarios", + "recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]), + } + reports_ = {"technical_validation": technical, "interpretability": interpretability} + return (model, reports.metrics(auc), reports_) diff --git a/models/cama/recurrence/calculator.py b/models/cama/recurrence/calculator.py new file mode 100644 index 0000000..8349240 --- /dev/null +++ b/models/cama/recurrence/calculator.py @@ -0,0 +1,202 @@ +from dataclasses import dataclass +import numpy as np +import pandas as pd +import statsmodels.api as sm +from joblib import Parallel, delayed +from models import curves +from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit + +RESAMPLES = 200 +MIN_EVENTS = 15 +CAP_MONTHS = 72 +GRID_POINTS = 289 +LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"} +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"]}, + }, +} +SCENARIOS["site"] = SCENARIOS["scanb"] + + +def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: + return { + name: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in cond.items()]) + for name, cond in scenarios.items() + } + + +@dataclass +class Risk: + fitted: CohortFit + + def __post_init__(self): + frame, covariates = (self.fitted.cohort.frame, self.fitted.cohort.covariates) + self.n = len(frame) + self.X = pd.get_dummies(frame[covariates], drop_first=True).astype(float) + self.codes = {v: pd.factorize(frame[v])[0] for v in covariates} + self.levels = {v: int(c.max()) + 1 for v, c in self.codes.items()} + self.time, self.event = (frame["tiempo_meses"].to_numpy(), frame["evento"].to_numpy()) + + def _key(self, chosen, rows) -> np.ndarray: + key = np.zeros(len(rows), dtype=np.int64) + for p in chosen: + key = key * self.levels[p] + self.codes[p][rows] + return key + + def _combined(self, rows, horizon) -> np.ndarray | None: + t, e = (self.time[rows], self.event[rows]) + recurred = (e == 1) & (t <= horizon) + known = recurred | (t > horizon) + train, y = (rows[known], recurred[known].astype(int)) + split = self.fitted.horizons[horizon].split + p_lr = p_hbn = np.full(self.n, y.mean()) + if split.terms: + m = logit(y, self.X.iloc[train][split.terms].reset_index(drop=True), "add") + if m is None: + return None + p_lr = m.predict(sm.add_constant(self.X[split.terms], has_constant="add")).to_numpy() + if split.parents: + q = int(np.prod([self.levels[p] for p in split.parents])) + a = ESS / (2 * q) + key = self._key(split.parents, train) + table = (pd.Series(y, index=key).groupby(level=0).sum() + a) / ( + pd.Series(1, index=key).groupby(level=0).sum() + 2 * a + ) + everyone = self._key(split.parents, np.arange(self.n)) + p_hbn = table.reindex(everyone).fillna(y.mean()).to_numpy() + return (p_lr + p_hbn) / 2 + + def mean_risk(self, rows, scenario_masks) -> dict[str, np.ndarray] | None: + out = {name: np.full(len(HORIZONS), np.nan) for name in scenario_masks} + for j, h in enumerate(HORIZONS): + combined = self._combined(rows, h) + if combined is None: + return None + for name, mask in scenario_masks.items(): + inside = mask[rows] + if inside.any(): + out[name][j] = combined[rows][inside].mean() + return out + + +def _curves(months, event, observed): + d, c, _ = curves.life_table(months, event) + k, lam = curves.fit_weibull(d, c) + fractional = curves.fit_fractional(d, c, k, lam) + grid = np.linspace(0, CAP_MONTHS, GRID_POINTS) + return { + "km": dict( + zip(("S", "low", "high"), curves.kaplan_meier(months, event, observed), strict=True) + ), + "weibull": curves.weibull(grid, k, lam), + "weibull_fractional": curves.fractional(grid, k, *fractional), + "grid": grid, + } + + +def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]: + source = fitted.cohort.source + scenarios = SCENARIOS[source] if scenarios is None else scenarios + risk = Risk(fitted) + found = masks(fitted.cohort.frame, scenarios) + rng = np.random.default_rng(SEED) + samples = [np.arange(risk.n)] + [rng.integers(0, risk.n, risk.n) for _ in range(RESAMPLES)] + months = np.floor(risk.time).astype(int) + event = risk.event == 1 + drawn = {n: m for n, m in found.items() if m.any() and event[m].sum() >= MIN_EVENTS} + jobs = [delayed(_curves)(months[m], event[m], int(months[m].max())) for m in drawn.values()] + jobs += [delayed(risk.mean_risk)(rows, found) for rows in samples] + done = Parallel(n_jobs=-1)(jobs) + fitted_curves, (point, *resampled) = (done[: len(drawn)], done[len(drawn) :]) + replicas = [r for r in resampled if r is not None] + records, rows = ([], []) + for (name, mask), drawn_curves in zip(drawn.items(), fitted_curves, strict=True): + free = 1 - point[name] + risks = np.array([r[name] for r in replicas]) + low, high = 1 - np.nanpercentile(risks, [97.5, 2.5], axis=0) + observed, n, events = (int(months[mask].max()), int(mask.sum()), int(event[mask].sum())) + km, grid = (drawn_curves["km"], drawn_curves["grid"].tolist()) + records.append( + { + "cohorte": source, + "cohorte_nombre": LABELS[source], + "escenario": name, + "condiciones": scenarios[name], + "n": n, + "recaidas": events, + "horizons_months": list(HORIZONS), + "observado_hasta": observed, + "months_max": CAP_MONTHS, + "km": { + "months": list(range(observed + 1)), + **{k: v.tolist() for k, v in km.items()}, + }, + "weibull": {"t": grid, "S": drawn_curves["weibull"].tolist()}, + "weibull_fractional": {"t": grid, "S": drawn_curves["weibull_fractional"].tolist()}, + "points": { + "COMB": { + "S": free.tolist(), + "low": np.clip(low, 0, 1).tolist(), + "high": np.clip(high, 0, 1).tolist(), + } + }, + "bootstrap_replicas": len(replicas), + } + ) + for j, h in enumerate(HORIZONS): + rows.append( + { + "cohorte": source, + "subgrupo": name, + "n": n, + "recaidas": events, + "horizonte_meses": h, + "S_libre_LR_HBN": free[j], + "IC95_inf": low[j], + "IC95_sup": high[j], + "riesgo_recurrencia": 1 - free[j], + "S_libre_KM": km["S"][min(h, observed)] if h <= observed else np.nan, + "replicas_bootstrap": len(replicas), + } + ) + return (records, rows) diff --git a/models/cama/recurrence/cohorts.py b/models/cama/recurrence/cohorts.py new file mode 100644 index 0000000..aaab7dd --- /dev/null +++ b/models/cama/recurrence/cohorts.py @@ -0,0 +1,163 @@ +from dataclasses import dataclass +import pandas as pd +from scipy.stats.contingency import association + +UNKNOWN = "Desconocido" +V_MAX = 0.8 +DAYS_PER_MONTH = 30.4375 +AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) +SIZE = ([0, 20.01, 50.01, 10000.0], ["<=20 mm", "21-50 mm", ">50 mm"]) +NODES = ([0, 1, 4, 1000.0], ["0", "1-3", "4+"]) +GRADES = {"1": "1", "2": "2", "3": "3"} +FIXED = { + "metabric": ["paciente", "tiempo_meses", "evento"], + "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], +} +TREATMENT = { + "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], + "scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], +} +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", + }, +} +SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} +SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} + + +def _number(s: pd.Series) -> pd.Series: + return pd.to_numeric(s, errors="coerce") + + +def _text(s: pd.Series) -> pd.Series: + return s.astype(object).where(s.notna(), UNKNOWN).astype(str) + + +def _band(s: pd.Series, edges: list, labels: list) -> pd.Series: + return _text(pd.cut(s, edges, labels=labels, right=False).astype(object)) + + +def _in_order(rows: pd.DataFrame) -> pd.DataFrame: + return rows.sort_values("line", kind="stable").reset_index(drop=True) + + +def _metabric(rows: pd.DataFrame) -> pd.DataFrame: + d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"]) + d = d.reset_index(drop=True) + out = pd.DataFrame({"paciente": d["patient_id"]}) + out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"]) + out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int) + out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE) + out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE) + out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES) + out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES)) + load = _number(d["mutation_count"]) + q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() + edges = [-1, q1 + 1e-09, q2 + 1e-09, 1000000.0] + 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) + out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE) + out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES)) + out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES)) + for name, column in PASSTHROUGH["scanb"].items(): + out[name] = _text(d[column]) + return out + + +def cramers_v(a: pd.Series, b: pd.Series) -> float: + table = pd.crosstab(a, b).to_numpy() + return association(table, method="cramer") if min(table.shape) > 1 else 0.0 + + +def collinear(frame: pd.DataFrame, candidates: list[str], v_max: float = V_MAX) -> list[str]: + pairs = sorted( + ( + (cramers_v(frame[a], frame[b]), a, b) + for i, a in enumerate(candidates) + for b in candidates[i + 1 :] + ), + reverse=True, + ) + unknown = {c: (frame[c] == UNKNOWN).mean() for c in candidates} + dropped = [] + for v, a, b in pairs: + if v < v_max: + break + if a not in dropped and b not in dropped: + dropped.append(a if unknown[a] >= unknown[b] else b) + return dropped + + +@dataclass(frozen=True) +class Cohort: + source: str + frame: pd.DataFrame + covariates: list[str] + treatment: list[str] + eliminated: list[str] + + @property + def intrinsic(self) -> list[str]: + return [c for c in self.covariates if c not in self.treatment] + + +def prepare(source: str, raw: pd.DataFrame) -> Cohort: + full = {"metabric": _metabric, "scanb": _scanb}[source](raw) + fixed, treatment = (FIXED[source], TREATMENT[source]) + covariates = [c for c in full.columns if c not in fixed] + dropped = collinear(full, [c for c in covariates if c not in treatment]) + kept = [c for c in covariates if c not in dropped] + return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped) + + +def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: + t, event = (frame["tiempo_meses"], frame["evento"] == 1) + found = frame[event & (t <= horizon) | (t > horizon)].reset_index(drop=True) + found["y"] = ((found["evento"] == 1) & (found["tiempo_meses"] <= horizon)).astype(int) + return found + + +def unknown_shares(cohort: Cohort) -> dict[str, float]: + return {c: float((cohort.frame[c] == UNKNOWN).mean()) for c in cohort.covariates} diff --git a/models/cama/recurrence/factors.py b/models/cama/recurrence/factors.py new file mode 100644 index 0000000..cd97e85 --- /dev/null +++ b/models/cama/recurrence/factors.py @@ -0,0 +1,113 @@ +import warnings +import numpy as np +import pandas as pd +from models import factors as rated +from models.cama.recurrence.calculator import SCENARIOS, masks +from models.cama.recurrence.cohorts import UNKNOWN, at_horizon +from models.cama.recurrence.modeling import CohortFit +from models.factors import FREQ_MIN, ORDER + +OR = "OR_recurrencia" +SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S") +TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" +COLUMNS = [ + "cohorte", + "horizonte_meses", + "tipo", + "variable", + "categoria", + "referencia", + "n_categoria", + OR, + "IC95_inf", + "IC95_sup", + "p", + "p_ajustado_BH", + "freq_seleccion_bootstrap", + "en_manta_markov", + *SURVIVAL, + "delta_IC95_inf", + "delta_IC95_sup", + "c1_or", + "c2_estabilidad", + "c3_manta_markov", + "c4_supervivencia", + "criterios_cumplidos", + "clasificacion", +] +DESCRIBING = rated.DESCRIBING + + +def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame: + cohort = fitted.cohort + frame = at_horizon(cohort.frame, horizon) + data, y = (frame[cohort.covariates].astype(str), frame["y"].to_numpy()) + reference = {v: data[v].value_counts().idxmax() for v in cohort.covariates} + t, everyone = (cohort.frame["tiempo_meses"].to_numpy(), cohort.frame[cohort.covariates]) + months = np.floor(np.minimum(t, horizon + 1)).astype(int) + event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy() + + def complete(table, variables): + return rated.complete( + table, variables, reference, everyone, months, event, horizon, SURVIVAL + ) + + intrinsic, treatment = (cohort.intrinsic, cohort.treatment) + tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic) + hz = fitted.horizons[horizon] + tab["freq_seleccion_bootstrap"] = tab["variable"].map( + lambda v: np.nan if selection is None else selection.get(v, 0.0) + ) + tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN + tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents) + tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN) + tab["tipo"] = "factor de riesgo" + if treatment: + both = intrinsic + treatment + tr = rated.odds_ratios(data, y, both, reference, OR) + of = tr["termino"].map(lambda x: rated.variable_of(x, both)) + tr = complete( + tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment + ) + tr["tipo"], tr["clasificacion"] = ("tratamiento", TREATMENT_CLASS) + tab = pd.concat([tab, tr], ignore_index=True) + tab["cohorte"], tab["horizonte_meses"] = (cohort.source, horizon) + return tab + + +def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFrame: + if selection is None: + covariates = fitted.cohort.covariates + selection = {h: hz.selection(covariates) for h, hz in fitted.horizons.items()} + with warnings.catch_warnings(), np.errstate(over="ignore"): + warnings.simplefilter("ignore") + found = [_horizon(fitted, h, selection[h]) for h in fitted.horizons] + tab = pd.concat(found, ignore_index=True) + tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) + tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5) + keys = ["horizonte_meses", "_kind", "_order", OR] + tab = tab.sort_values(keys, ascending=[True, True, True, False]) + return tab[COLUMNS].round(4) + + +def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]: + frame, source = (fitted.cohort.frame, fitted.cohort.source) + scenarios = SCENARIOS[source] + found = rated.classified(factors[factors["cohorte"] == source]) + rows = [] + for name, mask in masks(frame, scenarios).items(): + if not mask.any() or found.empty: + continue + definition = "; ".join((f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())) + for h in fitted.horizons: + rows.append( + { + "cohorte": source, + "escenario": name, + "definicion": definition, + "n_escenario": int(mask.sum()), + "horizonte_meses": h, + **rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]), + } + ) + return rows diff --git a/models/cama/recurrence/modeling.py b/models/cama/recurrence/modeling.py new file mode 100644 index 0000000..e67127d --- /dev/null +++ b/models/cama/recurrence/modeling.py @@ -0,0 +1,247 @@ +import warnings +from dataclasses import dataclass, field +import numpy as np +import pandas as pd +import statsmodels.api as sm +from joblib import Parallel, delayed +from lifelines import CoxPHFitter +from lifelines.utils import concordance_index +from pgmpy.structure_score import BDeu +from sklearn.metrics import roc_auc_score +from sklearn.model_selection import train_test_split +from models.cama.recurrence.cohorts import Cohort, at_horizon +from models.factors import variable_of + +HORIZONS = (12, 36, 60) +SEED = 42 +TEST_SIZE = 0.3 +ESS = 10 +MAX_PARENTS = 6 +ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = (0.1, 0.1, 0.15) +MAX_STEPS = 200 +COX_PENALIZER = 0.05 +COX_MIN_COUNT = 10 +N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40} + + +def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: + X = pd.get_dummies(frame[covariates], drop_first=True).astype(float) + return X.loc[:, X.nunique() > 1] + + +def logit(y, X: pd.DataFrame, has_constant: str = "skip"): + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + X = sm.add_constant(X, has_constant=has_constant) + return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300) + except Exception: + return None + + +def stepwise(X: pd.DataFrame, y) -> list[str]: + included = [] + for _ in range(MAX_STEPS): + changed, best, best_p = (False, None, ALPHA_IN) + for c in X.columns: + if c in included: + continue + m = logit(y, X[included + [c]]) + if m is not None and m.pvalues[c] < best_p: + best, best_p = (c, m.pvalues[c]) + if best is not None: + included.append(best) + changed = True + if included and (m := logit(y, X[included])) is not None: + p = m.pvalues.drop("const") + if p.max() > ALPHA_OUT: + included.remove(p.idxmax()) + changed = True + if not changed: + break + return included + + +def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]): + X = encode(pd.concat([train, test]), covariates) + X_train = X.loc[train.index] + X_train = X_train.loc[:, X_train.nunique() > 1] + y = train["y"] + candidates = [ + c + for c in X_train.columns + if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER + ] + terms = stepwise(X_train[candidates], y) if candidates else [] + if not terms: + return ([], np.full(len(test), y.mean())) + m = logit(y, X_train[terms]) + X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add") + return (terms, m.predict(X_test).to_numpy()) + + +def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame: + table = frame[covariates].astype(str) + table["outcome"] = frame["y"].astype(int).astype(str) + return table + + +def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]: + score = BDeu(table, equivalent_sample_size=ESS) + chosen, current = ([], score.local_score("outcome", ())) + while len(chosen) < MAX_PARENTS: + best, gain = (None, 0.0) + for c in [c for c in covariates if c not in chosen]: + g = score.local_score("outcome", (*chosen, c)) - current + if g > gain: + best, gain = (c, g) + if best is None: + break + chosen.append(best) + current += gain + return chosen + + +def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]: + q = q or int(np.prod([table[p].nunique() for p in chosen])) + a = ESS / (2 * q) + counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size") + return { + k if isinstance(k, tuple) else (k,): float((r.n1 + a) / (r.n + 2 * a)) + for k, r in counts.iterrows() + } + + +def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray: + rate = (train["outcome"] == "1").mean() + if not chosen: + return np.full(len(test), rate) + table = cpt(train, chosen) + return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())]) + + +@dataclass(frozen=True) +class Split: + terms: list[str] + parents: list[str] + auc_lr: float + auc_hbn: float + + +def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split: + train, test = train_test_split( + frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"] + ) + terms, p_lr = lr(train, test, covariates) + bn_train, bn_test = (bn_table(train, covariates), bn_table(test, covariates)) + chosen = parents(bn_train, covariates) + p_hbn = hbn(bn_train, bn_test, chosen) + return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn)) + + +def _replicate(frame, covariates, rows, b) -> Split | None: + try: + return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b) + except Exception: + return None + + +def c_index(cohort: Cohort) -> float: + time_event = ["tiempo_meses", "evento"] + X = pd.get_dummies( + cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True + ).astype(float) + X = X.loc[:, X.nunique() > 1] + train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"]) + n = len(train) + keep = [ + c + for c in X.columns + if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT + ] + cox = CoxPHFitter(penalizer=COX_PENALIZER) + cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5}) + risk = cox.predict_partial_hazard(test[keep]) + return float(concordance_index(test["tiempo_meses"], -risk, test["evento"])) + + +@dataclass +class Horizon: + n: int + events: int + split: Split + replicates: list[Split] = field(default_factory=list) + + @property + def aucs(self) -> np.ndarray: + return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2) + + def selection(self, covariates: list[str]) -> dict[str, float] | None: + if not self.replicates: + return None + counts = {} + for r in self.replicates: + for v in {variable_of(t, covariates) for t in r.terms}: + counts[v] = counts.get(v, 0) + 1 + return {v: k / len(self.replicates) for v, k in counts.items()} + + +@dataclass +class CohortFit: + cohort: Cohort + c_index: float + horizons: dict[int, Horizon] + + +def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]: + frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS} + tasks = [] + for (s, h), frame in frames.items(): + rng = np.random.default_rng(SEED) + rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))] + tasks += [ + ((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b)) + for b, r in enumerate(rows) + ] + tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates))) + tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()] + done = Parallel(n_jobs=-1)((delayed(f)(*args) for _, f, args in reversed(tasks))) + results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True)) + out = {} + for s, cohort in cohorts.items(): + horizons = {} + for h in HORIZONS: + frame = frames[s, h] + reps = [results[s, h, b] for b in range(n_bootstrap.get(s, 0))] + horizons[h] = Horizon( + len(frame), + int(frame["y"].sum()), + results[s, h, "split"], + [r for r in reps if r is not None], + ) + out[s] = CohortFit(cohort, results[s, None, "cox"], horizons) + return out + + +def tables(fitted: CohortFit) -> dict[int, dict]: + found = {} + for h, hz in fitted.horizons.items(): + frame = at_horizon(fitted.cohort.frame, h) + covariates, terms, chosen = (fitted.cohort.covariates, hz.split.terms, hz.split.parents) + prior = float(frame["y"].mean()) + entry = { + "lr_prior": prior, + "lr_terms": terms, + "lr_constant": 0.0, + "lr_coefficients": [], + "hbn_parents": chosen, + "hbn_prior": prior, + "hbn_cpt": {}, + } + if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None: + entry["lr_constant"] = float(m.params["const"]) + entry["lr_coefficients"] = [float(m.params[t]) for t in terms] + if chosen: + entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen) + found[h] = entry + return found diff --git a/models/cama/recurrence/reports.py b/models/cama/recurrence/reports.py new file mode 100644 index 0000000..8486a69 --- /dev/null +++ b/models/cama/recurrence/reports.py @@ -0,0 +1,150 @@ +import numpy as np +import pandas as pd +from models.cama.recurrence.calculator import MIN_EVENTS, RESAMPLES +from models.cama.recurrence.cohorts import UNKNOWN, Cohort, unknown_shares +from models.cama.recurrence.modeling import ( + ALPHA_IN, + ALPHA_OUT, + COX_PENALIZER, + ESS, + HORIZONS, + MAX_PARENTS, + CohortFit, +) + +VERSION = 1 +AUC_COLUMNS = [ + "cohorte", + "horizonte_meses", + "modelo", + "n_modelo", + "recurrencias", + "AUC_validacion_interna", + "AUC_bootstrap_medio", + "AUC_bootstrap_IC95_inf", + "AUC_bootstrap_IC95_sup", + "replicas_bootstrap", +] + + +def table(rows, columns=None) -> dict: + frame = pd.DataFrame(rows, columns=columns).replace([np.inf, -np.inf], np.nan).astype(object) + return { + "columnas": [str(c) for c in frame.columns], + "filas": frame.where(frame.notna(), None).to_dict("records"), + } + + +def auc_rows(fitted: CohortFit) -> list[dict]: + source, rows = (fitted.cohort.source, []) + for h, hz in fitted.horizons.items(): + for j, (name, internal) in enumerate((("LR", hz.split.auc_lr), ("HBN", hz.split.auc_hbn))): + aucs = hz.aucs[:, j] + boot = ( + [np.nanmean(aucs), *np.nanpercentile(aucs, [2.5, 97.5])] + if len(aucs) + else [None] * 3 + ) + rows.append( + { + "cohorte": source, + "horizonte_meses": h, + "modelo": name, + "n_modelo": hz.n, + "recurrencias": hz.events, + "AUC_validacion_interna": internal, + **dict(zip(AUC_COLUMNS[6:9], boot, strict=True)), + "replicas_bootstrap": len(aucs) if len(aucs) else None, + } + ) + frame = fitted.cohort.frame + rows.append( + { + "cohorte": source, + "horizonte_meses": "completo", + "modelo": "Cox penalizado (C-index)", + "n_modelo": len(frame), + "recurrencias": int(frame["evento"].sum()), + "AUC_validacion_interna": fitted.c_index, + } + ) + return [{k: round(v, 4) if isinstance(v, float) else v for k, v in r.items()} for r in rows] + + +def metrics(auc: list[dict]) -> dict[str, float]: + found = {} + for r in auc: + if r["horizonte_meses"] == "completo": + found[f"{r['cohorte']}.c_index_cox"] = float(r["AUC_validacion_interna"]) + continue + tag = f"{r['cohorte']}.auc_{r['modelo']}_{r['horizonte_meses']}m" + found[tag] = float(r["AUC_validacion_interna"]) + if r.get("AUC_bootstrap_medio") is not None: + found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"]) + return found + + +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: + return { + "MUESTREO": { + "cohortes": { + s: { + "pacientes": len(c.frame), + "recaidas": int(c.frame["evento"].sum()), + "covariables": len(c.covariates), + "eliminadas_por_colinealidad": c.eliminated, + } + for s, c in cohorts.items() + }, + **(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING), + }, + "DATOS_FALTANTES": { + "criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); no se imputa ni se descarta", + "desconocidos_por_covariable": {s: unknown_shares(c) for s, c in cohorts.items()}, + }, + "METODO_ANALITICO": { + "modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte", + "horizontes_meses": list(HORIZONS), + "alfa_entrada": ALPHA_IN, + "alfa_salida": ALPHA_OUT, + "ess_bdeu": ESS, + "maximo_de_padres": MAX_PARENTS, + "cox_penalizado": COX_PENALIZER, + "combinacion": "promedio de la LR y la HBN", + }, + "BALANCE_CLASES": { + "aplica": False, + "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea", + }, + "CONFIANZA_SALIDA": { + "salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap", + "replicas": {**{s: n_bootstrap.get(s, 0) for s in cohorts}, "calculadora": RESAMPLES}, + "eventos_minimos_por_escenario": MIN_EVENTS, + }, + } + + +def development(auc, factors: pd.DataFrame, points: list[dict], summary: list[dict]) -> dict: + return { + "version": VERSION, + "tablas": { + "auc": table(auc, AUC_COLUMNS), + "factores_riesgo": table(factors), + "calculadora": table(pd.DataFrame(points).round(4)), + "escenarios_resumen": table(summary), + }, + } + + +def figures(records: list[dict]) -> dict: + return {"version": VERSION, "horizons_months": list(HORIZONS), "escenarios": records} diff --git a/models/cama/recurrence/site.py b/models/cama/recurrence/site.py new file mode 100644 index 0000000..9033d93 --- /dev/null +++ b/models/cama/recurrence/site.py @@ -0,0 +1,105 @@ +import numpy as np +import pandas as pd +from models.cama.recurrence import cohorts +from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear + +RESULT_DAYS = 30 +TREATMENT_DAYS = 365 +KI67_HIGH = 20.0 +STAGE_GROUP = { + "0": "0", + "I": "I", + "IA": "I", + "IB": "I", + "II": "II", + "IIA": "II", + "IIB": "II", + "III": "III", + "IIIA": "III", + "IIIB": "III", + "IIIC": "III", + "IV": "IV", +} +RECEPTOR = {"positive": "Positive", "negative": "Negative"} +SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"} +TREATMENTS = { + "Quimioterapia": "chemotherapy", + "Radioterapia": "radiotherapy", + "Hormonoterapia": "hormone_therapy", + "AntiHER2": "anti_her2", +} +FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] +TREATMENT = ["Cirugia", *TREATMENTS] + + +def subtype(er, pr, her2, ki67) -> str: + hormone = "positive" in (er, pr) + if her2 == "positive": + return "Luminal B HER2+" if hormone else "Non-luminal HER2+" + if her2 != "negative": + return UNKNOWN + if not hormone: + return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN + if ki67 is None or ki67 != ki67: + return UNKNOWN + return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-" + + +def frame(events: pd.DataFrame, as_of) -> pd.DataFrame: + events = events.assign( + date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"]) + ) + members = events.groupby("person_id")["index_date"].first() + days = (events["date"] - events["index_date"]).dt.days + cut = pd.Timestamp(as_of) + after = events[(days > 0) & (events["date"] <= cut)] + first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min() + death = events[(events["type"] == "death") & (events["date"] <= cut)] + death = death.groupby("person_id")["date"].min().reindex(members.index) + end = first_recurrence.reindex(members.index).fillna(death).fillna(cut) + out = pd.DataFrame(index=members.index) + out["paciente"] = members.index + out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH + out["evento"] = first_recurrence.reindex(members.index).notna().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"]) + 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() + birth = events[events["type"] == "birth"].groupby("person_id")["date"].min() + age = (members - birth.reindex(members.index)).dt.days / 365.25 + out["Edad"] = _band(age, *cohorts.AGE) + out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE) + out["Ganglios_positivos"] = _band( + number("positive_nodes").reindex(members.index), *cohorts.NODES + ) + 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")} + ki67 = number("ki67_pct").reindex(members.index) + out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR)) + out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR)) + out["HER2"] = _text(receptors["her2"].map(RECEPTOR)) + 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["Subtipo_clinico"] = [ + 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["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP)) + course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)] + given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index) + given = given.apply(lambda g: g if isinstance(g, set) else set()) + out["Cirugia"] = given.apply( + lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None") + ) + for name, kind in TREATMENTS.items(): + out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No") + return out.reset_index(drop=True) + + +def prepare(rows: pd.DataFrame) -> Cohort: + 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]) + kept = [c for c in covariates if c not in dropped] + treatment = [c for c in TREATMENT if c in kept] + return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped) diff --git a/models/cama/specs.py b/models/cama/specs.py new file mode 100644 index 0000000..5a8e10f --- /dev/null +++ b/models/cama/specs.py @@ -0,0 +1,166 @@ +from dataclasses import dataclass, field +from datetime import date +import pandas as pd +from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band + +RESULTS = ("histologic_type", "grade", "er", "pr", "her2") +RESULT_DAYS = 30 +TREATMENT_DAYS = 365 +STAGE_GROUP = { + "0": "0", + "I": "I", + "IA": "I", + "IB": "I", + "II": "II", + "IIA": "II", + "IIB": "II", + "III": "III", + "IIIA": "III", + "IIIB": "III", + "IIIC": "III", + "IV": "IV", +} +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) +CONSERVING = ("surgery", "==", "breast_conserving_surgery") + + +def _younger(years): + return ("age", "<", years) + + +def _older(years): + return ("age", ">=", years) + + +SCENARIOS = { + "HER2+ · ≥60 años · estadio III–IV (Alto)": (HER2_POS, _older(60), STAGE_III_IV), + "HER2+ · <60 años · estadio 0–II (Bajo)": (HER2_POS, _younger(60), STAGE_0_II), + "Estadio IV": (("stage", "in", ("IV",)),), + "Estadio I": (("stage", "in", ("I",)),), + "≥ 75 años": (_older(75),), + "< 45 años": (_younger(45),), + "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": ( + _younger(45), + HER2_NEG, + STAGE_0_II, + CONSERVING, + ), + "HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING), + "HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING), + "Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II), + "Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG), + "Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II), + "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": ( + _older(65), + HER2_NEG, + STAGE_0_II, + CONSERVING, + ), +} + + +def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: + found = pd.DataFrame(index=members.index) + found["age_group"] = age_group(events, members, (45, 60, 75)) + birth = events[events["type"] == "birth"].groupby("person_id")["date"].min() + found["age"] = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR + days = (events["date"] - events["index_date"]).dt.days + near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"]) + for kind in RESULTS: + found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first() + for name, kind, cuts in ( + ("ki67_group", "ki67_pct", (14, 20)), + ("size_group", "size_mm", (20, 50)), + ): + value = near[near["type"] == kind].groupby("person_id")["value_num"].first() + found[name] = band(value.reindex(found.index), list(cuts)) + stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first() + found["stage"] = stage.reindex(found.index).map(STAGE_GROUP) + course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)] + given = course.groupby("person_id")["value_code"].agg(set).reindex(found.index) + given = given.apply(lambda g: g if isinstance(g, set) else set()) + found["surgery"] = given.apply(lambda g: next((s for s in reversed(SURGERY) if s in g), "none")) + for name in ("chemotherapy", "radiotherapy"): + found[name] = given.apply(lambda g, n=name: "yes" if n in g else "no") + return found + + +@dataclass(frozen=True) +class SiteRecurrence: + name: str + cohort: str = "cama_cohort_recurrence" + slow: bool = True + reports: bool = True + method: str = field(default="stepwise logistic regression + Bayesian network", init=False) + + def train(self, events, as_of=None) -> tuple: + from models.cama import recurrence + from models.cama.recurrence import site + + return recurrence.train_site(site.frame(events, as_of or date.today())) + + def predict(self, model, events) -> pd.DataFrame: + from models.cama.recurrence import calculator, site + + members = site.frame(events, date.today()) + found = model.predict(members) + index = events.groupby("person_id")["index_date"].first() + masks = calculator.masks(members, calculator.SCENARIOS["site"]) + named = [ + SCENARIO_SEPARATOR.join((n for n, m in masks.items() if m[i])) or None + for i in range(len(members)) + ] + rows = [] + for i, person in enumerate(members["paciente"]): + for h in model.horizons: + rows.append( + { + "person_id": person, + "index_date": pd.Timestamp(index[person]).date(), + "horizon_years": h / 12, + "probability": found[f"recurrence_{h}m"][i], + "ci_low": None, + "ci_high": None, + "scenarios": named[i], + } + ) + return pd.DataFrame(rows, columns=OUTPUT) + + +MODELS = { + "survival": Spec( + name="survival", + cohort="cama_cohort_survival", + features=( + "age_group", + *RESULTS, + "ki67_group", + "size_group", + "stage", + "surgery", + "chemotherapy", + "radiotherapy", + ), + covariates=covariates, + parents=( + "stage", + "histologic_type", + "surgery", + "chemotherapy", + "radiotherapy", + "age_group", + ), + borders=(0, 6, 12, 18), + cap_months=24, + scenarios=SCENARIOS, + scenario_columns=("age",), + treatments=("surgery", "chemotherapy", "radiotherapy"), + notes=( + 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.", + ), + ), + "recurrence": SiteRecurrence("recurrence"), +} diff --git a/models/cluster.py b/models/cluster.py new file mode 100644 index 0000000..6f46f42 --- /dev/null +++ b/models/cluster.py @@ -0,0 +1,41 @@ +import os +from collections.abc import Callable, Iterable +from importlib.util import find_spec +from typing import Any +from joblib import Parallel, delayed + + +def jobs() -> int: + return int(os.environ.get("BATCH_JOBS", "-1")) + + +def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]: + if find_spec("distributed") is None: + return Parallel(n_jobs=jobs())((delayed(task)(*a) for a in arguments)) + from distributed import Client, LocalCluster, as_completed + + address = os.environ.get("DASK_SCHEDULER_ADDRESS") + where = address or LocalCluster(threads_per_worker=1, dashboard_address=None) + try: + with Client(where) as client: + limit = jobs() if jobs() > 0 else sum(client.nthreads().values()) + pending = iter(enumerate(arguments)) + results: dict[int, Any] = {} + order: dict[Any, int] = {} + + def submit() -> Any | None: + if (item := next(pending, None)) is None: + return None + future = client.submit(task, *item[1], pure=False) + order[future] = item[0] + return future + + running = as_completed([f for f in (submit() for _ in range(limit)) if f]) + for done in running: + results[order.pop(done)] = done.result() + if (future := submit()) is not None: + running.add(future) + return [results[i] for i in range(len(results))] + finally: + if not address: + where.close() diff --git a/models/curves.py b/models/curves.py new file mode 100644 index 0000000..1cbb378 --- /dev/null +++ b/models/curves.py @@ -0,0 +1,156 @@ +import numpy as np +from scipy.optimize import minimize, minimize_scalar +from scipy.special import beta as beta_function +from scipy.special import betainc, gammaln + +Z = 1.96 +INVALID = 1000000000000.0 + + +def life_table(months: np.ndarray, event: np.ndarray, length: int = 0): + months, event = (np.asarray(months, int), np.asarray(event, bool)) + length = max(length, int(months.max()) + 2) + d = np.bincount(months[event], minlength=length) + c = np.bincount(months[~event], minlength=length) + at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]]) + return (d, c, at_risk) + + +def kaplan_meier(months, event, until: int): + d, _, n = life_table(months, event, until + 1) + with np.errstate(divide="ignore", invalid="ignore"): + q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) + v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0) + S = np.concatenate([[1.0], np.cumprod(q)])[: until + 1] + se = np.sqrt(np.concatenate([[0.0], np.cumsum(v)])[: until + 1]) / np.abs(np.log(S)) + inside = (S > 0) & (S < 1) + return ( + S, + np.where(inside, S ** np.exp(Z * se), S), + np.where(inside, S ** np.exp(-Z * se), S), + ) + + +def _nll(survival, d, c) -> float: + T = len(d) + both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5])) + S, mid = (both[: T + 1], both[T + 1 :]) + if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))): + return INVALID + p = np.clip(S[:-1] - S[1:], 1e-300, None) + return -(np.sum(d * np.log(p)) + np.sum(c * np.log(np.clip(mid, 1e-300, None)))) + + +def weibull(t, k, lam): + return np.exp(-((np.asarray(t, float) / lam) ** k)) + + +def fit_weibull(d, c) -> tuple[float, float]: + best = None + for k0 in (0.7, 1.0, 1.5): + for l0 in (50.0, 200.0, 1000.0): + r = minimize( + lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c), + [np.log(k0), np.log(l0)], + method="Nelder-Mead", + options={"xatol": 1e-05, "fatol": 1e-08, "maxiter": 2000}, + ) + r = _converged(r, "Weibull") + best = r if best is None or r.fun < best.fun else best + k, lam = np.exp(best.x) + return (float(k), float(lam)) + + +STEPS = 800 + + +class NotConverged(RuntimeError): + pass + + +def _converged(r, what: str): + if not r.success: + raise NotConverged(f"{what}: {r.message}") + return r + + +def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray: + t = np.atleast_1d(np.asarray(t, float)) + e = rho + s + top = float(t.max()) if t.size else 0.0 + if top <= 0: + return np.ones_like(t) + w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c + w[-1] = top**e + grid = w ** (1 / e) + y = np.ones(STEPS + 1) + kappa = c / np.exp(gammaln(rho)) + b0, be = (beta_function(s + 1, rho), beta_function(s + e + 1, rho)) + dw = np.diff(w) + for n in range(1, STEPS + 1): + x = grid[: n + 1] / grid[n] + i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x)) + ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x)) + slope = (ie - w[:n] * i0) / dw[:n] + own, next_ = (i0 - slope, slope) + known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n]) + y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1]) + return np.interp(t**e, w, y) + + +def fractional(t, k, alpha, beta, lam) -> np.ndarray: + t = np.atleast_1d(np.asarray(t, float)) + s = k + alpha - 2 + if k + alpha <= 1 or s + beta <= 0: + return np.full(t.shape, np.nan) + c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2) + return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0) + + +def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]: + 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, ...]: + floor = max(0.0, 1.0 - k) + 1e-06 + top = 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(10000000.0)) + + def unpack(p): + return (floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))) + + def profile(p) -> tuple[float, float]: + a, b = unpack(p) + if k + a <= 1 or k + a + b <= 2: + return (INVALID, np.nan) + rho, s, scale = _shape(k, a, b) + e = rho + s + z_top = scale * top**e + z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1)) + g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0) + + def nll(log_lam: float) -> float: + found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g) + return _nll(lambda t: found, d, c) + + coarse = np.linspace(*lambdas, 141) + i = int(np.argmin([nll(x) for x in coarse])) + r = minimize_scalar( + nll, + bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]), + method="bounded", + options={"xatol": 1e-09}, + ) + return (float(r.fun), float(r.x)) + + 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)] + best = None + for p0 in starts: + 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 = _converged(r, "fractional Weibull") + best = r if best is None or r.fun < best.fun else best + a, b = unpack(best.x) + return (float(a), float(b), float(np.exp(profile(best.x)[1]))) diff --git a/models/definitions.py b/models/definitions.py new file mode 100644 index 0000000..dc18117 --- /dev/null +++ b/models/definitions.py @@ -0,0 +1,122 @@ +import importlib +import os +from datetime import date +import dagster as dg +from models import graph +from models.jobs import EmptyCohort +from persistance import backup as backups +from persistance import config_log, silver + +WRITES = {"writes": "platform"} + + +class PipelineRun(dg.Config): + pipeline: str + version: int | None = None + + +@dg.op +def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int: + version, pipeline = config_log.get(config.pipeline, config.version) + context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes") + graph.run(config.pipeline, pipeline, log=context.log.info) + return version + + +@dg.job(tags=WRITES) +def ingest(): + run_pipeline() + + +def _jobs(domain: str): + try: + return importlib.import_module(f"models.{domain}.jobs") + except ModuleNotFoundError as e: + raise ValueError(f"{domain} has no models") from e + + +class Training(dg.Config): + domain: str + models: list[str] = [] + as_of: str | None = None + + +@dg.op +def train_models(context: dg.OpExecutionContext, config: Training) -> dict: + jobs = _jobs(config.domain) + as_of = date.fromisoformat(config.as_of) if config.as_of else None + found = {} + for name in config.models or jobs.JOBS.routine(): + try: + found[name] = jobs.train(name, as_of) + except EmptyCohort as e: + found[name] = None + context.log.warning(f"{e}: not trained") + continue + context.log.info(f"{config.domain}.{name}: version {found[name]}") + return found + + +@dg.job +def train(): + train_models() + + +class Scoring(dg.Config): + domain: str + models: list[str] = [] + + +@dg.op +def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict: + jobs = _jobs(config.domain) + found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()} + for name, version in found.items(): + context.log.info(f"{name}: " + (f"version {version}" if version else "no champion")) + silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"]) + return found + + +@dg.job(tags=WRITES) +def score(): + score_models() + + +class Analysis(dg.Config): + domain: str + + +@dg.op +def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int: + found = _jobs(config.domain).analyze() + context.log.info(f"{config.domain}: {found} analysed") + return found + + +@dg.job(tags=WRITES) +def analyze(): + analyze_studies() + + +@dg.op +def make_backup(context: dg.OpExecutionContext) -> str: + folder = backups.create() + context.log.info(f"backup {folder}") + return str(folder) + + +@dg.job(tags=WRITES) +def backup(): + make_backup() + + +nightly = ( + [ + dg.ScheduleDefinition( + job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING + ) + ] + if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *")) + else [] +) +defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly) diff --git a/models/factors.py b/models/factors.py new file mode 100644 index 0000000..2ae2bd3 --- /dev/null +++ b/models/factors.py @@ -0,0 +1,186 @@ +import numpy as np +import pandas as pd +import statsmodels.api as sm +from scipy.stats import false_discovery_control +from models.curves import life_table + +ALPHA = 0.05 +FREQ_MIN = 0.8 +Z = 1.96 +CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia") +ORDER = { + "riesgo robusto": 0, + "protector robusto": 1, + "riesgo sugerente": 2, + "protector sugerente": 3, + "no concluyente": 4, +} +UNKNOWN_CLASS = "no aplica (categoria desconocida)" +DEFINING, MAJORITY, PRESENT = (0.95, 0.5, 0.1) +DESCRIBING = ("definitoria", "mayoritaria") + + +def variable_of(term: str, covariates: list[str]) -> str: + found = [c for c in covariates if term.startswith(c + "_")] + return max(found, key=len) if found else term + + +def km_at(months, event, horizon) -> tuple[float, float]: + d, _, n = life_table(months, event) + q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0) + v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0) + last = min(horizon, len(d) - 1) + 1 + S = float(np.prod(q[:last])) + return (S, S * float(np.sqrt(np.sum(v[:last])))) + + +def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame: + X = pd.get_dummies(data[variables]).astype(float) + X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables]) + X = X.loc[:, X.nunique() > 1] + X = X.loc[:, ~X.T.duplicated()] + m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit() + ci = np.exp(m.conf_int().loc[X.columns]) + return pd.DataFrame( + { + "termino": X.columns, + name: np.exp(m.params[X.columns].to_numpy()), + "IC95_inf": ci[0].to_numpy(), + "IC95_sup": ci[1].to_numpy(), + "p": m.pvalues[X.columns].to_numpy(), + } + ) + + +def complete( + table: pd.DataFrame, + variables, + reference: dict, + everyone: pd.DataFrame, + months, + event, + horizon: int, + names: tuple[str, str, str], +) -> pd.DataFrame: + table = table.reset_index(drop=True) + table["variable"] = [variable_of(x, variables) for x in table["termino"]] + table["categoria"] = [ + x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True) + ] + table["referencia"] = table["variable"].map(reference) + table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else [] + category, ref, delta_name = names + rows = [] + 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()) + sa, ea = km_at(months[a], event[a], horizon) + sb, eb = km_at(months[b], event[b], horizon) + delta, se = (sa - sb, np.sqrt(ea**2 + eb**2)) + 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, + } + ) + 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, + evaluated: tuple[str, ...] = CRITERIA, +) -> pd.DataFrame: + risk = tab[or_name] > 1 + tab["direccion"] = np.where(risk, "riesgo", "protector") + tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA) + excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0) + tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1)) + tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1) + robust = min(3, len(evaluated)) + tab["clasificacion"] = [ + UNKNOWN_CLASS + if cat == unknown + else f"{d} robusto" + if c1 and k >= robust + else f"{d} sugerente" + if k >= 2 + else "no concluyente" + for cat, d, c1, k in zip( + tab["categoria"], + tab["direccion"], + tab["c1_or"], + tab["criterios_cumplidos"], + strict=True, + ) + ] + return tab + + +def presence(share: float) -> str: + if share >= DEFINING: + return "definitoria" + return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria" + + +def listing(part: pd.DataFrame) -> str: + strength = np.where( + part["tipo_efecto"] == "tratamiento", + "asociacion", + part["clasificacion"].str.split().str[-1], + ) + return "; ".join( + ( + f"{v}={c} ({s}, {p:.0%})" + for v, c, s, p in zip( + part["variable"], part["categoria"], strength, part["share"], strict=True + ) + ) + ) + + +def classified(factors: pd.DataFrame) -> pd.DataFrame: + found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")] + kind = np.where( + found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0] + ) + return found.assign(tipo_efecto=kind) + + +def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict: + share = [ + float((frame.loc[mask, v] == c).mean()) + for v, c in zip(found["variable"], found["categoria"], strict=True) + ] + detail = found.assign(share=share, presence=[presence(s) for s in share]) + row = {} + for k in ("riesgo", "protector", "tratamiento"): + for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")): + row[f"{k}_{label}"] = listing( + detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)] + ) + included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING) + row["n_factores_riesgo_incluidos"] = int(included.sum()) + row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0 + return row diff --git a/models/graph.py b/models/graph.py new file mode 100644 index 0000000..fe1d37c --- /dev/null +++ b/models/graph.py @@ -0,0 +1,537 @@ +import hashlib +import io +import json +import os +import unicodedata +from collections.abc import Callable +from concurrent.futures import ProcessPoolExecutor +from functools import cache +import duckdb +import ocrmypdf +import pandas as pd +import pdfplumber +import pikepdf +import splink.comparison_library as cl +from markitdown import MarkItDown +from openai import OpenAI, OpenAIError +from splink import Linker, SettingsCreator, block_on +from splink.backends.duckdb import DuckDBAPI +from splink.clustering import cluster_pairwise_predictions_at_threshold +from core import catalog, concept_map, fhir_in +from core.pipeline import ( + HELD, + IDENTIFIERS, + QUOTES, + RECORD, + Extract, + Fhir, + Join, + Link, + Map, + Pipeline, + Read, + Route, + Target, + answer_schema, + apply_patterns, + ground, + join, + map_row, + matches, + validate, +) +from persistance import config_log, files, nodes, silver + +MIN_WORDS = 5 +READ_BATCH = 32 +READ_COLUMNS = { + "text": {"data_type": "text", "nullable": True}, + "ocr": {"data_type": "bool"}, + "error": {"data_type": "text", "nullable": True}, + "format": {"data_type": "text", "nullable": True}, +} + + +def file_format(content: bytes) -> str: + if content.startswith(b"%PDF"): + return "pdf" + head = content[:256] + if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit(): + return "edf" + return "other" + + +@cache +def _reader() -> MarkItDown: + return MarkItDown() + + +def _lines(text: str) -> str: + return "\n".join((" ".join(line.split()) for line in text.splitlines() if line.strip())) + + +def _text(content: bytes) -> str: + return _reader().convert_stream(io.BytesIO(content)).text_content + + +def _pdf_pages(content: bytes) -> list[str]: + with pdfplumber.open(io.BytesIO(content)) as pdf: + return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages] + + +def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]: + source, scans = (pikepdf.open(io.BytesIO(content)), pikepdf.new()) + for n in numbers: + scans.pages.append(source.pages[n]) + pages, sidecar = (io.BytesIO(), io.BytesIO()) + scans.save(pages) + pages.seek(0) + ocrmypdf.ocr( + pages, + io.BytesIO(), + language="spa", + 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))] + + +def read_file(content: bytes) -> dict: + kind = file_format(content) + if kind == "edf": + return {"text": None, "ocr": False, "error": None, "format": kind} + return {**_read_text(content), "format": kind} + + +def _read_text(content: bytes) -> dict: + try: + if not content.startswith(b"%PDF"): + return {"text": _text(content), "ocr": False, "error": None} + pages = _pdf_pages(content) + scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS] + if scanned: + for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True): + pages[i] = page + return {"text": "\n".join((p for p in pages if p)), "ocr": bool(scanned), "error": None} + except Exception as e: + return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} + + +def run_read(p: str, node: Read): + rows = list(nodes.rows(p, node.inputs[0])) + for row in rows: + row["key"] = row.get(node.column) or None + keys = {r["key"] for r in rows} - {None} + found = nodes.cached("read_cache", keys) + legacy = [k for k, r in found.items() if r.get("format") is None] + for k in legacy: + 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}} for k in legacy], + READ_COLUMNS, + ) + new = sorted(keys - set(found)) + with ProcessPoolExecutor() as pool: + for start in range(0, len(new), READ_BATCH): + batch = new[start : start + READ_BATCH] + read = dict( + 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) + found |= read + for row in rows: + result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"}) + row |= {k: result[k] for k in READ_COLUMNS} + return nodes.write(p, node.id, rows, READ_COLUMNS) + + +def run_route(p: str, node: Route, others: list[Route] = ()): + 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)))] + return nodes.write(p, node.id, taken) + + +def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]: + if node.concept_map is None: + return {} + found = config_log.concept_map(node.concept_map) + return {f: concept_map.table([found], f) for f in fields} + + +def run_map(p: str, node: Map): + codes = _codes(node, node.fields) + rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])] + return nodes.write(p, node.id, rows) + + +def run_fhir(p: str, node: Fhir): + maps = [config_log.concept_map(node.concept_map)] if node.concept_map else [] + found: dict[str, dict] = {} + for row in nodes.rows(p, node.inputs[0]): + bundle = json.loads(row[node.column]) + for r in fhir_in.rows(bundle, node.entity, p, maps): + found[r[RECORD]] = r + return nodes.write(p, node.id, list(found.values())) + + +def run_join(p: str, node: Join): + left, right = (list(nodes.rows(p, i)) for i in node.inputs) + return nodes.write(p, node.id, join(node, left, right, node.inputs[1])) + + +@cache +def _llm() -> tuple[OpenAI, str] | None: + if not (url := os.environ.get("LLM_URL")): + return None + client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600) + try: + client.models.list() + except OpenAIError: + return None + return (client, os.environ["LLM_MODEL"]) + + +PROMPT = "Extract every {entity} record stated in the document. For each field give its value in the schema's terms and `quote`: the exact text of the document it was read from, copied character by character. Leave out fields the document does not state.{hints}" + + +def _ask_llm(node: Extract, text: str) -> dict: + client, model = _llm() + system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "") + key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest() + if found := nodes.cached("llm_cache", {key}): + return json.loads(found[key]["answer"]) + reply = client.chat.completions.create( + model=model, + temperature=0, + seed=7, + messages=[{"role": "system", "content": system}, {"role": "user", "content": text}], + response_format={ + "type": "json_schema", + "json_schema": {"name": "answer", "schema": answer_schema(node.entity), "strict": True}, + }, + ) + answer = reply.choices[0].message.content + nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {}) + return json.loads(answer) + + +def run_extract(p: str, node: Extract): + use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None) + codes = _codes(node, node.patterns) + out = [] + for row in nodes.rows(p, node.inputs[0]): + text = node.text(row) + if use_llm: + found = ground(_ask_llm(node, text), text) + elif node.patterns: + found = apply_patterns(node, text, codes) + else: + found = [({}, {}, ["no LLM answering and no patterns set"])] + 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"])]): + out.append( + { + **values, + **taken, + RECORD: row[RECORD], + "_index": index, + QUOTES: json.dumps(quotes, ensure_ascii=False), + HELD: json.dumps(held) if held else None, + } + ) + return nodes.write(p, node.id, out) + + +def _comparison(field: str): + if field == "birth_date": + return cl.DateOfBirthComparison(field, input_is_string=True) + if field == "full_name": + return cl.NameComparison(field) + if field in ("record_number", "curp", "nss"): + return cl.LevenshteinAtThresholds(field, [1, 2]) + return cl.ExactMatch(field) + + +def _plain(identifier: str) -> str: + return "".join((ch for ch in identifier if ch.isalnum())).upper() + + +def _name(name: str) -> str: + plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode() + return " ".join(plain.upper().split()) + + +def _near(identifier: str) -> list[str]: + return sorted( + {identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))} + ) + + +def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]: + skip, fixed = (nodes.rejected("identity"), nodes.corrections()) + records: dict[str, dict] = {} + sources: dict[str, str] = {} + written: dict[str, str] = {} + for i in node.inputs: + for row in nodes.rows(p, i): + if row.get(HELD) or row[RECORD] in skip: + continue + row = {**row, **fixed.get(row[RECORD], {})} + mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]}) + sources.setdefault(row[RECORD], i) + for f in node.fields: + if row.get(f) is not None and mine.get(f) is None: + value = str(row[f]) + if f == "full_name": + written[row[RECORD]] = " ".join(value.split()) + mine[f] = ( + _plain(value) + if f in IDENTIFIERS + else _name(value) + if f == "full_name" + else value + ) + frame = pd.DataFrame(list(records.values())) + present = [f for f in node.fields if f in frame and frame[f].notna().any()] + return (frame[["unique_id", *present]], sources, written) + + +def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series: + fields = [c for c in records.columns if c != "unique_id"] + key = records[fields].astype(object).where(records[fields].notna(), None) + same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index) + stand_in = records.groupby(same, sort=False)["unique_id"].transform("first") + stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"]) + joined = set() + if rules: + con = duckdb.connect() + con.register("candidates", records[records["unique_id"].isin(set(stand_in))]) + joins = " or ".join((f"({r})" for r in rules)) + joined = set( + con.sql( + f"select l.unique_id from candidates l join candidates r on l.unique_id = r.unique_id where {joins}" + ).df()["unique_id"] + ) + return stand_in.where(stand_in.isin(joined), records["unique_id"]) + + +def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame: + clusters = cluster_pairwise_predictions_at_threshold( + records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r" + ) + return clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(records) + + +def run_link(p: str, node: Link): + records, sources, written = _identities(p, node) + fields = [c for c in records.columns if c != "unique_id"] + rules = [ + r + for r in node.rules or node.default_rules() + if all((f"l.{f}" not in r or f in fields for f in node.fields)) + ] + comparisons = [_comparison(f) for f in fields] + decided = nodes.person_decisions() + stand_in = _distinct(records, rules, set().union(*decided)) + distinct = records[records["unique_id"].isin(set(stand_in))] + db = DuckDBAPI() + linker = Linker( + db.register(distinct), + SettingsCreator( + link_type="dedupe_only", + comparisons=comparisons, + blocking_rules_to_generate_predictions=rules, + ), + log_level=None, + ) + sure = linker.inference.deterministic_link().as_pandas_dataframe() + pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)} + pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same} + known = set(distinct.unique_id) + edges = pd.DataFrame( + [sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"] + ) + cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"] + persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy()) + facts = [f for f in ("birth_date", "sex") if f in fields] + spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame() + torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set() + read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1) + nameless = set(read[read == 0].index) + why = {c: "records of this person disagree on birth date or sex" for c in torn} + why |= {c: "no name, birth date or record number was read" for c in nameless - torn} + columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)} + stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict()) + linked = [ + { + RECORD: r.unique_id, + "person_id": stable[r.cluster_id], + "_source": sources[r.unique_id], + HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None, + **{f: getattr(r, f) for f in fields}, + **({"full_name": written[r.unique_id]} if r.unique_id in written else {}), + } + for r in persons.itertuples() + ] + nodes.write(p, node.id, linked, columns) + nodes.stage("identity", p, node.id, linked, silver.identity_columns()) + ids = [f for f in IDENTIFIERS if f in fields] + whole = persons.drop(columns="unique_id").groupby("cluster_id").first() + for f in ids: + near = ( + persons.dropna(subset=[f]) + .groupby("cluster_id")[f] + .agg(lambda values: sorted({n for v in values for n in _near(v)})) + ) + whole[f"{f}_near"] = near.reindex(whole.index).apply( + lambda v: v if isinstance(v, list) else [] + ) + whole = whole.reset_index().rename(columns={"cluster_id": "unique_id"}) + blocks = [block_on(f"{f}_near", arrays_to_explode=[f"{f}_near"]) for f in ids] + reasons = [f"{f} one typo apart" for f in ids] + if "birth_date" in fields: + blocks.append(block_on("birth_date")) + reasons.append("same birth date") + model = Linker( + db.register(whole), + SettingsCreator( + link_type="dedupe_only", + comparisons=comparisons, + blocking_rules_to_generate_predictions=blocks, + ), + log_level=None, + ) + model.training.estimate_u_using_random_sampling(max_pairs=1000000.0) + found = model.inference.predict(warning_mode="never").as_pandas_dataframe() + known = [f for f in ("birth_date", "sex") if f in fields] + orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set() + undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set() + lone = set() + for f in ids: + carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size() + lone |= {person for (person, _), n in carried.items() if n == 1} + + def settle(r) -> tuple[str, str] | None: + a, b = (r.unique_id_l, r.unique_id_r) + sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known] + if frozenset((a, b)) in decided or any( + (pd.notna(x) and pd.notna(y) and (x != y) for x, y in sides) + ): + return None + reason = reasons[int(r.match_key)] + if not reason.endswith("typo apart"): + return (a, b) + field = reason.removesuffix(" one typo apart") + if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): + return (a, b) if a in undated or b not in undated else (b, a) + if field == "full_name" and (a in undated) != (b in undated): + return (a, b) if a in undated else (b, a) + if a in orphan and b in lone: + return (a, b) + if b in orphan and a in lone: + return (b, a) + return None + + side = {r.unique_id: r for r in whole.itertuples()} + queue = [] + for r in found.itertuples(): + if pair := settle(r): + person, owner = pair + queue.append( + { + "person": person, + "candidate": owner, + "probability": r.match_probability, + "reason": reasons[int(r.match_key)], + **{f"person_{f}": getattr(side[person], f) for f in fields}, + **{f"candidate_{f}": getattr(side[owner], f) for f in fields}, + } + ) + return nodes.write(p, f"{node.id}__review", queue) + + +def run_target(p: str, node: Target, kinds: dict[str, str]): + link = next((i for i in node.inputs if kinds[i] == "link")) + linked = {r[RECORD]: r for r in nodes.rows(p, link)} + person = {k: r["person_id"] for k, r in linked.items()} + model, study = (catalog.model(node.entity), catalog.studies()[node.entity]) + fixed = nodes.corrections() + observations, held_rows = ([], []) + for i in (i for i in node.inputs if i != link): + for row in nodes.rows(p, i): + values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None} + values |= { + f: v for f, v in fixed.get(row[RECORD], {}).items() if f in model.model_fields + } + held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values) + if row[RECORD] not in person: + held.append("no identity linked to this record") + else: + held += json.loads(linked[row[RECORD]].get(HELD) or "[]") + base = { + "study": node.entity, + "person_id": person.get(row[RECORD]), + RECORD: row[RECORD], + "_index": row.get("_index", 0), + QUOTES: row.get(QUOTES), + } + if held: + raw = json.dumps(values, default=str, ensure_ascii=False) + held_rows.append({**base, HELD: json.dumps(held), "_raw": raw}) + continue + clean = model.model_validate(values) + instance = json.dumps([str(getattr(clean, k)) for k in model.key]) + for name, field in study.fields.items(): + if (value := getattr(clean, name)) is not None: + observations.append( + { + **base, + "instance": instance, + "field": name, + catalog.value_column(field): value, + } + ) + nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) + return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) + + +RUNNERS: dict[str, Callable] = { + "source": nodes.run_source, + "read": run_read, + "route": run_route, + "map": run_map, + "join": run_join, + "extract": run_extract, + "link": run_link, + "fhir": run_fhir, +} + + +def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None: + kinds = {n.id: n.kind for n in pipeline.nodes} + for node in pipeline.order(): + if node.kind == "target": + run_target(pipeline_id, node, kinds) + elif node.kind == "route" and node.otherwise: + others = [ + 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) + else: + RUNNERS[node.kind](pipeline_id, node) + log(f"{node.id} ({node.kind}) done") + if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}): + silver.build(["silver+"]) + log(f"silver and gold, from {', '.join(entities)}") diff --git a/models/jobs.py b/models/jobs.py new file mode 100644 index 0000000..7fb62c7 --- /dev/null +++ b/models/jobs.py @@ -0,0 +1,74 @@ +from collections.abc import Callable +from dataclasses import dataclass +from datetime import date +import mlflow.pyfunc +import pandas as pd +from joblib.externals.loky import get_reusable_executor +from persistance import gold, registry + + +class EmptyCohort(ValueError): + pass + + +class Predictor(mlflow.pyfunc.PythonModel): + def __init__(self, spec, fitted): + self.spec, self.fitted = (spec, fitted) + + def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: + return self.spec.predict(self.fitted, model_input) + + +@dataclass(frozen=True) +class Jobs: + domain: str + models: dict + technical_validation: Callable[..., dict] + interpretability: Callable[..., dict] + + @property + def events(self) -> str: + return f"{self.domain}_events" + + def routine(self) -> list[str]: + return [n for n, s in self.models.items() if not getattr(s, "slow", False)] + + def scored(self) -> list[str]: + return list(self.models) + + def registered(self, name: str) -> str: + return f"{self.domain}.{name}" + + def train(self, name: str, as_of: date | None = None) -> int: + spec, as_of = (self.models[name], as_of or date.today()) + if spec.cohort is None: + fitted, metrics, found = spec.train(None, as_of) + elif getattr(spec, "reports", False): + events = gold.timelines(self.events, spec.cohort, as_of) + if events.empty: + raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") + fitted, metrics, found = spec.train(events, as_of) + else: + events = gold.timelines(self.events, spec.cohort, as_of) + if events.empty: + raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") + fitted, metrics, data = spec.train(events, as_of) + found = { + "technical_validation": self.technical_validation(spec, metrics, data), + "interpretability": self.interpretability(spec, fitted, data), + } + get_reusable_executor().shutdown(wait=True) + params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()} + model = Predictor(spec, fitted) + return registry.register(self.registered(name), model, params, metrics, found) + + def score(self, name: str) -> int | None: + if self.models[name].cohort is None: + return None + found = registry.champion(self.registered(name)) + if found is None: + return None + version, model = found + risks = model.predict(gold.timelines(self.events, self.models[name].cohort)) + gold.save_scores(self.registered(name), version, risks) + return version diff --git a/models/survival.py b/models/survival.py new file mode 100644 index 0000000..7cc62be --- /dev/null +++ b/models/survival.py @@ -0,0 +1,614 @@ +import json +import warnings +from dataclasses import dataclass, field +from itertools import pairwise +import numpy as np +import pandas as pd +from joblib import Parallel, delayed +from scipy.optimize import minimize_scalar +from scipy.special import gammaln +from sklearn.base import BaseEstimator +from sklearn.linear_model import LogisticRegression + +UNKNOWN = "NA" +DAYS_PER_MONTH = 30.4375 +DAYS_PER_YEAR = 365.25 + + +def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame: + index, death, end = (pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)) + died = (death.notna() & (death <= end)).to_numpy() + last = death.where(died, end) + days = (last - index).dt.days.to_numpy() + months = np.floor(days / DAYS_PER_MONTH).astype(int).clip(min=0) + if cap_months: + died = died & (months < cap_months) + months = np.minimum(months, cap_months) + return pd.DataFrame({"months": months, "event": died}, index=index.index) + + +def band(values: pd.Series, cuts: list) -> pd.Series: + edges = [-np.inf, *cuts, np.inf] + labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"] + return pd.cut(values, edges, right=False, labels=labels).astype(object) + + +@dataclass(frozen=True) +class Constant: + p: float + + def predict_proba(self, X) -> np.ndarray: + return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)]) + + +def _bdeu(code, y, w, q, ess) -> float: + n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2) + aj, ajk = (ess / q, ess / q / 2) + return float( + np.sum( + gammaln(aj) - gammaln(aj + n.sum(1)) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1) + ) + ) + + +def _search(X, levels, y, w, ess, max_parents) -> list[int]: + parents, code, q = ([], np.zeros(len(y), int), 1) + best = _bdeu(code, y, w, q, ess) + while len(parents) < max_parents: + found = None + for j in range(X.shape[1]): + if j in parents or q * levels[j] > 200000: + continue + c2 = code * levels[j] + X[:, j] + score = _bdeu(c2, y, w, q * levels[j], ess) + if score > best + 1e-09 and (found is None or score > found[0]): + found = (score, j, c2, q * levels[j]) + if found is None: + break + best, j, code, q = found + parents.append(j) + return parents + + +def _code(X, levels, parents) -> np.ndarray: + code = np.zeros(len(X), int) + for j in parents: + code = code * levels[j] + X[:, j] + return code + + +class IntervalSurvival(BaseEstimator): + def __init__( + self, + features, + borders=(0, 6, 12, 18), + parents=None, + ess=1000, + max_parents=5, + folds=5, + shrink=20, + seed=42, + ): + self.features = features + self.borders = borders + self.parents = parents + self.ess = ess + self.max_parents = max_parents + self.folds = folds + self.shrink = shrink + self.seed = seed + + def _frame(self, X: pd.DataFrame) -> pd.DataFrame: + found = X[list(self.features)].astype(object) + return found.where(found.notna(), UNKNOWN).astype(str) + + def _encode(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + frame = self._frame(X) + columns = [] + for name in self.features: + known = self.categories_[name] + codes = pd.Categorical(frame[name], categories=known).codes + fallback = known.index(UNKNOWN) if UNKNOWN in known else 0 + columns.append(np.where(codes < 0, fallback, codes)) + dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0) + return (dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)) + + def _fit_intervals(self, X_dum, X_int, months, event) -> list: + fitted = [] + for a, b in pairwise(self.borders): + at_risk = np.where(months >= a)[0] + if len(at_risk) == 0: + fitted.append((Constant(1.0), ([], np.array([1.0])))) + continue + m, e = (months[at_risk], event[at_risk]) + y = np.where(e & (m < b), 0, 1) + w = np.where(~e & (m < b), 0.5, 1.0) + if y.min() == y.max(): + lr = Constant(float(y[0])) + else: + lr = LogisticRegression(C=1000000.0, max_iter=500) + lr.fit(X_dum[at_risk], y, sample_weight=w) + fitted.append((lr, self._hbn(X_int[at_risk], y, w))) + return fitted + + def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]: + if self.parents is None: + parents = _search(X, self.levels_, y, w, self.ess, self.max_parents) + else: + parents = [list(self.features).index(p) for p in self.parents] + q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1 + n = np.bincount( + _code(X, self.levels_, parents) * 2 + y, weights=w, minlength=q * 2 + ).reshape(q, 2) + aj = self.ess / q + marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1) + return (parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)) + + def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]: + lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted]) + hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted]) + return (lr, hbn) + + def _weights(self, X_dum, X_int, months, event) -> np.ndarray: + n = len(months) + fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds + oof_lr, oof_hbn = ( + np.zeros((n, len(self.borders) - 1)), + np.zeros((n, len(self.borders) - 1)), + ) + for k in range(self.folds): + test, train = (np.where(fold == k)[0], np.where(fold != k)[0]) + fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train]) + oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test]) + weights = [] + for j, (a, b) in enumerate(pairwise(self.borders)): + at_risk = np.where(months >= a)[0] + if len(at_risk) == 0: + weights.append(0.5) + continue + m, e = (months[at_risk], event[at_risk]) + y = np.where(e & (m < b), 0, 1) + w = np.where(~e & (m < b), 0.5, 1.0) + p1 = np.clip(oof_lr[at_risk, j], 1e-09, 1 - 1e-09) + p2 = np.clip(oof_hbn[at_risk, j], 1e-09, 1 - 1e-09) + + def loss(x, p1=p1, p2=p2, y=y, w=w): + 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))) + + best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x) + shrunk = self.shrink / (self.shrink + int((y == 0).sum())) + weights.append((1 - shrunk) * best + shrunk * 0.5) + return np.array(weights) + + def fit(self, X: pd.DataFrame, months, event): + frame = self._frame(X) + self.dummies_ = list(pd.get_dummies(frame, drop_first=True).columns) + self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features} + X_dum, X_int = self._encode(X) + self.levels_ = X_int.max(axis=0) + 1 + months, event = (np.asarray(months, int), np.asarray(event, bool)) + if len(X) >= 2 * self.folds: + self.weights_ = self._weights(X_dum, X_int, months, event) + else: + self.weights_ = np.full(len(self.borders) - 1, 0.5) + self.fitted_ = self._fit_intervals(X_dum, X_int, months, event) + return self + + def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + return self._predict(self.fitted_, *self._encode(X)) + + def survival(self, X: pd.DataFrame) -> np.ndarray: + lr, hbn = self.components(X) + w = self.weights_[None, :] + return np.cumprod(w * lr + (1 - w) * hbn, axis=1) + + +TRAIN_FRACTION = 0.7 +OUTPUT = [ + "person_id", + "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]: + ordered = members.sort_values(["index_date", "record_number"], kind="stable") + cut = int(len(ordered) * train_fraction) + return (ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)) + + +def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series: + birth = events[events["type"] == "birth"].groupby("person_id")["date"].min() + age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR + return band(age, list(cuts)) + + +@dataclass(frozen=True) +class Spec: + name: str + cohort: str + features: tuple[str, ...] + covariates: object + parents: tuple[str, ...] | None = None + borders: tuple[int, ...] = (0, 6, 12, 18) + cap_months: int = 24 + interval_level: float | None = None + replicas: int = 100 + seed: int = 0 + method: str = "interval survival" + notes: tuple[str, ...] = () + scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict) + scenario_columns: tuple[str, ...] = () + treatments: tuple[str, ...] = () + + @property + def horizons(self) -> tuple[float, ...]: + return tuple((b / 12 for b in self.borders[1:])) + + def members(self, events: pd.DataFrame) -> pd.DataFrame: + events = events.assign( + date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"]) + ) + found = events.groupby("person_id")[["index_date", "record_number"]].first() + death = events[events["type"] == "death"].groupby("person_id")["date"].min() + found["death_date"] = death.reindex(found.index) + kept = [*self.features, *self.scenario_columns] + found = found.join(self.covariates(events, found)[kept]) + return found.reset_index() + + def _model(self) -> IntervalSurvival: + return IntervalSurvival(list(self.features), self.borders, self.parents) + + def _combinations(self, X: pd.DataFrame) -> pd.DataFrame: + found = X[list(self.features)].astype(object) + return found.where(found.notna(), UNKNOWN).astype(str).reset_index(drop=True) + + def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]: + combinations = self._combinations(train).drop_duplicates() + frame = combinations.replace(UNKNOWN, None) + rng = np.random.default_rng(self.seed) + samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)] + + def mortality(rows: np.ndarray) -> np.ndarray: + sample = train.iloc[rows].reset_index(drop=True) + refit = self._model().fit(sample, sample["months"], sample["event"]) + return 1.0 - refit.survival(frame) + + replicas = Parallel(n_jobs=-1)((delayed(mortality)(rows) for rows in samples)) + tail = 50 * (1 - self.interval_level) + low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0) + rows = combinations.itertuples(index=False) + return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)} + + def train(self, events: pd.DataFrame, as_of) -> tuple: + members = self.members(events) + members = members.join( + outcomes(members["index_date"], members["death_date"], as_of, self.cap_months) + ) + train, test = split(members, TRAIN_FRACTION) + model = self._model().fit(train, train["months"], train["event"]) + model.intervals_ = self._intervals(train) if self.interval_level else {} + weights = zip(self.borders[1:], model.weights_, strict=True) + metrics = { + "n_train": float(len(train)), + "n_test": float(len(test)), + "events_train": float(train["event"].sum()), + "events_test": float(test["event"].sum()), + **{f"stack_w_lr_{b}m": float(w) for b, w in weights}, + } + return (model, metrics, {"train": train, "test": test}) + + def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame: + members = self.members(events) + mortality = 1.0 - model.survival(members) + n, h = (len(members), len(self.horizons)) + empty = ([np.nan] * h, [np.nan] * h) + ends = [ + model.intervals_.get(tuple(c), empty) + for c in self._combinations(members).itertuples(index=False) + ] + masks = scenario_masks(members, self.scenarios) + scenarios = [ + SCENARIO_SEPARATOR.join((name for name, m in masks.items() if m[i])) or None + for i in range(n) + ] + return pd.DataFrame( + { + "person_id": np.repeat(members["person_id"].to_numpy(), h), + "index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h), + "horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n), + "probability": mortality.ravel(), + "ci_low": np.array([e[0] for e in ends], dtype=float).ravel(), + "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(), + "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h), + } + )[OUTPUT] + + +BOOTSTRAP = 100 +BOOTSTRAP_SEED = 42 + + +def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict: + members = pd.concat([data["train"], data["test"]]) + return { + "model": spec.name, + "method": spec.method, + "cohort": spec.cohort, + "split": "temporal: the earliest 70% of index dates train, the latest 30% test", + "members": len(members), + "index_dates": [ + str(members["index_date"].min().date()), + str(members["index_date"].max().date()), + ], + "horizons_months": list(spec.borders[1:]), + "follow_up_cap_months": spec.cap_months, + "notes": list(spec.notes), + "metrics": metrics, + } + + +def _curve(fitter, name: str) -> dict: + table = fitter.confidence_interval_survival_function_ + return { + "months": fitter.survival_function_.index.tolist(), + "survival": fitter.survival_function_.iloc[:, 0].tolist(), + "low": table.iloc[:, 0].tolist(), + "high": table.iloc[:, 1].tolist(), + "name": name, + } + + +MIN_SCENARIO_EVENTS = 5 +GRID_POINTS = 200 + + +def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: + found = {} + for name, conditions in scenarios.items(): + mask = np.ones(len(members), bool) + for column, op, value in conditions: + v = members[column] + if op in ("<", ">="): + number = pd.to_numeric(v, errors="coerce") + held = number < value if op == "<" else number >= value + elif op == "in": + held = v.isin(list(value)) + elif op == "==": + held = v == value + else: + raise ValueError(f"unknown condition {op!r} in scenario {name!r}") + mask &= held.fillna(False).to_numpy(bool) + found[name] = mask + return found + + +def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) -> dict: + from models import curves + + d, c, _ = curves.life_table(months, event) + k, lam = curves.fit_weibull(d, c) + fractional = curves.fit_fractional(d, c, k, lam) + grid = np.linspace(0, cap_months, GRID_POINTS) + observed = int(months.max()) + km = curves.kaplan_meier(months, event, observed) + return { + "observado_hasta": observed, + "km": { + "months": list(range(observed + 1)), + **{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}, + }, + "weibull": { + "t": grid.tolist(), + "S": curves.weibull(grid, k, lam).tolist(), + "k": k, + "lambda": lam, + }, + "weibull_fractional": { + "t": grid.tolist(), + "S": curves.fractional(grid, k, *fractional).tolist(), + "alpha": fractional[0], + "beta": fractional[1], + "lambda": fractional[2], + }, + } + + +def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: + from lifelines import KaplanMeierFitter, WeibullFitter + + train = data["train"] + months, event = (train["months"].to_numpy(), train["event"].to_numpy()) + curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")] + if event.any() and (months > 0).all(): + curves.append(_curve(WeibullFitter().fit(months, event), "Weibull")) + rng = np.random.default_rng(BOOTSTRAP_SEED) + samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)] + members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True) + masks = scenario_masks(members, spec.scenarios) + + def mean_survival(rows: np.ndarray) -> tuple[np.ndarray, dict]: + sample = train.iloc[rows].reset_index(drop=True) + refit = spec._model().fit(sample, sample["months"], sample["event"]) + found = refit.survival(members) + by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()} + return (found[: len(train)].mean(axis=0), by) + + all_months, all_event = (members["months"].to_numpy(), members["event"].to_numpy(bool)) + drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS} + jobs = [ + delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months) + for m in drawn.values() + ] + jobs += [delayed(mean_survival)(rows) for rows in samples] + done = Parallel(n_jobs=-1)(jobs) + drawn_curves, replicas = (done[: len(drawn)], done[len(drawn) :]) + band = np.stack([r[0] for r in replicas]) + point = model.survival(members) + scenarios = [] + for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True): + spread = np.array([r[1][name] for r in replicas]) + low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0) + scenarios.append( + { + "escenario": name, + "condiciones": [list(c) for c in spec.scenarios[name]], + "n": int(mask.sum()), + "fallecidos": int(all_event[mask].sum()), + "horizons_months": list(spec.borders[1:]), + "months_max": spec.cap_months, + **found, + "points": { + "COMB": { + "S": point[mask].mean(axis=0).tolist(), + "low": np.clip(low, 0, 1).tolist(), + "high": np.clip(high, 0, 1).tolist(), + } + }, + "bootstrap_replicas": len(replicas), + } + ) + 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") + survival = model.survival(combinations.replace(UNKNOWN, None)) + return { + "model": spec.name, + "kind": "curves", + "curves": curves, + "predicted": { + "months": list(spec.borders[1:]), + "survival": model.survival(train).mean(axis=0).tolist(), + "low": np.percentile(band, 2.5, axis=0).tolist(), + "high": np.percentile(band, 97.5, axis=0).tolist(), + "name": "LR + HBN combinado (IC 95 % bootstrap)", + }, + "weights_lr": model.weights_.tolist(), + "parents": [[spec.features[j] for j in parents] for _, (parents, _) in model.fitted_], + "combinations": [ + {**row, "survival": survival[i].tolist()} + for i, row in enumerate(combinations.to_dict("records")) + ], + "escenarios": scenarios, + "escenarios_sin_curvas": skipped, + "min_fallecidos_escenario": MIN_SCENARIO_EVENTS, + **risk_factor_report(spec, model, members), + } + + +FACTOR_COLUMNS = ( + "tipo", + "variable", + "categoria", + "referencia", + "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") +TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)" +EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia") + + +def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame: + from models import factors as rated + + horizon = spec.borders[-1] + months, event = (members["months"].to_numpy(), members["event"].to_numpy(bool)) + died = event & (months < horizon) + known = died | (months >= horizon) + data = spec._combinations(members)[known].reset_index(drop=True) + y, months, event = (died[known].astype(int), months[known], event[known]) + empty = pd.DataFrame(columns=list(FACTOR_COLUMNS)) + if len(data) == 0 or y.min() == y.max(): + return empty + features = list(spec.features) + treatment = [f for f in features if f in spec.treatments] + intrinsic = [f for f in features if f not in spec.treatments] + reference = {v: data[v].value_counts().idxmax() for v in features} + blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents} + + def complete(table, variables): + return rated.complete( + table, variables, reference, data, months, event, horizon, SURVIVAL_COLUMNS + ) + + with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"): + warnings.simplefilter("ignore") + try: + tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"), intrinsic) + except (np.linalg.LinAlgError, ValueError): + return empty + tab["c2_estabilidad"] = np.nan + tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket) + tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED) + tab["tipo"] = "factor de riesgo" + if treatment: + both = intrinsic + treatment + try: + tr = rated.odds_ratios(data, y, both, reference, "OR_muerte") + except (np.linalg.LinAlgError, ValueError): + tr = None + if tr is not None: + of = tr["termino"].map(lambda x: rated.variable_of(x, both)) + tr = complete( + tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment + ) + tr["tipo"], tr["clasificacion"] = ("tratamiento", TREATMENT_CLASS) + tab = pd.concat([tab, tr], ignore_index=True) + tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int) + tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5) + tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False]) + return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True) + + +def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]: + from models import factors as rated + + found = rated.classified(table) if len(table) else table + data = spec._combinations(members) + rows = [] + for name, mask in scenario_masks(members, spec.scenarios).items(): + if not mask.any() or found.empty: + continue + rows.append( + { + "escenario": name, + "condiciones": [list(c) for c in spec.scenarios[name]], + "n_escenario": int(mask.sum()), + **rated.scenario_row(data, mask, found), + } + ) + return rows + + +def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict: + table = risk_factors(spec, model, members) + rows = json.loads(table.to_json(orient="records")) + return { + "factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows}, + "factores_escenarios": scenario_factors(spec, members, table), + } diff --git a/models/tea/__init__.py b/models/tea/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/models/tea/__init__.py @@ -0,0 +1 @@ + diff --git a/models/tea/association.py b/models/tea/association.py new file mode 100644 index 0000000..13086f6 --- /dev/null +++ b/models/tea/association.py @@ -0,0 +1,359 @@ +import warnings +from dataclasses import dataclass, field +import numpy as np +import pandas as pd +from scipy import optimize, stats +from scipy.special import expit +from statsmodels.stats.multitest import multipletests +from core.tea import association as spec + +CHI2_95 = float(stats.chi2.ppf(0.95, 1)) +MIN_ROWS = 8 +TOO_FEW = "too few data or no variation" + + +def item_scores(frame: pd.DataFrame, number: int) -> pd.Series: + name, modules = spec.ITEMS[number] + if name not in frame or "module" not in frame: + return pd.Series(np.nan, index=frame.index) + v = pd.to_numeric(frame[name], errors="coerce") + v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2) + return v.where(frame["module"].isin(modules)) + + +def has_items(frame: pd.DataFrame) -> bool: + scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1) + return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN + + +@dataclass +class Design: + predictor: str + numeric: dict[str, float] = field(default_factory=dict) + categorical: dict[str, list[str]] = field(default_factory=dict) + reference: dict[str, str] = field(default_factory=dict) + + @classmethod + def of(cls, t: pd.DataFrame, predictor: str) -> "Design": + d = cls(predictor) + for a in (a for a in spec.ADJUST if a in t): + v = t[a] + if pd.api.types.is_numeric_dtype(v): + if v.astype(float).std() > 0: + d.numeric[a] = float(v.astype(float).mean()) + continue + commonest = v.value_counts().index[0] + levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)] + if levels: + d.categorical[a], d.reference[a] = ([str(x) for x in levels], str(commonest)) + return d + + @property + def names(self) -> list[str]: + return [ + "intercept", + self.predictor, + *self.numeric, + *(f"{a}={x}" for a, levels in self.categorical.items() for x in levels), + ] + + def matrix(self, t: pd.DataFrame) -> np.ndarray: + cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)] + cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()] + known = np.ones(len(t), bool) + for a, levels in self.categorical.items(): + v = t[a].astype(str) + cols += [(v == x).to_numpy(float) for x in levels] + known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy() + X = np.column_stack(cols) + X[~known] = np.nan + return X + + def state(self) -> dict: + return { + "predictor": self.predictor, + "numeric": self.numeric, + "categorical": self.categorical, + "reference": self.reference, + } + + @classmethod + def from_state(cls, s: dict) -> "Design": + return cls( + s["predictor"], + dict(s["numeric"]), + {k: list(v) for k, v in s["categorical"].items()}, + dict(s["reference"]), + ) + + +def _penalised(b, X, y) -> float: + eta = X @ b + w = expit(eta) * (1 - expit(eta)) + sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None])) + return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2) + + +def _gradient(b, X, y): + p = expit(X @ b) + w = p * (1 - p) + info = X.T @ (X * w[:, None]) + leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w + return (X.T @ (y - p + leverage * (0.5 - p)), info) + + +def _firth_fit(X, y, max_iter=200, tol=1e-10): + b = np.zeros(X.shape[1]) + best = _penalised(b, X, y) + for _ in range(max_iter): + score, info = _gradient(b, X, y) + step, t = (np.linalg.solve(info, score), 1.0) + while t > 1e-08: + trial = _penalised(b + t * step, X, y) + if trial >= best - 1e-12: + break + t /= 2 + b, best = (b + t * step, trial) + if np.max(np.abs(t * step)) < tol: + break + return (b, best) + + +def _firth_profile(value, j, X, y, start) -> float: + free = [k for k in range(X.shape[1]) if k != j] + + def negative(bf): + b = np.empty(X.shape[1]) + b[free], b[j] = (bf, value) + v = _penalised(b, X, y) + if not np.isfinite(v): + return (10000000000.0, np.zeros(len(free))) + return (-v, -_gradient(b, X, y)[0][free]) + + return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun) + + +def _interval(profile, centre, maximum, scale) -> tuple[float, float]: + drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 + limits = [] + for sign in (-1, 1): + previous, limit = (centre, sign * np.inf) + for k in range(1, 80): + v = centre + sign * scale * k + if drop(v) > 0: + limit = optimize.brentq(drop, min(previous, v), max(previous, v)) + break + previous = v + limits.append(limit) + return (limits[0], limits[1]) + + +def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict: + return { + "model": model, + "n": n, + "coef": round(float(coef), 4), + "odds_ratio": round(float(np.exp(coef)), 4), + "ci_low": round(float(np.exp(low)), 4), + "ci_high": round(float(np.exp(high)), 4), + "p": round(p, 5), + "adjusted_for": ", ".join(design.names[2:]), + "reason": "", + **extra, + "state": {"design": design.state(), **state}, + } + + +def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict: + d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna() + y = d[outcome].to_numpy(float) + out = {"model": "firth", "n": len(d), "events": int(y.sum())} + if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or (d[predictor].std() == 0): + return {**out, "reason": TOO_FEW} + design = Design.of(d, predictor) + X = design.matrix(d) + b, top = _firth_fit(X, y) + se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1])) + profile = lambda v: _firth_profile(v, 1, X, y, b) + 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)) + eta = X[:, 1:] @ b[1:] + intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50) + state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)} + return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum())) + + +def _ordinal_nll(par, X, y, K) -> float: + theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) + eta = X @ par[K - 1 :] + n = len(y) + cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)] + return -float( + np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None))) + ) + + +def _ordinal_fit(X, y, K, fixed=None): + start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])] + if fixed is None: + r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS") + return (r.x, float(r.fun)) + j, value = fixed + free = [k for k in range(len(start)) if k != K - 1 + j] + + def nll(q): + par = np.empty(len(start)) + par[free], par[K - 1 + j] = (q, value) + return _ordinal_nll(par, X, y, K) + + return (None, float(optimize.minimize(nll, start[free], method="BFGS").fun)) + + +def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict: + d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna() + levels = np.sort(d[outcome].unique()) + out = {"model": "ordinal", "n": len(d), "levels": len(levels)} + if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0: + return {**out, "reason": TOO_FEW} + design = Design.of(d, predictor) + X = design.matrix(d)[:, 1:] + K = len(levels) + y = np.searchsorted(levels, d[outcome].to_numpy()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + par, nll = _ordinal_fit(X, y, K) + beta = par[K - 1 :] + if abs(beta[0]) > 20: + return {**out, "reason": "does not converge (separation)"} + profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] + low, high_ = _interval(profile, beta[0], -nll, 0.1) + p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1)) + theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])]) + k = int(np.searchsorted(levels, high)) + inside = 0 < k < K + state = { + "beta": [float(v) for v in beta], + "threshold": float(theta[k - 1]) if inside else None, + "always": None if inside else float(k == 0), + } + return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K) + + +def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]: + s = fit["state"] + X = Design.from_state(s["design"]).matrix(t) + if fit["model"] == "firth": + return ( + expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), + float(expit(s["intercept"])), + ) + if s["threshold"] is None: + return (np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]) + return ( + 1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])), + float(1 - expit(s["threshold"])), + ) + + +def _guarded(fit, *args) -> dict: + try: + return fit(*args) + except (np.linalg.LinAlgError, ValueError) as error: + model = "firth" if fit is firth else "ordinal" + return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"} + + +def fit(cohort: pd.DataFrame, level: str = "auto") -> dict: + if level == "auto": + level = "item" if has_items(cohort) else "domain" + rows = [] + for pair in spec.pairs(level): + if pair["predictor"] not in cohort: + continue + d = cohort.copy() + d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan) + if pair["kind"] == "item": + d["_level"] = item_scores(cohort, pair["outcome"]) + d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna()) + principal = _guarded(firth, d, "_yes", pair["predictor"]) + sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED) + else: + d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce") + d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna()) + principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH) + sensitivity = _guarded(firth, d, "_yes", pair["predictor"]) + rows.append({**pair, "principal": principal, "sensitivity": sensitivity}) + p = np.array([r["principal"].get("p", np.nan) for r in rows], float) + biomarkers = np.array([r["biomarker"] for r in rows]) + q = np.full(len(rows), np.nan) + for b in dict.fromkeys(biomarkers): + mine = (biomarkers == b) & np.isfinite(p) + if mine.any(): + q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5) + for r, v in zip(rows, q, strict=True): + r["q"] = None if np.isnan(v) else float(v) + return {"level": level, "n": len(cohort), "rows": rows} + + +def outcome_code(row: dict) -> str: + return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS + + +def associations(fitted: dict) -> list[dict]: + out = [] + for r in fitted["rows"]: + f, s = (r["principal"], r["sensitivity"]) + ratio, other = (f.get("odds_ratio"), s.get("odds_ratio")) + out.append( + { + "biomarker": r["biomarker"], + "zone": r["zone"], + "kind": r["kind"], + "outcome": r["outcome"], + "outcome_code": outcome_code(r), + "event": f">={(spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH)}", + "model": f["model"], + "n": f["n"], + "odds_ratio": ratio, + "ci_low": f.get("ci_low"), + "ci_high": f.get("ci_high"), + "p": f.get("p"), + "q": r["q"], + "sens_model": s["model"], + "sens_odds_ratio": other, + "same_direction": None + if ratio is None or other is None + else bool(np.sign(ratio - 1) == np.sign(other - 1)), + "reason": f.get("reason", ""), + } + ) + return out + + +def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]: + out = [] + for r in fitted["rows"]: + f = r["principal"] + if f.get("odds_ratio") is None or r["predictor"] not in cohort: + continue + t = cohort + if r["kind"] == "item": + t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])] + t = t[t[r["predictor"]].notna()] + if not len(t): + continue + found, reference = probability(f, t) + for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True): + if np.isfinite(p): + out.append( + { + "key": key, + "biomarker": r["biomarker"], + "zone": r["zone"], + "outcome_code": outcome_code(r), + "z": float(z), + "probability": round(float(p), 4), + "reference_probability": round(reference, 4), + } + ) + return out diff --git a/models/tea/eeg/__init__.py b/models/tea/eeg/__init__.py new file mode 100644 index 0000000..2ae2839 --- /dev/null +++ b/models/tea/eeg/__init__.py @@ -0,0 +1 @@ +pass diff --git a/models/tea/eeg/analysis.py b/models/tea/eeg/analysis.py new file mode 100644 index 0000000..630bc31 --- /dev/null +++ b/models/tea/eeg/analysis.py @@ -0,0 +1,114 @@ +import math +import re +from dataclasses import dataclass, field +from datetime import date +from models.tea.eeg import biomarkers, checks, preprocess, read, sleep + +DAYS_PER_MONTH = 30.4375 +MAINS_HZ = 60.0 + + +@dataclass(frozen=True) +class Metric: + code: str + value: float | None + electrodes: dict[str, float] = field(default_factory=dict) + zones: dict[str, float] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Analysis: + valid: bool | None + level: str + age_months: float | None + clean_fraction: float | None + bad_channels: int | None + channels: int | None + duration_min: float | None + line_noise_db: float | None + sleep: bool | None + checks: list[dict] + metrics: list[Metric] + features: dict[str, dict[str, float]] + error: str | None + + +def _number(v) -> float | None: + return float(v) if v is not None and math.isfinite(v) else None + + +def _error(exc: Exception) -> str: + message = re.sub("(/|[A-Za-z]:\\\\)[^\\s'\\\"]*", "", str(exc))[:300] + return f"{type(exc).__name__}: {message}" + + +def analyze( + edf: bytes, + birth_date: date | None = None, + *, + age_months: float | None = None, + mains_hz: float = MAINS_HZ, +) -> Analysis: + out = dict( + valid=None, + level=checks.NOT_ANALYZABLE, + age_months=age_months, + clean_fraction=None, + bad_channels=None, + channels=None, + duration_min=None, + line_noise_db=None, + sleep=None, + checks=[], + metrics=[], + features={}, + error=None, + ) + try: + try: + rec = read.read(edf) + except read.FileNotValid as exc: + verdict = checks.file_not_valid(str(exc)) + return Analysis( + **out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks) + ) + if age_months is None: + header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH) + given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH) + out["age_months"] = age = header if header is not None else given + else: + age = age_months + verdict = checks.validate(rec, mains_hz) + out.update( + valid=verdict.valid, + level=verdict.level, + clean_fraction=verdict.clean_pct / 100, + bad_channels=len(verdict.bad), + channels=len(rec.names) or None, + duration_min=round(rec.duration_s / 60, 2), + line_noise_db=_number(verdict.line_db), + checks=verdict.checks, + ) + if not verdict.valid: + return Analysis(**out) + prep = preprocess.prepare(rec, verdict.bad) + notes = sleep.note_intervals(prep.annotations, prep.duration_s) + states = sleep.states(prep, notes, age) + staged = sleep.stages(prep, states) + metrics, features = biomarkers.measure(prep, states, staged, notes) + out.update( + sleep=bool((states == "sleep").any()), + metrics=[ + Metric( + code, + _number(value), + {k: _number(v) for k, v in electrodes.items()}, + {k: _number(v) for k, v in zones.items()}, + ) + for code, (value, electrodes, zones) in metrics.items() + ], + features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()}, + ) + return Analysis(**out) + except Exception as exc: + return Analysis(**out | dict(error=_error(exc))) diff --git a/models/tea/eeg/biomarkers.py b/models/tea/eeg/biomarkers.py new file mode 100644 index 0000000..a9f10f0 --- /dev/null +++ b/models/tea/eeg/biomarkers.py @@ -0,0 +1,112 @@ +import numpy as np +from scipy.fft import rfft, rfftfreq +from scipy.signal.windows import hann +from scipy.stats import theilslopes +from models.tea.eeg import signals, spikes, spindles +from models.tea.eeg.preprocess import WINDOW_S, Prepared +from models.tea.eeg.sleep import POSTERIOR + +MIN_WINDOWS = 15 +FRONT_BACK = { + "Fp1": 0.95, + "Fp2": 0.95, + "F7": 0.59, + "F3": 0.53, + "Fz": 0.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 = ( + "posterior_rhythm", + "spindles_n2", + "spindles_n3", + "paroxysmal_spikes", + "anteroposterior_gradient", +) + + +def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None: + starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state] + if len(starts) < MIN_WINDOWS or not names: + return None + x, n = (prep.data(names), int(round(WINDOW_S * prep.fs))) + found = [] + for a in (int(round(float(s) * prep.fs)) for s in starts): + if a + n <= len(x) and np.isfinite(x[a : a + n]).all(): + found.append(x[a : a + n].T) + return found or None + + +def posterior_rhythm(prep: Prepared, states) -> float: + names = prep.columns(POSTERIOR) + segments = _segments(prep, names, states, "wake") + if segments is None: + return np.nan + f, power = signals.periodograms(np.stack(segments), prep.fs) + peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))] + found = [hz for hz, _, ok in peaks if ok] + return float(np.median(found)) if len(found) >= 2 else np.nan + + +def delta_gradient(prep: Prepared, states) -> float: + names = [c for c in prep.names if c in FRONT_BACK] + segments = _segments(prep, names, states, "sleep") + if segments is None: + return np.nan + stack = np.stack(segments) + n = stack.shape[-1] + f = rfftfreq(n, 1 / prep.fs) + power = np.abs(rfft((stack - stack.mean(axis=-1, keepdims=True)) * hann(n, sym=True))) ** 2 + delta = np.median(power[..., (f >= 0.5) & (f < 4)].sum(axis=-1), axis=0) + log_power = np.log10(np.maximum(delta, 1e-30)) + y = np.array([FRONT_BACK[c] for c in names]) + finite = np.isfinite(log_power) + return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan + + +def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]: + metrics, features = ({}, {}) + rhythm = posterior_rhythm(prep, states) + metrics["posterior_rhythm"] = (rhythm, {}, {}) + features["eeg-posterior-rhythm"] = {"value": rhythm} + for stage in ("N2", "N3"): + found = spindles.detect(prep, staged, stage) + value, zones = spindles.density(found) + electrodes = spindles.enhancement(prep, found, states) + metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones) + features[f"eeg-spindles-{stage.lower()}"] = { + "value": value, + **{f"zone_{z}": v for z, v in zones.items()}, + } + features[f"eeg-spindle-topography-{stage.lower()}"] = { + f"electrode_{e}": v for e, v in electrodes.items() + } + found = spikes.detect(prep, states, intervals) + if found is None: + nan = dict.fromkeys + found = spikes.Spikes( + np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0 + ) + metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones) + features["eeg-spikes"] = { + "value": found.rate, + **{f"electrode_{e}": v for e, v in found.electrodes.items()}, + **{f"zone_{z}": v for z, v in found.zones.items()}, + "minutes": found.minutes, + } + gradient = delta_gradient(prep, states) + metrics["anteroposterior_gradient"] = (gradient, {}, {}) + features["eeg-gradient"] = {"value": gradient} + return ({code: metrics[code] for code in CODES}, features) diff --git a/models/tea/eeg/checks.py b/models/tea/eeg/checks.py new file mode 100644 index 0000000..59a40a5 --- /dev/null +++ b/models/tea/eeg/checks.py @@ -0,0 +1,331 @@ +from dataclasses import dataclass, field +import numpy as np +from models.tea.eeg import signals +from models.tea.eeg.read import Recording + +NEIGHBOURS = { + "Fp1": ("Fp2", "F3", "F7"), + "Fp2": ("Fp1", "F4", "F8"), + "F7": ("Fp1", "F3", "T3"), + "F8": ("Fp2", "F4", "T4"), + "F3": ("Fp1", "F7", "Fz", "C3"), + "F4": ("Fp2", "F8", "Fz", "C4"), + "Fz": ("F3", "F4", "Cz"), + "T3": ("F7", "C3", "T5"), + "T4": ("F8", "C4", "T6"), + "C3": ("F3", "T3", "Cz", "P3"), + "C4": ("F4", "T4", "Cz", "P4"), + "Cz": ("Fz", "C3", "C4", "Pz"), + "T5": ("T3", "P3", "O1"), + "T6": ("T4", "P4", "O2"), + "P3": ("C3", "T5", "Pz", "O1"), + "P4": ("C4", "T6", "Pz", "O2"), + "Pz": ("Cz", "P3", "P4"), + "O1": ("T5", "P3", "O2"), + "O2": ("T6", "P4", "O1"), +} +EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")} +MIN_CLEAN_PCT = 60.0 +MIN_COVERAGE = 0.9 +MAX_BAD_SCALP = 2 +MIN_SCALP = 12 +MAX_LINE_DB = 45.0 +NOT_ANALYZABLE = "not_analyzable" + + +@dataclass(frozen=True) +class Validation: + valid: bool + level: str + bad: dict[str, list[str]] + clean_pct: float + line_db: float + checks: list[dict] = field(default_factory=list) + + @property + def ears_usable(self) -> bool: + return all((ear not in self.bad for ear in ("A1", "A2"))) + + +def check( + code, + *, + electrode=None, + value=None, + text=None, + unit=None, + low=None, + high=None, + decisive=False, + abnormal=False, +) -> dict: + return dict( + code=code, + electrode=electrode, + value=value, + text=text, + unit=unit, + low=low, + high=high, + decisive=decisive, + abnormal=abnormal, + ) + + +def file_not_valid(reason: str) -> Validation: + rows = [check("file", text=reason, decisive=True, abnormal=True)] + return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows) + + +def _filtered(x, fs, mains_hz, lo, hi): + return signals.bandpass(signals.notch(x, fs, mains_hz), fs, lo, hi) + + +def _temporal(v: np.ndarray) -> list[tuple[str, str]]: + finite = v[np.isfinite(v)] + if len(finite) < 10 or np.std(finite) < 0.5: + return [("dead-channel", "dead channel")] + out = [] + if np.mean(np.abs(np.diff(finite)) < 1e-09) > 0.5: + out.append(("frozen", "frozen")) + if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001: + out.append(("saturated", "saturated")) + if np.isinf(v).any(): + out.append(("inf-values", "Inf values")) + return out + + +def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: + size = int(10 * fs) + blocks = len(y) // size + low, high = (np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan)) + if blocks < 6: + return (low, high) + sd = np.full((blocks, y.shape[1]), np.nan) + for b in range(blocks): + block = y[b * size : (b + 1) * size] + if np.isfinite(block).all(): + sd[b] = block.std(axis=0) + with np.errstate(all="ignore"): + relative = sd / np.maximum(np.nanmedian(sd, axis=1, keepdims=True), 1e-12) + for i in range(y.shape[1]): + v = relative[:, i] + v = v[np.isfinite(v) & (v > 0)] + if len(v) >= 6: + low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35)) + high[i] = np.mean(v > 4.0) + return (low, high) + + +def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]: + finite = np.isfinite(y).all(axis=1) + if finite.sum() < 200 or len(scalp) < 2: + return {} + r = np.abs(np.corrcoef(y[finite][:, scalp].T)) + index = {names[i]: k for k, i in enumerate(scalp)} + out = {} + for name, k in index.items(): + near = [index[n] for n in NEIGHBOURS.get(name, ()) if n in index] + far = [j for j in index.values() if j != k and j not in near] + if not near: + continue + best = max(near, key=lambda j: r[k, j]) + if r[k, best] > 0.99 and (not (far and max((r[k, j] for j in far)) > 0.99)): + out[name] = next((n for n, j in index.items() if j == best)) + return out + + +def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]: + out = {} + for ear, around in EAR_NEIGHBOURS.items(): + present = [n for n in around if n in names] + if ear not in names or len(present) < 2: + continue + cols = [names.index(ear)] + [names.index(n) for n in present] + rows = np.isfinite(y[:, cols]).all(axis=1) + if rows.sum() < fs * 30: + continue + r = np.abs(np.corrcoef(y[rows][:, cols].T)) + between = [r[a, b] for a in range(1, len(cols)) for b in range(a + 1, len(cols))] + out[ear] = (float(np.nanmax(r[0, 1:])), float(np.nanmedian(between))) + return out + + +def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]: + x, fs, names, kinds = (rec.x, rec.fs, list(rec.names), rec.kinds()) + reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)} + dead = { + name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")] + } + notched = signals.notch(x, fs, mains_hz) + y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9)) + y40 = signals.bandpass(notched, fs, 1.0, 40.0) + scalp = [i for i, name in enumerate(names) if kinds[name] == "eeg"] + rms = np.nanstd(y45, axis=0) + median = float(np.nanmedian(rms[scalp])) if scalp else np.nan + ratio = rms / median if np.isfinite(median) and median > 0 else np.full(len(names), np.nan) + low, burst = _contact(y45, fs) + bridges = _bridges(y40, names, scalp) + ears = _ears(y40, fs, names) + missing = 1 - np.isfinite(x).mean(axis=0) + for i, name in enumerate(names): + found, k = (reasons[name], kinds[name]) + if missing[i] > missing.min() + 0.02: + excess = 100 * (missing[i] - missing.min()) + found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)")) + if name in dead: + continue + if k == "eeg" and name in bridges: + found.append(("bridge", f"bridge with {bridges[name]}")) + if k in ("eeg", "ear") and np.isfinite(ratio[i]) and (ratio[i] > 4.0): + found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median")) + if name in ears and ears[name][1] > 0.2 and (ears[name][0] < 0.5 * ears[name][1]): + c, e = ears[name] + found.append( + ( + "does-not-correlate", + f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})", + ) + ) + if np.isfinite(low[i]) and low[i] > 0.1: + found.append( + ( + "intermittent-contact", + f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)", + ) + ) + if k in ("eeg", "ear") and np.isfinite(burst[i]) and (burst[i] > 0.05): + found.append( + ( + "intermittent-bursts", + f"intermittent contact by bursts ({100 * burst[i]:.0f}% of blocks above 4 x the montage)", + ) + ) + if k in ("eog", "ecg"): + v = x[:, i][np.isfinite(x[:, i])] + if np.sqrt(np.mean(v**2)) > 20000: + found.append( + ( + "aux-amplitude", + f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, out of range even for {k.upper()}", + ) + ) + return {name: found for name, found in reasons.items() if found} + + +def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]: + n = int(4 * fs) + lines = signals.fixed_lines(y, fs, f_max=44.0) + starts = list(range(0, len(y) - n + 1, n)) + segments = [y[a : a + n] for a in starts] + whole = [bool(np.isfinite(s).all()) for s in segments] + emg = {} + if any(whole): + stack = np.stack([s.T for s, ok in zip(segments, whole, strict=True) if ok]) + f, power = signals.periodograms(stack, fs) + power = np.moveaxis(power, -1, 0) + high = signals.band_power(f, power, 30.0, 45.0, lines) + low = signals.band_power(f, power, 4.0, 13.0, lines) + ratio = np.median(high / np.maximum(low, 1e-12), axis=1) + emg = dict(zip([a for a, ok in zip(starts, whole, strict=True) if ok], ratio, strict=True)) + out = [] + for a, s, ok in zip(starts, segments, whole, strict=True): + if not ok: + out.append((a / fs, (a + n) / fs, "gap")) + continue + p2p = float(np.max(s.max(axis=0) - s.min(axis=0))) + variance = float(np.mean(s.var(axis=0))) + common = float(s.mean(axis=1).var() / variance) if variance > 0 else np.nan + muscle = float(emg[a]) + suspect = p2p > 800 or (np.isfinite(muscle) and muscle > 0.6) or common > 0.8 + out.append((a / fs, (a + n) / fs, "suspect" if suspect else "clean")) + return out + + +def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float): + x, fs, kinds = (rec.x, rec.fs, rec.kinds()) + columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")] + y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0) + rms, flat = ({}, {}) + for k, i in enumerate(columns): + v = y[:, k][np.isfinite(y[:, k])] + rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan + flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-09)) if len(v) > 1 else 1.0 + scalp = rec.of("eeg") + median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan + triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5] + minutes = rec.duration_s * clean_pct / 100 / 60 + base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP + if not (base and clean_pct >= 30 and (minutes >= 3)): + level = NOT_ANALYZABLE + elif not (clean_pct >= 50 and minutes >= 3): + level = "partial" + elif {"A1", "A2"} & {n for n in bad if kinds[n] == "ear"}: + level = "no_ear_reference" + else: + level = "complete" + return (level, triaged) + + +def validate(rec: Recording, mains_hz: float) -> Validation: + flagged = bad_channels(rec, mains_hz) + scalp = rec.of("eeg") + usable = [n for n in scalp if n not in flagged] + qc = usable if len(usable) >= 2 else scalp + y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0) + windows = window_qc(y, rec.fs) + clean_pct = 100.0 * sum((v == "clean" for *_, v in windows)) / max(len(windows), 1) + coverage = float(np.isfinite(rec.x).all(axis=1).mean()) + columns = [rec.names.index(n) for n in scalp] if scalp else slice(None) + db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz) + line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan + level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage) + rows = [ + check(code, electrode=name, text=reason, abnormal=True) + for name, found in flagged.items() + for code, reason in found + ] + rows += [ + check( + "clean-windows", + value=clean_pct, + unit="%", + low=MIN_CLEAN_PCT, + abnormal=clean_pct < MIN_CLEAN_PCT, + decisive=True, + ), + check( + "internal-coverage", + value=coverage, + unit="fraction", + low=MIN_COVERAGE, + abnormal=coverage < MIN_COVERAGE, + decisive=True, + ), + check( + "bad-scalp-triage", + value=float(len(triaged)), + unit="electrodes", + high=float(MAX_BAD_SCALP), + abnormal=len(triaged) > MAX_BAD_SCALP, + decisive=True, + ), + check( + "usable-scalp", + value=float(len(usable)), + unit="electrodes", + low=float(MIN_SCALP), + abnormal=len(usable) < MIN_SCALP, + decisive=True, + ), + check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True), + ] + if np.isfinite(line): + rows.append( + check( + "line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB + ) + ) + valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and (len(usable) >= MIN_SCALP) + bad = {name: [reason for _, reason in found] for name, found in flagged.items()} + return Validation(valid, level, bad, clean_pct, line, rows) diff --git a/models/tea/eeg/curves.py b/models/tea/eeg/curves.py new file mode 100644 index 0000000..b3ee2a8 --- /dev/null +++ b/models/tea/eeg/curves.py @@ -0,0 +1,163 @@ +import math +from dataclasses import dataclass +import numpy as np +import pandas as pd +from scipy import stats + +QUANTILES = {"p5": 0.05, "p25": 0.25, "median": 0.5, "p75": 0.75, "p95": 0.95} +CURVE_AGES = np.exp(np.linspace(np.log(1.0), np.log(216.0), 120)) +LOG_WIDTH = 0.2 +MIN_EFFECTIVE = 30 +COUNT_AGES = (16.0, 37.0) +Z_MAX = 8.0 +EXPOSURE = "minutes" + + +@dataclass(frozen=True) +class Scenario: + metric: str + parts: tuple[str, ...] + stage: str | None = None + counts: bool = False + + +SCENARIOS = { + "eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)), + "eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"), + "eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"), + "eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"), + "eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"), + "eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True), + "eeg-gradient": Scenario("anteroposterior_gradient", ("value",)), +} +PREFIX = {"electrodes": "electrode_", "zones": "zone_"} + + +def _weighted_quantile(x: np.ndarray, w: np.ndarray, q: float) -> float: + order = np.argsort(x) + x, w = (x[order], w[order]) + return float(np.interp(q, (np.cumsum(w) - 0.5 * w) / w.sum(), x)) + + +def _curve(values: np.ndarray, ages: np.ndarray) -> dict: + ok = np.isfinite(values) & np.isfinite(ages) & (ages > 0) + v, log_age = (values[ok], np.log(ages[ok])) + curve = {"age_months": [], "n_effective": [], **{q: [] for q in QUANTILES}} + for a in CURVE_AGES: + w = np.exp(-0.5 * ((log_age - np.log(a)) / LOG_WIDTH) ** 2) + n_effective = w.sum() ** 2 / (w**2).sum() if w.sum() > 0 else 0.0 + inside = len(log_age) and log_age.min() <= np.log(a) <= log_age.max() + curve["age_months"].append(round(float(a), 3)) + curve["n_effective"].append(round(float(n_effective), 1)) + for name, q in QUANTILES.items(): + enough = n_effective >= MIN_EFFECTIVE and inside + curve[name].append(round(_weighted_quantile(v, w, q), 4) if enough else None) + return { + "kind": "curves", + "log_width": LOG_WIDTH, + "min_effective": MIN_EFFECTIVE, + "curve": curve, + } + + +def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict: + n = np.round(values * exposure) + keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0) + keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1]) + n, x = (n[keep], exposure[keep]) + rate = float(n.sum() / x.sum()) if x.sum() > 0 else float("nan") + mu = rate * x + excess = float(((n - mu) ** 2 - n).sum()) + k = float((mu**2).sum() / excess) if excess > 0 else None + return { + "kind": "count_rate", + "ages": list(COUNT_AGES), + "rate": rate, + "k": k, + "reference": int(keep.sum()), + "events": int(n.sum()), + } + + +def train(features: pd.DataFrame, scenario: str) -> dict: + counts = SCENARIOS[scenario].counts + ages = features["age_months"].to_numpy(float) + out = {} + for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"): + values = pd.to_numeric(features[name]).to_numpy(float) + if counts: + out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float)) + else: + out[name] = _curve(values, ages) + return out + + +def _number(v) -> float | None: + return float(v) if v is not None and math.isfinite(v) else None + + +def _score_curve(baseline: dict, value: float, age: float) -> dict: + curve = pd.DataFrame(baseline["curve"]).astype(float).dropna() + out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) + if not len(curve) or not age > 0: + return out + log_ages, at = (np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0])) + if not log_ages.min() <= at <= log_ages.max(): + return out + q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES} + side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"] + z = (value - q["median"]) / (side / 1.645) if side > 0 else None + outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0 + return { + "z": _number(z), + "outside": outside, + "p5": q["p5"], + "median": q["median"], + "p95": q["p95"], + } + + +def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict: + out = dict.fromkeys(("z", "outside", "p5", "median", "p95")) + rate, k = (baseline["rate"], baseline["k"]) + lo, hi = baseline["ages"] + if exposure is None or not math.isfinite(rate) or (not (exposure > 0 and lo <= age < hi)): + return out + n, mu = (float(np.round(value * exposure)), rate * exposure) + law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu)) + tail, at = (law.sf(n - 1), law.pmf(n)) + z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX)) + p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95)) + return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95} + + +def score( + baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None +) -> dict: + value, age_months = (_number(value), _number(age_months)) + if value is None or age_months is None: + return dict.fromkeys(("z", "outside", "p5", "median", "p95")) + if baseline["kind"] == "count_rate": + return _score_count(baseline, value, age_months, _number(exposure)) + return _score_curve(baseline, value, age_months) + + +def deviations(models: dict[str, dict], analysis) -> dict[str, dict]: + out = {m.code: {} for m in analysis.metrics} + metrics = {m.code: m for m in analysis.metrics} + for name, scenario in SCENARIOS.items(): + model, metric = (models.get(name), metrics.get(scenario.metric)) + if model is None or metric is None: + continue + exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None + for part in scenario.parts: + if part == "value": + out[metric.code]["value"] = score( + model["value"], metric.value, analysis.age_months, exposure + ) + else: + out[metric.code][part] = { + key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure) + for key, v in getattr(metric, part).items() + } + return out diff --git a/models/tea/eeg/data/hk1k_state.json b/models/tea/eeg/data/hk1k_state.json new file mode 100644 index 0000000..3eca189 --- /dev/null +++ b/models/tea/eeg/data/hk1k_state.json @@ -0,0 +1,11 @@ +{ + "source": "HK1K reference of the sleep-depth index (223 studies, 16-36 months): each window feature standardised by its median and dispersion, the posterior rhythm's median a line on log10 age; signs and weights of the weighted mean; cut-offs wake < -1.2327 <= drowsy < -0.3032 <= sleep", + "features": { + "delta_beta": {"median": 1.6117037688126001, "dispersion": 0.3097998485854789, "sign": 1, "weight": 1.0}, + "posterior_rhythm": {"slope": 4.934510806157707, "intercept": 0.999676072265559, "median": 7.765061458878031, "dispersion": 1.021788597296859, "sign": -1, "weight": 1.0}, + "sigma": {"median": 0.019957376774209706, "dispersion": 0.012167857665235331, "sign": 1, "weight": 0.7}, + "muscle": {"median": 0.0742822337558628, "dispersion": 0.056777351044491706, "sign": -1, "weight": 0.7}, + "alpha": {"median": 0.03498707283228359, "dispersion": 0.016352123389996105, "sign": -1, "weight": 0.6} + }, + "cuts": [-1.2326590642152986, -0.3031551001049524] +} diff --git a/models/tea/eeg/preprocess.py b/models/tea/eeg/preprocess.py new file mode 100644 index 0000000..e165f94 --- /dev/null +++ b/models/tea/eeg/preprocess.py @@ -0,0 +1,51 @@ +import warnings +from dataclasses import dataclass +import numpy as np +from models.tea.eeg import signals +from models.tea.eeg.checks import window_qc +from models.tea.eeg.read import Recording + +NOTCH_HZ = 60.0 +NOTCH_MIN_DB = 6.0 +WINDOW_S = 4.0 +STEP_S = 2.0 + + +@dataclass(frozen=True) +class Prepared: + x: np.ndarray + names: tuple[str, ...] + fs: float + starts: np.ndarray + unclean: tuple[tuple[float, float], ...] + annotations: tuple[tuple[float, float, str], ...] + + @property + def duration_s(self) -> float: + return len(self.x) / self.fs + + def columns(self, wanted) -> list[str]: + return [name for name in wanted if name in self.names] + + def data(self, names) -> np.ndarray: + return self.x[:, [self.names.index(name) for name in names]] + + +def prepare(rec: Recording, bad) -> Prepared: + scalp = [name for name in rec.of("eeg") if name not in bad] + x = rec.x[:, [rec.names.index(name) for name in scalp]] + if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB: + x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5) + gaps = ~np.isfinite(x).all(axis=1) + y = signals.bandpass(x, rec.fs, 0.5, 100.0) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + referenced = y - np.nanmean(y, axis=1, keepdims=True) + referenced = np.asfortranarray(referenced * 1e-06 * 1000000.0) + qc = signals.bandpass(x, rec.fs, 0.5, 45.0) + qc[gaps] = np.nan + unclean = tuple( + ((float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean") + ) + starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-09, STEP_S) + return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations) diff --git a/models/tea/eeg/read.py b/models/tea/eeg/read.py new file mode 100644 index 0000000..a307377 --- /dev/null +++ b/models/tea/eeg/read.py @@ -0,0 +1,116 @@ +import io +import re +from dataclasses import dataclass +from datetime import date, datetime +import edfio +import mne +import numpy as np + +STANDARD = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz" +CANONICAL = {name.upper(): name for name in STANDARD.split()} +RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"} +AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC")) +EARS = {"A1", "A2"} +EOG = {"LOC", "ROC"} +UNKNOWN_START = date(1985, 1, 1) + + +class FileNotValid(ValueError): + pass + + +def normalize(label: str) -> str | None: + text = str(label).strip() + if not text or "ANNOT" in text.upper(): + return None + stem = re.sub("^\\s*(EEG|ECG|EKG|EOG|EMG|POL)\\s+", "", text, flags=re.I).split("-")[0] + key = re.sub("[^A-Z0-9]", "", stem.strip().upper()) + if key in CANONICAL: + name = CANONICAL[key] + return RENAMED.get(name, name) + return next((name for part, name in AUXILIARY if part in text.upper()), None) + + +def kind(name: str) -> str: + if name in EARS: + return "ear" + if name in EOG: + return "eog" + return "ecg" if name == "EKG" else "eeg" + + +@dataclass(frozen=True) +class Recording: + x: np.ndarray + fs: float + names: tuple[str, ...] + annotations: tuple[tuple[float, float, str], ...] + start: date | None + birthday: date | None + + @property + def duration_s(self) -> float: + return len(self.x) / self.fs + + def kinds(self) -> dict[str, str]: + return {name: kind(name) for name in self.names} + + def of(self, *kinds: str) -> list[str]: + return [name for name in self.names if kind(name) in kinds] + + +def _kept(edf: bytes) -> list[tuple[str, str]]: + if len(edf) < 256: + raise FileNotValid("file too short to be an EDF (header < 256 bytes)") + try: + signals = edfio.read_edf(edf, lazy_load_data=True).signals + except Exception as exc: + raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None + if not signals: + raise FileNotValid("the EDF declares zero signals") + named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals] + named = [(label, name, rate) for label, name, rate in named if name is not None] + if not named: + raise FileNotValid("no recognised channel") + rates = [rate for _, _, rate in named] + fs = max(set(rates), key=rates.count) + kept, seen = ([], set()) + for label, name, rate in named: + if abs(rate - fs) <= 1e-06 and name not in seen: + seen.add(name) + kept.append((label, name)) + return kept + + +def read(edf: bytes) -> Recording: + kept = _kept(edf) + options = dict(include=[label for label, _ in kept], preload=True, verbose="error") + try: + raw = mne.io.read_raw_edf(io.BytesIO(edf), **options) + except Exception as exc: + if "latin1" not in str(exc): + raise + raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options) + raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name}) + names = [name for name in raw.ch_names if name in {n for _, n in kept}] + x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1000000.0 + start = raw.info.get("meas_date") + born = (raw.info.get("subject_info") or {}).get("birthday") + notes = tuple( + ((float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations) + ) + return Recording( + x=x, + fs=float(raw.info["sfreq"]), + names=tuple(names), + annotations=notes, + start=start.date() if isinstance(start, datetime) else start, + birthday=date(*born) if isinstance(born, tuple) else born, + ) + + +def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None: + if start is None or birthday is None or start == UNKNOWN_START or (birthday > start): + return None + months = round((start - birthday).days / days_per_month, 1) + return months if months <= 216 else None diff --git a/models/tea/eeg/reference.py b/models/tea/eeg/reference.py new file mode 100644 index 0000000..ce759fa --- /dev/null +++ b/models/tea/eeg/reference.py @@ -0,0 +1,43 @@ +from pathlib import Path +import pandas as pd +from models import cluster +from models.tea.eeg.analysis import analyze +from models.tea.eeg.curves import SCENARIOS + +NAME = "hk1k" +MAINS_HZ = 50.0 +AGES = (16.0, 36.0) + + +def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]: + table = pd.read_csv(ages_table) + years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True)) + found = [] + for path in sorted((p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf")): + age = round(float(years[path.name] * 12), 1) if path.name in years else None + if age is not None and age == age and (ages[0] <= age <= ages[1]): + found.append((path, age)) + return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)] + + +def _one(key: str, edf: bytes, age: float) -> dict: + a = analyze(edf, age_months=age, mains_hz=MAINS_HZ) + return { + "key": key, + "age_months": age, + "valid": a.valid, + "error": a.error, + "features": a.features, + } + + +def measure(studies) -> list[dict]: + 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]: + usable = [s for s in measured if s["valid"] and s["error"] is None] + return { + name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable]) + for name in SCENARIOS + } diff --git a/models/tea/eeg/signals.py b/models/tea/eeg/signals.py new file mode 100644 index 0000000..9963dd5 --- /dev/null +++ b/models/tea/eeg/signals.py @@ -0,0 +1,134 @@ +import numpy as np +from mne.time_frequency import psd_array_welch +from scipy import signal +from scipy.ndimage import median_filter + + +def runs(valid: np.ndarray) -> list[tuple[int, int]]: + edges = np.diff(np.concatenate([[False], np.asarray(valid, bool), [False]]).astype(int)) + return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True)) + + +def by_runs(x: np.ndarray, fn, minimum: int) -> np.ndarray: + x = np.asarray(x, float) + out = np.full_like(x, np.nan) + for a, b in runs(np.isfinite(x).all(axis=1)): + if b - a >= minimum: + out[a:b] = fn(x[a:b]) + return out + + +def bandpass(x: np.ndarray, fs: float, lo: float, hi: float, order: int = 4) -> np.ndarray: + sos = signal.butter(order, [lo / (fs / 2), hi / (fs / 2)], btype="band", output="sos") + minimum = max(3 * (2 * len(sos) + 1), int(fs)) + return by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum) + + +def notch(x: np.ndarray, fs: float, f0: float, width: float = 1.5) -> np.ndarray: + centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98] + + def interpolate(run): + f = np.fft.rfftfreq(len(run), 1 / fs) + spectrum = np.fft.rfft(run, axis=0) + for c in centres: + inside = (f >= c - width) & (f <= c + width) + left = (f >= c - 3 * width) & (f < c - width) + right = (f > c + width) & (f <= c + 3 * width) + if not (inside.any() and left.any() and right.any()): + continue + k = np.linspace(0, 1, int(inside.sum()))[:, None] + target = ( + np.abs(spectrum[left]).mean(axis=0)[None, :] * (1 - k) + + np.abs(spectrum[right]).mean(axis=0)[None, :] * k + ) + current = spectrum[inside] + magnitude = np.abs(current) + phase = np.where(magnitude > 0, current / np.maximum(magnitude, 1e-30), 1.0) + spectrum[inside] = target * phase + return np.fft.irfft(spectrum, n=len(run), axis=0) + + return by_runs(x, interpolate, max(int(2 * fs), 256)) + + +def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray: + finite = np.isfinite(x).all(axis=1) + if not finite.any(): + return np.full(x.shape[1], np.nan) + run = x[finite] - x[finite].mean(axis=0) + f = np.fft.rfftfreq(len(run), 1 / fs) + power = np.abs(np.fft.rfft(run * np.hanning(len(run))[:, None], axis=0)) ** 2 + peak = power[(f >= f0 - 0.6) & (f <= f0 + 0.6)].mean(axis=0) + around = (f >= f0 - 6) & (f <= f0 - 2) | (f >= f0 + 2) & (f <= f0 + 6) + near = power[around].mean(axis=0) + with np.errstate(divide="ignore", invalid="ignore"): + return 10 * np.log10(np.where(near > 0, peak / near, np.nan)) + + +def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: + n = segments.shape[-1] + power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + return (f, power) + + +def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]: + n = int(round(8 * fs)) + f = np.fft.rfftfreq(n, 1 / fs) + taper = np.hanning(n)[:, None] + total, count = (None, 0) + for a in range(0, len(x) - n + 1, n): + segment = x[a : a + n] + if np.isfinite(segment).all(): + power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2 + total = power if total is None else total + power + count += 1 + if not count: + return [] + db = 10 * np.log10(np.maximum(np.median(total / count, axis=1), 1e-30)) + df = float(f[1] - f[0]) + half = max(1, int(round(2 / df))) + prominence = db - median_filter(db, size=2 * half + 1, mode="nearest") + f_max = min(f_max, fs / 2 - 2) + found = [] + for i in range(1, len(f) - 1): + p = prominence[i] + if not 1 <= f[i] <= f_max or p < 6 or p < prominence[i - 1] or (p < prominence[i + 1]): + continue + a = b = i + while a > 0 and prominence[a - 1] >= p - 3: + a -= 1 + while b < len(f) - 1 and prominence[b + 1] >= p - 3: + b += 1 + if (b - a + 1) * df <= 0.5: + found.append((round(float(f[i]), 3), round(float(p), 1))) + kept = [] + for hz, db_up in sorted(found, key=lambda line: -line[1]): + if all((abs(hz - other) > 0.5 for other, _ in kept)): + kept.append((hz, db_up)) + return [hz for hz, _ in kept] + + +def band_power(f, power, lo, hi, lines=(), include_hi=False): + band = (f >= lo) & (f <= hi if include_hi else f < hi) + clean = band.copy() + for line in lines: + clean &= np.abs(f - line) > 1.0 + if not clean.any(): + return np.full(power.shape[1:], np.nan) if power.ndim > 1 else np.nan + return power[clean].sum(axis=0) * (band.sum() / clean.sum()) + + +def dominant_peak(f: np.ndarray, power: np.ndarray) -> tuple[float, float, bool]: + usable = (f >= 1.5) & (f <= 45) & (power > 0) + background = usable & ~((f >= 4) & (f <= 16)) + if background.sum() < 5: + return (np.nan, np.nan, False) + line = np.polyfit(np.log10(f[background]), np.log10(power[background]), 1) + residual = 10 * (np.log10(power[usable]) - np.polyval(line, np.log10(f[usable]))) + fu = f[usable] + band = (fu >= 3) & (fu <= 14) + if not band.any(): + return (np.nan, np.nan, False) + i = int(np.argmax(residual[band])) + prominence = float(residual[band][i]) + found = prominence >= 1.5 and 0 < i < int(band.sum()) - 1 + return (float(fu[band][i]) if found else np.nan, prominence, bool(found)) diff --git a/models/tea/eeg/sleep.py b/models/tea/eeg/sleep.py new file mode 100644 index 0000000..ce830ac --- /dev/null +++ b/models/tea/eeg/sleep.py @@ -0,0 +1,211 @@ +import json +import unicodedata +from pathlib import Path +import numpy as np +from models.tea.eeg import signals +from models.tea.eeg.preprocess import WINDOW_S, Prepared + +REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text()) +NOTE_WORDS = { + "photic": ("fotic", "photic", "flash", "estimulacion luminosa"), + "hyperventilation": ("hv", "hipervent", "hypervent"), + "eyes_open": ("ojos abiertos", "eyes open", "oa"), + "eyes_closed": ("ojos cerrados", "eyes closed", "oc"), + "sleep": ( + "sueno", + "dormido", + "sleep", + "somnol", + "husos", + "spindle", + "fase i", + "fase ii", + "n1", + "n2", + "n3", + ), + "awake": ("despierta", "despierto", "arousal", "vigilia"), + "crying": ("llanto", "llora", "cry"), + "movement": ("movimiento", "movement", "artefacto de movimiento"), + "feeding": ("come", "alimenta", "biberon", "lactancia"), +} +EXCLUDED = ("crying", "movement", "disconnection") +MASKED = (*EXCLUDED, "photic", "hyperventilation") +STATES = np.array(["wake", "drowsy", "sleep"], dtype=object) +BANDS = { + "delta": (0.5, 4), + "theta": (4, 8), + "alpha": (8, 13), + "sigma": (11, 16), + "beta": (16, 30), + "high": (20, 40), +} +POSTERIOR = ("O1", "O2", "P3", "P4") +CENTRAL = ("C3", "C4", "Cz") +FRONTAL = ("F3", "F4", "Fz") + + +def note_state(text: str) -> str | None: + kept = str(text or "").replace("ñ", "\x00").replace("Ñ", "\x01") + plain = "".join( + (c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn") + ) + plain = plain.replace("\x00", "ñ").replace("\x01", "Ñ").lower().strip() + return next( + (state for state, words in NOTE_WORDS.items() if any((w in plain for w in words))), None + ) + + +def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]: + notes = sorted(annotations, key=lambda note: note[0]) + found = [] + for i, (t0, length, text) in enumerate(notes): + state = note_state(text) + if state is None: + continue + if length > 0: + t1 = t0 + length + else: + following = next((n[0] for n in notes[i + 1 :] if note_state(n[2])), None) + t1 = min(t0 + 60.0, following if following else t0 + 60.0) + if t1 - t0 >= 1: + found.append((t0, t1, state)) + found.sort(key=lambda piece: piece[0]) + full, cursor = ([], 0.0) + for t0, t1, state in found: + if t0 - cursor >= 1: + full.append((cursor, t0, "unmarked")) + full.append((t0, t1, state)) + cursor = max(cursor, t1) + if duration_s - cursor >= 1: + full.append((cursor, duration_s, "unmarked")) + pieces = [(round(t0, 2), round(t1, 2), state) for t0, t1, state in full] + return [(t0, t1 - t0, state) for t0, t1, state in pieces] + + +def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]: + overlap = {} + for onset, length, state in intervals: + lo, hi = (max(t0, onset), min(t1, onset + length)) + if hi > lo: + overlap[state] = overlap.get(state, 0) + (hi - lo) + if not overlap: + return ("unlabelled", False) + dominant = max(overlap, key=overlap.get) + return (dominant, overlap[dominant] < 0.8 * (t1 - t0)) + + +def mask(prep: Prepared, intervals) -> np.ndarray: + out = np.zeros(len(prep.x), bool) + spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)] + for onset, length in spans: + out[int(onset * prep.fs) : int((onset + length) * prep.fs)] = True + return out + + +def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]: + fs, x, names = (prep.fs, prep.x, list(prep.names)) + n, step = (int(WINDOW_S * fs), int(2 * fs)) + starts = [ + a + for a in range(0, len(x) - n + 1, step) + if np.isfinite(x[a : a + n]).all() and (not masked[a : a + n].any()) + ] + if not starts: + return ([], {}) + f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs) + band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()} + total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12) + central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names)))) + posterior = [names.index(c) for c in POSTERIOR if c in names] + delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1) + features = { + "delta_beta": np.log10(np.clip(delta_beta, 1e-06, None)), + "sigma": np.median((band["sigma"] / total)[:, central], axis=1), + "muscle": np.median( + band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1 + ), + "alpha": np.median(band["alpha"] / total, axis=1), + } + if posterior: + peaks = [ + signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts)) + ] + features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks]) + return (starts, features) + + +def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray: + z, weights = ([], []) + for name, ref in REFERENCE["features"].items(): + if name not in features: + continue + if "slope" in ref and age_months and (age_months > 0): + median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"] + else: + median = ref["median"] + z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-09)) + weights.append(ref["weight"]) + w = np.array(weights, float) + return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6) + + +def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray: + starts, features = _features(prep, mask(prep, intervals)) + out = np.full(len(prep.starts), "", dtype=object) + if not starts: + return out + labels = STATES[np.digitize(depth(features, age_months), REFERENCE["cuts"])] + by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True)) + out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts] + return out + + +def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]: + y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0] + sign = np.sign(y) + sign[sign == 0] = 1 + crossings = np.flatnonzero(np.diff(sign) != 0) + 1 + waves = [] + for j, c0 in enumerate(crossings): + if not y[c0] < 0: + continue + if j + 2 >= len(crossings): + break + c1, c2 = (crossings[j + 1], crossings[j + 2]) + negative, total = ((c1 - c0) / fs, (c2 - c0) / fs) + if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0): + continue + p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1]))) + if 75.0 <= p2p <= 300.0: + waves.append((round(c0 / fs, 3), round(total, 3))) + return waves + + +def _merged(waves: list[tuple[float, float]]) -> np.ndarray: + if not waves: + return np.empty((0, 2)) + a = np.array([onset for onset, _ in waves]) + b = a + np.array([length for _, length in waves]) + order = np.argsort(a) + out = [[a[order[0]], b[order[0]]]] + for i in order[1:]: + if a[i] <= out[-1][1]: + out[-1][1] = max(out[-1][1], b[i]) + else: + out.append([a[i], b[i]]) + return np.array(out) + + +def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray: + waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)] + covered = _merged(waves) + out = np.full(len(prep.starts), "", dtype=object) + for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)): + if label != "sleep": + continue + t0, t1 = (start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0) + overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None) + coverage = min(overlap.sum() / max(t1 - t0, 1e-09), 1.0) if len(covered) else 0.0 + out[k] = "N3" if round(coverage, 4) >= 0.2 else "N2" + return out diff --git a/models/tea/eeg/spikes.py b/models/tea/eeg/spikes.py new file mode 100644 index 0000000..de6b970 --- /dev/null +++ b/models/tea/eeg/spikes.py @@ -0,0 +1,204 @@ +from dataclasses import dataclass +import numpy as np +import pandas as pd +from models.tea.eeg import signals +from models.tea.eeg.checks import NEIGHBOURS +from models.tea.eeg.preprocess import WINDOW_S, Prepared +from models.tea.eeg.sleep import EXCLUDED, window_note +from models.tea.eeg.spindles import ZONES + +ELECTRODES = tuple(NEIGHBOURS) +GATE_S = 2.0 +VERTEX = ("Cz", "Fz", "Pz") +POSTS = ("O1", "O2") +OCULAR = ("Fp1", "Fp2", "F7", "F8") +POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"} +LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4")) +ASLEEP = ("N2", "N3", "sleep") + + +@dataclass(frozen=True) +class Spikes: + rate: float + electrodes: dict[str, float] + zones: dict[str, float] + minutes: float + + +def _mad(v: np.ndarray) -> float: + v = v[np.isfinite(v)] + if not len(v): + return np.nan + return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan + + +def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]: + n = int(GATE_S * fs) + top = min(45, fs / 2 * 0.9) + lines = signals.fixed_lines(x, fs, f_max=top) + f = np.fft.rfftfreq(n, 1 / fs) + taper = np.hanning(n)[:, None] + kept = [] + for a in range(0, len(x) - n + 1, n): + t0, t1 = (a / fs, a / fs + GATE_S) + state, mixed = window_note(t0, t1, intervals) + segment = x[a : a + n] + if not np.isfinite(segment).all() or state in EXCLUDED or mixed: + continue + power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2 + power = power.mean(axis=1) + high = signals.band_power(f, power, 20, top, lines, include_hi=True) + low = signals.band_power(f, power, 4, 13, lines, include_hi=True) + muscle = float(high / max(low, 1e-12)) + frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-09)) + if not (muscle > 1.5 or frozen > 0.5): + kept.append((round(t0, 2), round(t1, 2))) + return kept + + +def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]: + n = len(y) + if i <= 0 or i >= n - 1: + return (np.nan, np.nan) + w = int(500 * fs / 1000) + base = float(np.median(y[max(0, i - w) : min(n, i + w)])) + peak = float(y[i]) - base + if peak == 0.0: + return (np.nan, np.nan) + sign, half, reach = (np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)) + a, low = (i, max(0, i - reach)) + while a > low and sign * (y[a] - base) >= half: + a -= 1 + b, high = (i, min(n - 1, i + reach)) + while b < high and sign * (y[b] - base) >= half: + b += 1 + if b <= a: + return (np.nan, np.nan) + rise, fall = (half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)) + return (float(min(rise, fall)), float((b - a) / fs * 1000.0)) + + +def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]: + y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel() + if np.isfinite(y).sum() < fs * 2: + return [] + slope_mad, amplitude_mad = (_mad(np.diff(y) * fs), _mad(y)) + if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad): + return [] + v = np.abs(y) + peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else [] + after = (int(100 * fs / 1000), int(500 * fs / 1000)) + out = [] + for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad): + slope, width = _flanks(y, int(i), fs) + if not (np.isfinite(slope) and np.isfinite(width) and (20.0 <= width <= 200.0)): + continue + if slope < 6.0 * slope_mad: + continue + a, b = (int(i) + after[0], min(int(i) + after[1], len(y))) + post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0 + out.append( + dict( + channel=channel, + t=float(i) / fs, + sign=int(np.sign(y[i])), + width=width, + size=float(abs(y[i]) / amplitude_mad), + post=post, + ) + ) + return out + + +def _field(c: pd.DataFrame) -> np.ndarray: + times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])} + out = np.zeros(len(c), int) + for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)): + for other in NEIGHBOURS.get(ch, ()): + near = times.get((other, s)) + if near is None: + continue + j = np.searchsorted(near, t) + close = near[max(j - 1, 0) : j + 1] + out[k] += bool(np.any(np.abs(close - t) <= 0.025)) + return out + + +def _merge(c: pd.DataFrame) -> pd.DataFrame: + c = c.iloc[np.argsort(c.t.to_numpy(), kind="quicksort")].reset_index(drop=True) + groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1) + rows = [] + for g in groups: + part = c.iloc[g] + top = c.loc[part["size"].idxmax()] + asleep = top.state in ASLEEP + signs = dict(zip(part.channel, part.sign, strict=True)) + frontal_only = top.channel in OCULAR and (not set(part.channel) & POSTERIOR) + opposite = any( + (a in signs and b in signs and (signs[a] * signs[b] < 0) for a, b in LEFT_RIGHT) + ) + vertex = asleep and top.channel in VERTEX and (float(part.post.max()) > 3.0) + posts = asleep and top.channel in POSTS and (top.sign > 0) and (top.width > 80.0) + rows.append( + dict( + channel=top.channel, + state=top.state, + field=int(part.field.max()), + useful=not (vertex or posts or frontal_only or opposite), + ) + ) + return pd.DataFrame(rows, columns=["channel", "state", "field", "useful"]) + + +def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None: + channels = [c for c in prep.names if c in ELECTRODES] + if len(channels) < 4: + return None + fs = prep.fs + x = np.array(prep.data(channels), dtype=np.float64) + labelled = [ + (s, s + WINDOW_S, label) + for s, label in zip(prep.starts, states, strict=True) + if label in ("wake", "drowsy", "sleep") + ] + + def state_at(t: np.ndarray) -> np.ndarray: + out, open_ = (np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)) + for t0, t1, label in labelled: + hit = open_ & (t0 <= t) & (t < t1) + out[hit], open_ = (label, open_ & ~hit) + return out + + gate = _gate(x, fs, intervals) + minutes = {} + middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate])) + for (t0, t1), state in zip(gate, middles, strict=True): + minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0 + sleep_minutes = float(sum((minutes.get(s, 0.0) for s in ("sleep",)))) + counts = dict.fromkeys(channels, 0) + candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)] + if candidates and gate: + c = pd.DataFrame(candidates) + t = c.t.to_numpy(float) + inside = np.zeros(len(t), bool) + for t0, t1 in gate: + inside |= (t >= t0) & (t < t1) + c = c[inside] + if len(c): + c = c.assign(field=_field(c), state=state_at(c.t.to_numpy())) + found = _merge(c) + found = found[found.useful & (found.field > 0) & (found.state == "sleep")] + for channel, n in found.channel.value_counts().items(): + counts[channel] = int(n) + rounded = round(sleep_minutes, 2) + rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan + electrodes = { + e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan + for e in ELECTRODES + } + zones = {} + for zone, members in ZONES.items(): + present = [e for e in members if e in counts] + total = sum((counts[e] for e in present)) + zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan + return Spikes(rate, electrodes, zones, round(sleep_minutes, 4)) diff --git a/models/tea/eeg/spindles.py b/models/tea/eeg/spindles.py new file mode 100644 index 0000000..e1080d7 --- /dev/null +++ b/models/tea/eeg/spindles.py @@ -0,0 +1,157 @@ +from dataclasses import dataclass +import numpy as np +from scipy.signal import hilbert, welch +from models.tea.eeg import signals +from models.tea.eeg.preprocess import WINDOW_S, Prepared + +CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz") +SIGMA = (11.0, 16.0) +ZONES = { + "frontal_left": ("Fp1", "F3", "F7"), + "frontal_right": ("Fp2", "F4", "F8"), + "frontal_midline": ("Fz",), + "central": ("C3", "Cz", "C4"), + "parietal": ("P3", "Pz", "P4"), + "temporal_left": ("T3", "T5"), + "temporal_right": ("T4", "T6"), + "occipital": ("O1", "O2"), +} + + +@dataclass(frozen=True) +class Spindles: + events: list[tuple[float, float, str]] + minutes: float + channels: list[str] + + +def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: + y = signals.bandpass(x, fs, *SIGMA) + envelope = np.abs(hilbert(np.nan_to_num(y), axis=0)) + k = max(1, int(0.2 * fs)) + envelope = np.apply_along_axis( + lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope + ) + envelope[~np.isfinite(y)] = np.nan + return (y, envelope) + + +def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]: + edges = np.diff(extent.astype(np.int8), prepend=0, append=0) + out = [] + for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True): + if not core[a:b].any(): + continue + if 0.5 <= (b - a) / fs <= 3.0: + out.append((int(a), int(b))) + elif (b - a) / fs > 3.0: + step = int(3.0 * fs) + for c in range(a, b, step): + e = min(c + step, b) + if 0.5 <= (e - c) / fs <= 3.0 and core[c:e].any(): + out.append((int(c), int(e))) + return out + + +def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool: + if not np.isfinite(x).all(): + return False + nperseg = min(len(x), int(fs)) + f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4)) + inside = (f >= SIGMA[0]) & (f <= SIGMA[1]) + flanks = (f >= 5) & (f < SIGMA[0]) | (f > SIGMA[1]) & (f <= 30) + if not inside.any() or not flanks.any(): + return False + if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5: + return False + frequency = np.diff(np.unwrap(np.angle(hilbert(y)))) * fs / (2 * np.pi) + frequency = frequency[np.isfinite(frequency)] + in_band = frequency[(frequency >= SIGMA[0] - 1) & (frequency <= SIGMA[1] + 1)] + if len(in_band) < 0.5 * max(len(frequency), 1): + return False + return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1] + + +def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles: + fs, n = (prep.fs, int(WINDOW_S * prep.fs)) + asleep = np.zeros(len(prep.x), bool) + for start, s in zip(prep.starts, staged, strict=True): + if s == stage: + a = int(round(float(start) * fs)) + asleep[a : a + n] = True + minutes = float(asleep.sum() / fs / 60) + names = prep.columns([c for c in prep.names if c in CHANNELS]) + if minutes < 1 or not names: + return Spindles([], minutes, []) + x = prep.data(names) + y, envelope = _envelope(x, fs) + events = [] + for i, name in enumerate(names): + in_stage = np.where(asleep, envelope[:, i], np.nan) + values = in_stage[np.isfinite(in_stage)] + if len(values) < fs * 30: + continue + median = float(np.median(values)) or 1e-09 + core = max(float(np.percentile(values, 95)), 3 * median) + extent = max(float(np.percentile(values, 70)), 1.6 * median) + finite = np.isfinite(in_stage) + for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs): + if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3: + events.append((round(a / fs, 3), round((b - a) / fs, 3), name)) + return Spindles(events, minutes, names) + + +def density(found: Spindles) -> tuple[float, dict[str, float]]: + zones = dict.fromkeys(ZONES, np.nan) + if not found.events or found.minutes <= 0: + return (np.nan, zones) + counts = {} + for _, _, channel in found.events: + counts[channel] = counts.get(channel, 0) + 1 + for zone, electrodes in ZONES.items(): + searched = [e for e in electrodes if e in found.channels] + if searched: + total = sum((counts.get(e, 0) for e in searched)) + zones[zone] = total / (found.minutes * len(searched)) + per_channel = len(found.events) / found.minutes / max(len(found.channels), 1) + return (round(per_channel, 3), zones) + + +def _episodes(events) -> list[list[float]]: + if not events: + return [] + a = np.array([onset for onset, _, _ in events], float) + b = a + np.array([length for _, length, _ in events], float) + order = np.argsort(a) + out = [[a[order[0]], b[order[0]]]] + for i in order[1:]: + if a[i] <= out[-1][1]: + out[-1][1] = max(out[-1][1], b[i]) + else: + out.append([a[i], b[i]]) + return out + + +def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]: + out = dict.fromkeys(CHANNELS, np.nan) + use = prep.columns(CHANNELS) + episodes = _episodes(found.events) + if not use or not episodes: + return out + fs = prep.fs + y = signals.bandpass(prep.data(use), fs, *SIGMA) + envelope = signals.by_runs(y, lambda run: np.abs(hilbert(run, axis=0)), int(fs)) + asleep = np.zeros(len(envelope), bool) + for start, label in zip(prep.starts, states, strict=True): + if label == "sleep": + asleep[int(start * fs) : int((start + WINDOW_S) * fs)] = True + median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0) + peaks = np.full((len(episodes), len(use)), np.nan) + for k, (t0, t1) in enumerate(episodes): + a, b = (max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))) + if b - a >= 3: + peaks[k] = np.nanmax(envelope[a:b], axis=0) + for j, name in enumerate(use): + if np.isfinite(median[j]) and median[j] > 0: + out[name] = float(np.nanmedian(peaks[:, j]) / median[j]) + return out diff --git a/models/tea/jobs.py b/models/tea/jobs.py new file mode 100644 index 0000000..01969ee --- /dev/null +++ b/models/tea/jobs.py @@ -0,0 +1,269 @@ +import hashlib +from dataclasses import dataclass +from datetime import date +import mlflow.pyfunc +import pandas as pd +from core.tea import ados2 +from core.tea import association as relation +from models import cluster +from models.jobs import EmptyCohort +from models.tea import association +from models.tea.eeg import analysis, curves, reference +from persistance import eeg, registry, silver + +CURVES = curves.SCENARIOS +ASSOCIATION = "eeg-ados2" +MODELS = [*CURVES, ASSOCIATION] +GOLD = "tea_eeg_metrics" + + +class Baseline(mlflow.pyfunc.PythonModel): + def __init__(self, scenario: str, baseline: dict): + self.scenario, self.baseline = (scenario, baseline) + + def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: + feature = (params or {}).get("feature", "value") + rows = model_input.to_dict("records") + return pd.DataFrame( + [ + curves.score( + self.baseline[feature], r.get("value"), r.get("age_months"), r.get("exposure") + ) + for r in rows + ] + ) + + +def analyze() -> int: + pending = eeg.pending() + done = cluster.run(analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)) + found = dict(zip((r["edf"] for r in pending), done, strict=True)) + eeg.save_analyses(found) + silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"]) + return len(found) + + +@dataclass(frozen=True) +class Jobs: + def routine(self) -> list[str]: + return list(MODELS) + + def scored(self) -> list[str]: + return list(MODELS) + + +JOBS = Jobs() + + +def registered(name: str) -> str: + return f"tea.{name}" + + +def train(name: str, as_of: date | None = None) -> int: + if name == ASSOCIATION: + return _train_association(as_of) + return _train_curve(name, as_of) + + +def _train_curve(name: str, as_of: date | None = None) -> int: + day = as_of or date.today() + measured = eeg.ruled_out(day) + if not measured: + 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() + table = reference.tables(measured)[name] + baseline = curves.train(table, name) + ages = [m["age_months"] for m in measured] + technical = { + "model": name, + "method": "age curves (weighted centiles on log age)", + "cohort": "site: children with TEA ruled out", + "cohort_sha256": digest, + "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} + metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))} + params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)} + reports = {"technical_validation": technical, "interpretability": interpretability} + return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports) + + +def score(name: str) -> int | None: + if name == ASSOCIATION: + return _score_association() + return _score_curve(name) + + +def _score_curve(name: str) -> int | None: + found = registry.champion(registered(name)) + if found is None: + return None + version, model = found + baseline = model.unwrap_python_model().baseline + scenario, label = (CURVES[name], f"{registered(name)}/{version}") + rows = [] + for one in eeg.analysed(): + metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None) + if metric is None: + continue + exposure = ( + (one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None + ) + for part in scenario.parts: + sites = {"": metric["value"]} if part == "value" else metric[part] + prefix = "" if part == "value" else curves.PREFIX[part] + for site, value in sites.items(): + feature = "value" if part == "value" else prefix + site + if feature not in baseline: + continue + s = curves.score(baseline[feature], value, one["age_months"], exposure) + rows.append( + { + "key": f"{one['edf']}|{name}|{part}|{site}", + "edf": one["edf"], + "scenario": name, + "model": label, + "metric": scenario.metric, + "part": part, + "site": site or None, + **s, + } + ) + eeg.save_scores(name, rows) + return version + + +class Association(mlflow.pyfunc.PythonModel): + def __init__(self, fitted: dict): + self.fitted = fitted + + def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame: + return pd.DataFrame(association.score(self.fitted, model_input)) + + +def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]: + day = str(as_of) if as_of else None + rows = [] + for r in eeg.association_inputs(relation.BIOMARKERS): + a = r["ados2"] + evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None + if day and (r["study_date"] > day or (evaluated and evaluated > day)): + continue + css = None + if evaluated and r["birth_date"]: + row = {**a, "evaluation_date": date.fromisoformat(evaluated)} + css, _ = ados2.score(row, date.fromisoformat(r["birth_date"])) + rows.append( + { + "key": r["edf"], + "person": r["person_id"], + "age_months": r["age_months"], + "module": a.get("module"), + "css": css, + **{n: a.get(n) for n, _ in relation.ITEMS.values()}, + **{k: v for k, v in r.items() if k.startswith("z_")}, + } + ) + scored = pd.DataFrame(rows) + if scored.empty: + return (scored, scored) + 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() + fit = scored[with_z].drop_duplicates("person").reset_index(drop=True) + return (fit.drop(columns=["person"]), scored.drop(columns=["person"])) + + +def _train_association(as_of: date | None = None) -> int: + fit, _ = association_cohort(as_of) + if fit.empty: + raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG") + fitted = association.fit(fit) + pairs = association.associations(fitted) + estimated = [p for p in pairs if p["odds_ratio"] is not None] + technical = { + "model": ASSOCIATION, + "method": "Firth logistic (items) / cumulative logit (CSS), adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q", + "cohort": "site: children with an ADOS-2 and a valid EEG", + "as_of": str(as_of or date.today()), + "children": int(fitted["n"]), + "level": fitted["level"], + "pairs": len(pairs), + "estimated": len(estimated), + "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))} + params = {"level": fitted["level"], "as_of": str(as_of or date.today())} + reports = {"technical_validation": technical, "interpretability": interpretability} + return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports) + + +def _score_association() -> int | None: + found = registry.champion(registered(ASSOCIATION)) + if found is None: + return None + version, model = found + fitted = model.unwrap_python_model().fitted + label = f"{registered(ASSOCIATION)}/{version}" + _, scored = association_cohort() + kept = ( + "biomarker", + "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']}", + "metric": relation.BIOMARKERS[p["biomarker"]], + "principal": p["model"], + "sensitivity": p["sens_model"], + } + for p in association.associations(fitted) + if p["odds_ratio"] is not None + ] + observed: dict[str, dict] = {} + if not scored.empty: + keys = scored["key"].tolist() + for n in relation.ITEMS: + items = association.item_scores(scored, n).tolist() + observed[relation.item_code(n)] = dict(zip(keys, items, strict=True)) + observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), strict=True)) + scores = [] + for one in association.score(fitted, scored) if not scored.empty else []: + seen = observed.get(one["outcome_code"], {}).get(one["key"]) + pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}" + 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}", + "observed": shown, + } + ) + eeg.save_association(label, pairs, scores) + return version diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..fd0258f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,41 @@ +[project] +name = "models" +version = "0.0.0" +description = "Dagster assets and jobs; one module per model." +requires-python = ">=3.12" +dependencies = [ + "core", + "persistance", + "dagster", + "dagster-webserver", + "mlflow-skinny", + "openai>=3.59.0", + "splink>=5.0.0", + "duckdb>=2.0.1", + "markitdown[docx,xlsx]>=0.1.9", + "ocrmypdf>=17.14.2", + "pikepdf>=10.0", + "pdfplumber>=0.11.11", + "scikit-learn>=1.9.1", + "scipy>=1.18.1", + "joblib>=1.6.0", + "lifelines>=0.30.0", + "mne>=1.13.2", + "edfio>=0.4.18", + "statsmodels>=0.15.0", + "pgmpy>=1.1.2", +] + +[project.optional-dependencies] +dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs + +[build-system] +requires = ["uv_build>=0.12,<0.13"] +build-backend = "uv_build" + +[tool.uv.build-backend] +module-name = "models" +module-root = "" +[tool.uv.sources] +core = { workspace = true } +persistance = { workspace = true }