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" NOT_MEASURES = ("age_months", EXPOSURE, "rhythm_near_sigma") SCORE_FIELDS = ("z", "outside", "p5", "median", "p95") @dataclass(frozen=True) class Scenario: metric: str parts: tuple[str, ...] counts: bool = False SCENARIOS = { "eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)), "eeg-spindles": Scenario("spindles", ("value", "zones")), "eeg-spindle-topography": Scenario("spindles", ("electrodes",)), "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, electrodes: np.ndarray ) -> dict: n = np.round(values * exposure) exposure = exposure * electrodes 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(list(NOT_MEASURES), errors="ignore"): if name.startswith(("zone_electrodes_", "awake_")): continue values = pd.to_numeric(features[name]).to_numpy(float) if counts: column = f"zone_electrodes_{name.removeprefix('zone_')}" electrodes = ( pd.to_numeric(features[column]).fillna(1).to_numpy(float) if name.startswith("zone_") and column in features else np.ones(len(features)) ) out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes) else: out[name] = _curve(values, ages) return out def _unscored(reason: str | None = None) -> dict: return {**dict.fromkeys(SCORE_FIELDS), "reason": reason} def _number(v) -> float | None: return float(v) if v is not None and math.isfinite(v) else None def centiles(baseline_feature: dict, age_months: float) -> dict: curve = pd.DataFrame(baseline_feature["curve"]).astype(float).dropna() names = [name for name in QUANTILES if name in curve or name in ("p5", "median", "p95")] if curve.empty or not age_months > 0: return dict.fromkeys(names) log_ages = np.log(curve["age_months"].to_numpy()) at = float(np.log(np.array([age_months]))[0]) if not log_ages.min() <= at <= log_ages.max(): return dict.fromkeys(names) return {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in names} def _score_curve(baseline: dict, value: float, age: float) -> dict: q = centiles(baseline, age) if q["median"] is None: return _unscored("age-out-of-range") 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"], "reason": None, } def _score_count( baseline: dict, value: float, age: float, exposure: float | None, electrodes: float ) -> dict: rate, k = baseline["rate"], baseline["k"] lo, hi = baseline["ages"] if not lo <= age < hi: return _unscored("age-out-of-range") if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0: return _unscored("no-exposure") n, mu = float(np.round(value * exposure)), rate * exposure * electrodes 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, "reason": None, } def score( baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None, electrodes: float | None = None, ) -> dict: value, age_months = _number(value), _number(age_months) if value is None: return _unscored() if age_months is None: return _unscored("no-age") if baseline["kind"] == "count_rate": electrodes = _number(electrodes) return _score_count( baseline, value, age_months, _number(exposure), electrodes if electrodes is not None else 1.0, ) 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, analysis.features[name].get(f"zone_electrodes_{key}") if scenario.counts and part == "zones" else None, ) for key, v in getattr(metric, part).items() } return out