24534606f1
Remove 212 Python docstrings and 118 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files. Preserve the existing executable statements and lint pragmas. Use pass for class bodies that previously consisted of only a docstring.
205 lines
7.8 KiB
Python
205 lines
7.8 KiB
Python
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
from models.tea.eeg import signals
|
|
from models.tea.eeg.checks import NEIGHBOURS
|
|
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
|
from models.tea.eeg.sleep import EXCLUDED, window_note
|
|
from models.tea.eeg.spindles import ZONES
|
|
|
|
ELECTRODES = tuple(NEIGHBOURS)
|
|
GATE_S = 2.0
|
|
VERTEX = ("Cz", "Fz", "Pz")
|
|
POSTS = ("O1", "O2")
|
|
OCULAR = ("Fp1", "Fp2", "F7", "F8")
|
|
POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"}
|
|
LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4"))
|
|
ASLEEP = ("N2", "N3", "sleep")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Spikes:
|
|
rate: float
|
|
electrodes: dict[str, float]
|
|
zones: dict[str, float]
|
|
minutes: float
|
|
|
|
|
|
def _mad(v: np.ndarray) -> float:
|
|
v = v[np.isfinite(v)]
|
|
if not len(v):
|
|
return np.nan
|
|
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
|
|
|
|
|
|
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
|
|
n = int(GATE_S * fs)
|
|
top = min(45, fs / 2 * 0.9)
|
|
lines = signals.fixed_lines(x, fs, f_max=top)
|
|
f = np.fft.rfftfreq(n, 1 / fs)
|
|
taper = np.hanning(n)[:, None]
|
|
kept = []
|
|
for a in range(0, len(x) - n + 1, n):
|
|
t0, t1 = a / fs, a / fs + GATE_S
|
|
state, mixed = window_note(t0, t1, intervals)
|
|
segment = x[a : a + n]
|
|
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
|
|
continue
|
|
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
|
power = power.mean(axis=1)
|
|
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
|
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
|
muscle = float(high / max(low, 1e-12))
|
|
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-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]:
|
|
n = len(y)
|
|
if i <= 0 or i >= n - 1:
|
|
return np.nan, np.nan
|
|
w = int(500 * fs / 1000)
|
|
base = float(np.median(y[max(0, i - w) : min(n, i + w)]))
|
|
peak = float(y[i]) - base
|
|
if peak == 0.0:
|
|
return np.nan, np.nan
|
|
sign, half, reach = np.sign(peak), 0.5 * abs(peak), int(150 * fs / 1000)
|
|
a, low = i, max(0, i - reach)
|
|
while a > low and sign * (y[a] - base) >= half:
|
|
a -= 1
|
|
b, high = i, min(n - 1, i + reach)
|
|
while b < high and sign * (y[b] - base) >= half:
|
|
b += 1
|
|
if b <= a:
|
|
return np.nan, np.nan
|
|
rise, fall = half / (max(i - a, 1) / fs), half / (max(b - i, 1) / fs)
|
|
return float(min(rise, fall)), float((b - a) / fs * 1000.0)
|
|
|
|
|
|
def _candidates(x: np.ndarray, fs: float, channel: str) -> list[dict]:
|
|
y = signals.bandpass(x.reshape(-1, 1), fs, 1.0, min(70.0, fs / 2 * 0.9)).ravel()
|
|
if np.isfinite(y).sum() < fs * 2:
|
|
return []
|
|
slope_mad, amplitude_mad = _mad(np.diff(y) * fs), _mad(y)
|
|
if not np.isfinite(slope_mad) or not np.isfinite(amplitude_mad):
|
|
return []
|
|
v = np.abs(y)
|
|
peaks = np.flatnonzero((v[1:-1] > v[:-2]) & (v[1:-1] >= v[2:])) + 1 if len(v) >= 3 else []
|
|
after = int(100 * fs / 1000), int(500 * fs / 1000)
|
|
out = []
|
|
for i in (i for i in peaks if v[i] > 3.0 * amplitude_mad):
|
|
slope, width = _flanks(y, int(i), fs)
|
|
if not (np.isfinite(slope) and np.isfinite(width) and 20.0 <= width <= 200.0):
|
|
continue
|
|
if slope < 6.0 * slope_mad:
|
|
continue
|
|
a, b = int(i) + after[0], min(int(i) + after[1], len(y))
|
|
post = float(-np.sign(y[i]) * np.mean(y[a:b]) / amplitude_mad) if b > a else 0.0
|
|
out.append(
|
|
dict(
|
|
channel=channel,
|
|
t=float(i) / fs,
|
|
sign=int(np.sign(y[i])),
|
|
width=width,
|
|
size=float(abs(y[i]) / amplitude_mad),
|
|
post=post,
|
|
)
|
|
)
|
|
return out
|
|
|
|
|
|
def _field(c: pd.DataFrame) -> np.ndarray:
|
|
times = {(ch, s): np.sort(g.t.to_numpy()) for (ch, s), g in c.groupby(["channel", "sign"])}
|
|
out = np.zeros(len(c), int)
|
|
for k, (ch, t, s) in enumerate(zip(c.channel, c.t, c.sign, strict=True)):
|
|
for other in NEIGHBOURS.get(ch, ()):
|
|
near = times.get((other, s))
|
|
if near is None:
|
|
continue
|
|
j = np.searchsorted(near, t)
|
|
close = near[max(j - 1, 0) : j + 1]
|
|
out[k] += bool(np.any(np.abs(close - t) <= 0.025))
|
|
return out
|
|
|
|
|
|
def _merge(c: pd.DataFrame) -> pd.DataFrame:
|
|
c = c.iloc[np.argsort(c.t.to_numpy(), kind="quicksort")].reset_index(drop=True)
|
|
groups = np.split(np.arange(len(c)), np.flatnonzero(np.diff(c.t.to_numpy()) > 0.18) + 1)
|
|
rows = []
|
|
for g in groups:
|
|
part = c.iloc[g]
|
|
top = c.loc[part["size"].idxmax()]
|
|
asleep = top.state in ASLEEP
|
|
signs = dict(zip(part.channel, part.sign, strict=True))
|
|
frontal_only = top.channel in OCULAR and not (set(part.channel) & POSTERIOR)
|
|
opposite = any(a in signs and b in signs and signs[a] * signs[b] < 0 for a, b in LEFT_RIGHT)
|
|
vertex = asleep and top.channel in VERTEX and float(part.post.max()) > 3.0
|
|
posts = asleep and top.channel in POSTS and top.sign > 0 and top.width > 80.0
|
|
rows.append(
|
|
dict(
|
|
channel=top.channel,
|
|
state=top.state,
|
|
field=int(part.field.max()),
|
|
useful=not (vertex or posts or frontal_only or opposite),
|
|
)
|
|
)
|
|
return pd.DataFrame(rows, columns=["channel", "state", "field", "useful"])
|
|
|
|
|
|
def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
|
channels = [c for c in prep.names if c in ELECTRODES]
|
|
if len(channels) < 4:
|
|
return None
|
|
fs = prep.fs
|
|
x = np.array(prep.data(channels), dtype=np.float64)
|
|
labelled = [
|
|
(s, s + WINDOW_S, label)
|
|
for s, label in zip(prep.starts, states, strict=True)
|
|
if label in ("wake", "drowsy", "sleep")
|
|
]
|
|
|
|
def state_at(t: np.ndarray) -> np.ndarray:
|
|
out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
|
|
for t0, t1, label in labelled:
|
|
hit = open_ & (t0 <= t) & (t < t1)
|
|
out[hit], open_ = label, open_ & ~hit
|
|
return out
|
|
|
|
gate = _gate(x, fs, intervals)
|
|
minutes = {}
|
|
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
|
|
for (t0, t1), state in zip(gate, middles, strict=True):
|
|
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
|
|
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
|
|
counts = dict.fromkeys(channels, 0)
|
|
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
|
|
if candidates and gate:
|
|
c = pd.DataFrame(candidates)
|
|
t = c.t.to_numpy(float)
|
|
inside = np.zeros(len(t), bool)
|
|
for t0, t1 in gate:
|
|
inside |= (t >= t0) & (t < t1)
|
|
c = c[inside]
|
|
if len(c):
|
|
c = c.assign(field=_field(c), state=state_at(c.t.to_numpy()))
|
|
found = _merge(c)
|
|
found = found[found.useful & (found.field > 0) & (found.state == "sleep")]
|
|
for channel, n in found.channel.value_counts().items():
|
|
counts[channel] = int(n)
|
|
rounded = round(sleep_minutes, 2)
|
|
rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan
|
|
electrodes = {
|
|
e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan
|
|
for e in ELECTRODES
|
|
}
|
|
zones = {}
|
|
for zone, members in ZONES.items():
|
|
present = [e for e in members if e in counts]
|
|
total = sum(counts[e] for e in present)
|
|
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
|
|
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
|