192 lines
8.4 KiB
Python
192 lines
8.4 KiB
Python
"""Age baselines: each metric's value (and per electrode and zone) against children of the same
|
|
age in a reference cohort.
|
|
|
|
Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
|
|
study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets
|
|
its own baseline, plain JSON-able data (`train`), scored by `score`:
|
|
|
|
* Centile curves: on 120 ages log-spaced from 1 to 216 months, the p5, p25, median, p75 and p95
|
|
of the reference weighted by a Gaussian on log age (width 0.2), where the effective number of
|
|
studies is at least 30 and the age lies within the reference's. A value scores z = (value -
|
|
median) / ((median - p5 or p95 - median) / 1.645), outside -1 / +1 below p5 / above p95; the
|
|
centiles are interpolated on log age; ages outside the curve get none.
|
|
* Count rate (spikes, which most reference children never have): the reference's rate per
|
|
minute (16 to 37 months) and its dispersion between children (negative binomial by moments,
|
|
Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from
|
|
the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5,
|
|
median and p95 are the rates at those quantiles of the count in those minutes.
|
|
"""
|
|
|
|
import math
|
|
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 # the metric code it scores
|
|
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones"
|
|
stage: str | None = None
|
|
counts: bool = False # a count against the `minutes` feature, not centile curves
|
|
|
|
|
|
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:
|
|
"""Interpolated between the midpoints of each weight's cumulative share."""
|
|
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 # None: Poisson
|
|
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:
|
|
"""Feature -> baseline, for every feature of the scenario's table (`age_months` and the
|
|
count's `minutes` excepted)."""
|
|
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:
|
|
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the
|
|
age or the baseline's coverage is missing."""
|
|
value, age_months = _number(value), _number(age_months)
|
|
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]:
|
|
"""Metric code -> {"value": score, "electrodes": {e: score}, "zones": {z: score}} from the
|
|
trained scenarios in `models` (scenario -> `train`'s output); a scenario without a model
|
|
leaves its parts out."""
|
|
out = {m.code: {} for m in analysis.metrics}
|
|
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
|