TEA EEG analysis and age curves, TEA jobs; CaMa recurrence on METABRIC and SCAN-B; reference-data models and routine runs
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
"""The TEA EEG analysis: verdict, metrics and age baselines of a child's EEG (`analysis.py`,
|
||||
`curves.py`)."""
|
||||
@@ -0,0 +1,132 @@
|
||||
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
|
||||
|
||||
analysis = analyze(edf_bytes, birth_date)
|
||||
|
||||
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
|
||||
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are
|
||||
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
|
||||
|
||||
The age is the EDF header's (recording start minus birth date) when it has both dates, else the
|
||||
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
|
||||
`error` set, keeping the verdict and checks when validation finished before it. Missing values
|
||||
are None.
|
||||
"""
|
||||
|
||||
import math
|
||||
import 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) # None where not measured
|
||||
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] # code, electrode, value, text, unit, low, high, decisive, abnormal
|
||||
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes,
|
||||
# anteroposterior_gradient
|
||||
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
|
||||
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(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", 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:
|
||||
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
|
||||
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`)."""
|
||||
out = dict(
|
||||
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: # noqa: BLE001 -- one unreadable EDF must not stop a batch
|
||||
return Analysis(**out | dict(error=_error(exc)))
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features
|
||||
each age baseline scores (by scenario, `curves.SCENARIOS`).
|
||||
|
||||
Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior
|
||||
electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more.
|
||||
|
||||
Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-4 Hz) power of
|
||||
each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the
|
||||
electrode's front-back position (6 electrodes at least).
|
||||
|
||||
Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode.
|
||||
Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
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.50, "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.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
|
||||
} # fmt: skip
|
||||
CODES = (
|
||||
"posterior_rhythm",
|
||||
"spindles_n2",
|
||||
"spindles_n3",
|
||||
"paroxysmal_spikes",
|
||||
"anteroposterior_gradient",
|
||||
)
|
||||
|
||||
|
||||
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None:
|
||||
"""The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15."""
|
||||
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
|
||||
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: code -> (value, electrodes, zones), features by scenario)."""
|
||||
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
|
||||
@@ -0,0 +1,349 @@
|
||||
"""Whether an EEG can be analysed: channel rules, 4 s window QC, triage level and gates.
|
||||
|
||||
Channel rules flag a channel bad (each reason is one check): dead (< 10 finite samples or SD
|
||||
< 0.5 µV, which skips the rest), frozen, saturated, infinite values, gaps of its own; after the
|
||||
mains notch and a 0.5-45 Hz band-pass, an amplitude over 4 x the scalp median, intermittent
|
||||
contact (10 s blocks far below the montage) or bursts (far above it); on 1-40 Hz, a bridge with
|
||||
a contiguous electrode or an ear that does not follow its neighbours; EOG/ECG out of range.
|
||||
|
||||
Window QC splits the kept scalp channels (notch, 0.5-45 Hz) into back-to-back 4 s windows: a
|
||||
gap, or a window over 800 µV peak to peak, with muscle (30-45 / 4-13 Hz power, fixed lines out,
|
||||
over 0.6) or common mode over 0.8, is not clean. Triage sets the level from coverage, bad scalp
|
||||
electrodes and clean minutes; the gates make the EEG not valid when the level is
|
||||
`not_analyzable`, fewer than 60 % of windows are clean or fewer than 12 scalp electrodes are
|
||||
usable.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
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"),
|
||||
} # fmt: skip
|
||||
EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")}
|
||||
MIN_CLEAN_PCT = 60.0
|
||||
MIN_COVERAGE = 0.90
|
||||
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]] # channel -> reasons, every kind of channel
|
||||
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]]:
|
||||
"""Rules on a channel's raw samples: (code, reason)."""
|
||||
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-9) > 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]:
|
||||
"""Per channel, the fraction of 10 s blocks silent against the montage and bursting above it
|
||||
(NaN with fewer than 6 blocks)."""
|
||||
size = int(10 * fs)
|
||||
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]:
|
||||
"""Scalp channels correlating over 0.99 with a contiguous electrode and with no far one."""
|
||||
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]]:
|
||||
"""Per ear: its best |r| with its neighbours, and the neighbours' median |r| between them."""
|
||||
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]]]:
|
||||
"""Channel -> [(code, reason)] of every channel some rule flags."""
|
||||
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.10:
|
||||
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 "
|
||||
f"({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, "
|
||||
f"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]]:
|
||||
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
|
||||
verdict `gap`, `suspect` or `clean`."""
|
||||
n = int(4 * fs)
|
||||
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):
|
||||
"""(level, bad scalp electrodes by the triage rule)."""
|
||||
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-9)) 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)
|
||||
@@ -0,0 +1,191 @@
|
||||
"""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
|
||||
@@ -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]
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
|
||||
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
|
||||
|
||||
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp
|
||||
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given:
|
||||
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so.
|
||||
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp
|
||||
channels at 0.5-45 Hz.
|
||||
"""
|
||||
|
||||
import warnings
|
||||
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 # (samples, scalp channels) µV, average reference
|
||||
names: tuple[str, ...] # the kept scalp channels
|
||||
fs: float
|
||||
starts: np.ndarray # window grid starts, s
|
||||
unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean
|
||||
annotations: tuple[tuple[float, float, str], ...]
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return len(self.x) / self.fs
|
||||
|
||||
def columns(self, wanted) -> list[str]:
|
||||
"""The kept channels among `wanted`, in `wanted`'s order."""
|
||||
return [name for name in wanted if name in self.names]
|
||||
|
||||
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) # the mean of a gap's row
|
||||
referenced = y - np.nanmean(y, axis=1, keepdims=True)
|
||||
# Kept as the reference analysis read it from MNE: through volts and back, column-major in
|
||||
# memory (the layout decides the order of float sums along time).
|
||||
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
|
||||
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
|
||||
qc[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-9, STEP_S)
|
||||
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""An EDF's bytes as signals: the recognised channels in µV, their kind, the notes and dates.
|
||||
|
||||
`edfio` reads the header first: a file under 256 bytes, an unreadable header, no signals or no
|
||||
recognised channel is not valid (`FileNotValid`). Channels sampled at another rate than the
|
||||
majority, and later duplicates of a name, are dropped rather than resampled. MNE then reads the
|
||||
kept channels' data (`reject_by_annotation="NaN"`: `BAD*` notes are gaps) and the notes.
|
||||
|
||||
Labels are normalised to 10-20 names (`EEG Fp1-REF` -> `Fp1`, T7/T8/P7/P8 -> T3/T4/T5/T6) or
|
||||
to EKG/LOC/ROC; anything else is not a channel the analysis reads.
|
||||
"""
|
||||
|
||||
import io
|
||||
import 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"}
|
||||
# What a header's start date holds when the writer didn't know it.
|
||||
UNKNOWN_START = date(1985, 1, 1)
|
||||
|
||||
|
||||
class FileNotValid(ValueError):
|
||||
"""The bytes are not an EDF the analysis can read."""
|
||||
|
||||
|
||||
def normalize(label: str) -> str | None:
|
||||
"""The channel's 10-20 name (or EKG/LOC/ROC), None if not a recognised channel."""
|
||||
text = str(label).strip()
|
||||
if not text or "ANNOT" in text.upper():
|
||||
return None
|
||||
stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0]
|
||||
key = re.sub(r"[^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:
|
||||
"""`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name."""
|
||||
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 # (samples, channels) µV, NaN in gaps
|
||||
fs: float
|
||||
names: tuple[str, ...]
|
||||
annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text)
|
||||
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]:
|
||||
"""The channels of these kinds, in file order."""
|
||||
return [name for name in self.names if kind(name) in kinds]
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
if len(edf) < 256:
|
||||
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: # noqa: BLE001 -- any parse failure means the same
|
||||
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-6 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: # notes in a Windows code page
|
||||
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 * 1e6
|
||||
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:
|
||||
"""Months from birth to the recording, to one decimal; None when a date is missing or is the
|
||||
unknown-start placeholder, the birth is after the start or the age is over 18 years."""
|
||||
if start is None or birthday is None or start == UNKNOWN_START or birthday > start:
|
||||
return None
|
||||
months = round((start - birthday).days / days_per_month, 1)
|
||||
return months if months <= 216 else None
|
||||
@@ -0,0 +1,62 @@
|
||||
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
|
||||
children of 16 to 36 months, recorded on 50 Hz mains.
|
||||
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
||||
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
||||
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
||||
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
|
||||
from the valid studies.
|
||||
"""
|
||||
|
||||
import multiprocessing
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
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]]:
|
||||
"""(key, path, age in months) of each EDF with an age within `ages`."""
|
||||
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(study: tuple[str, Path, float]) -> dict:
|
||||
key, path, age = study
|
||||
a = analyze(Path(path).read_bytes(), 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, workers: int = 4) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order."""
|
||||
context = multiprocessing.get_context("spawn")
|
||||
with ProcessPoolExecutor(workers, mp_context=context) as pool:
|
||||
return list(pool.map(_one, studies))
|
||||
|
||||
|
||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
"""Scenario -> its training table: the valid studies' features and `age_months`."""
|
||||
usable = [s for s in measured if s["valid"] and s["error"] is None]
|
||||
return {
|
||||
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
|
||||
for name in SCENARIOS
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Signal primitives every step shares.
|
||||
|
||||
Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A
|
||||
filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum
|
||||
stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge
|
||||
padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains
|
||||
notch, the fixed-line search and the dominant peak are small rules of their own: no library
|
||||
computes the same thing (MNE's notch filters change the signal by microvolts).
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
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]]:
|
||||
"""`(start, stop)` of each run of True."""
|
||||
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:
|
||||
"""`fn` on each gap-free run of rows at least `minimum` long; NaN elsewhere."""
|
||||
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:
|
||||
"""Zero-phase Butterworth band-pass of each gap-free run."""
|
||||
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:
|
||||
"""Mains removal by spectrum interpolation: around `f0` and each harmonic below 98 % of
|
||||
Nyquist, the FFT magnitudes within `width` Hz are replaced by a line from the mean magnitude
|
||||
of the `2 width` Hz on the left to that on the right, keeping the phase."""
|
||||
centres = [f0] + [k * f0 for k in range(2, 1000) if k * f0 < fs / 2 * 0.98]
|
||||
|
||||
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:
|
||||
"""Per channel, dB of the mains peak (`f0` ± 0.6 Hz) over its neighbourhood (2-6 Hz away),
|
||||
from one Hann-tapered FFT of the rows finite in every channel."""
|
||||
finite = np.isfinite(x).all(axis=1)
|
||||
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]:
|
||||
"""One Hann periodogram (density, mean removed) of each segment along the last axis:
|
||||
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
|
||||
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]:
|
||||
"""Frequencies of narrow fixed lines of a recording (artefacts, not EEG): the power of 8 s
|
||||
Hann segments, averaged and its median taken over channels, in dB above a 4 Hz running
|
||||
median; local maxima in [1, f_max] Hz at least 6 dB up and at most 0.5 Hz wide at -3 dB,
|
||||
the most prominent kept where two lie within 0.5 Hz."""
|
||||
n = int(round(8 * fs))
|
||||
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):
|
||||
"""Power summed over [lo, hi) Hz (`include_hi`: [lo, hi]) along the first axis of `power`,
|
||||
without the bins within 1 Hz of a fixed line, rescaled to the band's full width."""
|
||||
band = (f >= lo) & ((f <= hi) if include_hi else (f < hi))
|
||||
clean = band.copy()
|
||||
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]:
|
||||
"""The largest 3-14 Hz peak over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz:
|
||||
(Hz, prominence in dB, found). Found when at least 1.5 dB up and not at the band's edge."""
|
||||
usable = (f >= 1.5) & (f <= 45) & (power > 0)
|
||||
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)
|
||||
@@ -0,0 +1,223 @@
|
||||
"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3).
|
||||
|
||||
Notes: a note's state is the first whose words its text contains (lower case, accents removed,
|
||||
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s;
|
||||
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement,
|
||||
disconnection, photic stimulation and hyperventilation are masked.
|
||||
|
||||
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
|
||||
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
|
||||
muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is standardised by
|
||||
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
|
||||
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
|
||||
posterior electrode leaves that feature out of the mean.
|
||||
|
||||
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
|
||||
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
|
||||
20 % of the 30 s centred on it, else N2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import 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"),
|
||||
} # fmt: skip
|
||||
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)} # fmt: skip
|
||||
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("ñ", "\0").replace("Ñ", "\1")
|
||||
plain = "".join(
|
||||
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
|
||||
)
|
||||
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").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]]:
|
||||
"""(onset s, duration s, state) covering the record: the notes' states and `unmarked`."""
|
||||
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]:
|
||||
"""The state covering most of [t0, t1) and whether it covers less than 80 % of it."""
|
||||
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:
|
||||
"""Samples of the QC spans and of the masked notes."""
|
||||
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]]:
|
||||
"""Start samples of the usable windows and their features."""
|
||||
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-6, 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:
|
||||
"""The weighted mean of the standardised features, clipped to ±6."""
|
||||
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-9))
|
||||
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:
|
||||
"""`wake`, `drowsy`, `sleep` or `` (not scored) per grid window."""
|
||||
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]]:
|
||||
"""(onset s, duration s) of the slow waves of one channel."""
|
||||
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
|
||||
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:
|
||||
"""`N3` or `N2` per sleep window (`` elsewhere)."""
|
||||
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
|
||||
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-9), 1.0) if len(covered) else 0.0
|
||||
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
|
||||
return out
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Paroxysmal spikes in sleep: candidates per channel, merged into discharges, counted against
|
||||
the clean minutes of sleep.
|
||||
|
||||
Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an
|
||||
excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz
|
||||
power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is
|
||||
one. Each kept window adds its 2 s to the state of its midpoint.
|
||||
|
||||
Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD,
|
||||
20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both
|
||||
flanks at least 6 x the MAD of the channel's slope; inside a kept window. Its field is the
|
||||
number of 10-20 neighbours with a same-sign candidate within 25 ms.
|
||||
|
||||
Discharge: candidates closer than 180 ms are one; the largest (in MADs) gives its channel, state
|
||||
and width. A useful discharge has field and is not a vertex wave (asleep, max on Cz/Fz/Pz, a
|
||||
slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on
|
||||
Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair).
|
||||
|
||||
Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode
|
||||
(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
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 # useful discharges per minute of clean sleep
|
||||
electrodes: dict[str, float]
|
||||
zones: dict[str, float]
|
||||
minutes: float # clean sleep minutes, the rate's exposure
|
||||
|
||||
|
||||
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]]:
|
||||
"""(start, end) s of the 2 s windows the detector reads."""
|
||||
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-9))
|
||||
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]:
|
||||
"""(slower flank's slope µV/s, width ms) of the transient peaking at `i`, at half height."""
|
||||
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:
|
||||
"""Per candidate, its 10-20 neighbours with a same-sign candidate within 25 ms."""
|
||||
times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])}
|
||||
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:
|
||||
"""One row per discharge: candidates closer than 180 ms."""
|
||||
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:
|
||||
"""None with fewer than 4 10-20 channels."""
|
||||
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:
|
||||
"""The state of the first labelled window holding each time."""
|
||||
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))
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the
|
||||
sigma envelope per electrode.
|
||||
|
||||
Detection runs on the frontal, central and parietal electrodes over the windows of the stage
|
||||
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
|
||||
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
|
||||
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
|
||||
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
|
||||
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
|
||||
envelope peaks 3 x over the median.
|
||||
|
||||
Density: spindles per minute and searched channel (NaN when none were found); per zone, the
|
||||
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
|
||||
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
|
||||
the episode ± 0.25 s, over the median envelope in sleep.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
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]] # (onset s, duration s, channel)
|
||||
minutes: float
|
||||
channels: list[str] # the channels searched (none when under a minute of the stage)
|
||||
|
||||
|
||||
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:
|
||||
"""Sigma over its flanks, and an instantaneous frequency in band."""
|
||||
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:
|
||||
"""The spindles in the grid windows staged `stage`."""
|
||||
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-9
|
||||
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]]:
|
||||
"""Spindles per minute and channel (rounded to 3), and per zone; NaN when none."""
|
||||
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]:
|
||||
"""Per spindle electrode, the envelope's median peak over episodes against its sleep median
|
||||
(NaN for an absent electrode, or without spindles)."""
|
||||
out = dict.fromkeys(CHANNELS, np.nan)
|
||||
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
|
||||
Reference in New Issue
Block a user