Files
models/models/tea/eeg/curves.py
T
Roberto Treviño 41508efeb6 ISSSTELEON models
2026-11-29 18:11:48 -06:00

164 lines
6.4 KiB
Python

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