Files
tea/src/tea_modulo/processes/spindle_detection/_signal.py
T
AlbertoPMDM f870ee9f14 spindle_detection and spindles, legacy and modern
- legacy: husos.detectar / husos.resumen vendored unchanged, run on the
  'sueno' windows as medidas_director does; the wake rhythm that sets the
  'rhythm near sigma' flag is computed inside the process (no biomarker
  dependency).
- modern: the same detector on MNE (sigma band-pass) and SciPy (Hilbert,
  Welch narrowness, phase stability); summary with the director's
  definitions; one baseline per feature.
- privacy.group_size understands per-feature baseline dicts.

Legacy equals the submodule's cluster route exactly (spindle count and the
six summary measures); modern equals legacy on the synthetic study.
2026-11-18 20:57:24 -06:00

193 lines
7.3 KiB
Python

"""
Signal primitives for spindle detection (private copy), on MNE and SciPy.
Arrays are (samples, channels) in µV with NaN in gaps. Filters run on each
gap-free run separately (runs shorter than the filter's minimum become NaN,
as the director's por_tramos does).
"""
from __future__ import annotations
import numpy as np
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
"""[(start, stop)] of the True runs of a boolean vector."""
v = np.concatenate([[False], np.asarray(valid, bool), [False]])
d = np.diff(v.astype(int))
return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)))
def by_runs(x, fn, minimum: int):
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, fs, lo=None, hi=None, order=4):
"""Butterworth, zero phase (mne.filter.filter_data, IIR), run by run."""
import mne
iir = {"order": order, "ftype": "butter"}
def f(seg):
return mne.filter.filter_data(seg.T, fs, lo, hi, method="iir", iir_params=iir,
phase="zero", verbose="error").T
return by_runs(x, f, minimum=max(3 * (2 * order + 1), int(fs)))
def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True):
"""Spectrum interpolation around f0 and harmonics (port of eeg_io.notch_interpolado).
No library implements this method; MNE's notch filters change the signal differently."""
freqs = [f0]
if harmonics:
k = 2
while k * f0 < fs / 2 * 0.98:
freqs.append(k * f0)
k += 1
def f(seg):
n = seg.shape[0]
fr = np.fft.rfftfreq(n, 1.0 / fs)
F = np.fft.rfft(seg, axis=0)
for c in freqs:
inside = (fr >= c - width) & (fr <= c + width)
left = (fr >= c - 3 * width) & (fr < c - width)
right = (fr > c + width) & (fr <= c + 3 * width)
if not (inside.any() and left.any() and right.any()):
continue
ml, mr = np.abs(F[left]).mean(axis=0), np.abs(F[right]).mean(axis=0)
k_ = np.linspace(0, 1, int(inside.sum()))[:, None]
target = ml[None, :] * (1 - k_) + mr[None, :] * k_
cur = F[inside]
mag = np.abs(cur)
F[inside] = target * np.where(mag > 0, cur / np.maximum(mag, 1e-30), 1.0)
return np.fft.irfft(F, n=n, axis=0)
return by_runs(x, f, minimum=max(int(2 * fs), 256))
def welch(x, fs, seg_s=4.0, overlap=0.5):
"""Welch PSD (Hann) per channel over the gap-free runs (mne psd_array_welch), µV²/Hz."""
from mne.time_frequency import psd_array_welch
x = np.asarray(x, float)
x = x[:, None] if x.ndim == 1 else x
n = int(round(seg_s * fs))
acc, w = None, 0
for a, b in runs(np.isfinite(x).all(axis=1)):
if b - a < n:
continue
P, f = psd_array_welch(x[a:b].T, fs, n_fft=n, n_per_seg=n, n_overlap=int(n * overlap),
window="hann", average="mean", verbose="error")
k = (b - a - n) // int(n * (1 - overlap)) + 1
acc = P * k if acc is None else acc + P * k
w += k
if acc is None:
return None, None
return f, (acc / w).T # (freqs, channels)
def line_db(x, fs, f0=60.0, width=0.6, neighbourhood=(2, 6)):
"""dB of the mains peak over its neighbourhood on the samples valid in all channels
(eeg_io.nivel_de_red)."""
x = np.atleast_2d(np.asarray(x, float).T).T
fin = np.isfinite(x).all(axis=1)
if not fin.any():
return np.full(x.shape[1], np.nan)
seg = x[fin] - x[fin].mean(axis=0)
fr = np.fft.rfftfreq(len(seg), 1.0 / fs)
P = np.abs(np.fft.rfft(seg * np.hanning(len(seg))[:, None], axis=0)) ** 2
lo, hi = neighbourhood
peak = P[(fr >= f0 - width) & (fr <= f0 + width)].mean(axis=0)
nb = P[((fr >= f0 - hi) & (fr <= f0 - lo)) | ((fr >= f0 + lo) & (fr <= f0 + hi))].mean(axis=0)
with np.errstate(divide="ignore", invalid="ignore"):
return 10 * np.log10(np.where(nb > 0, peak / nb, np.nan))
def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5):
"""Peak over the 1/f fit (eeg_io.pico_dominante): (Hz, prominence dB, found)."""
f, P = np.asarray(f, float), np.asarray(P, float)
val = (f >= fit[0]) & (f <= fit[1]) & (P > 0)
bg = val & ~((f >= exclude[0]) & (f <= exclude[1]))
if bg.sum() < 5:
return np.nan, np.nan, False
coef = np.polyfit(np.log10(f[bg]), np.log10(P[bg]), 1)
resid = 10 * (np.log10(P[val]) - np.polyval(coef, np.log10(f[val])))
fv = f[val]
sel = (fv >= band[0]) & (fv <= band[1])
if not sel.any():
return np.nan, np.nan, False
i = int(np.argmax(resid[sel]))
peak, prom = float(fv[sel][i]), float(resid[sel][i])
edge = i == 0 or i == int(sel.sum()) - 1
found = bool(prom >= min_db and not edge)
return (peak if found else np.nan), prom, found
def fixed_lines(x, fs, f_min=1.0, f_max=None, min_db=6.0, max_width=0.5, bg_hz=2.0, seg_s=8.0):
"""Fixed-frequency lines of the recording (lineas.lineas_fijas): [(Hz, dB, width)]."""
from scipy.ndimage import median_filter
x = np.asarray(x, float)
x = x[:, None] if x.ndim == 1 else x
n = int(round(seg_s * fs))
f = np.fft.rfftfreq(n, 1.0 / fs)
win = np.hanning(n)[:, None]
acc, k = None, 0
for a in range(0, len(x) - n + 1, n):
seg = x[a:a + n]
if not np.isfinite(seg).all():
continue
S = np.abs(np.fft.rfft((seg - seg.mean(axis=0)) * win, axis=0)) ** 2
acc = S if acc is None else acc + S
k += 1
if not k:
return []
P = np.median(acc / k, axis=1)
df = float(f[1] - f[0])
lp = 10 * np.log10(np.maximum(P, 1e-30))
kk = max(1, int(round(bg_hz / df)))
prom = lp - median_filter(lp, size=2 * kk + 1, mode="nearest")
f_max = min(f_max or fs / 2, fs / 2 - bg_hz)
cand = []
for i in range(1, len(f) - 1):
if not (f_min <= f[i] <= f_max) or prom[i] < min_db:
continue
if prom[i] < prom[i - 1] or prom[i] < prom[i + 1]:
continue
u = prom[i] - 3.0
a = i
while a > 0 and prom[a - 1] >= u:
a -= 1
b = i
while b < len(f) - 1 and prom[b + 1] >= u:
b += 1
if (b - a + 1) * df <= max_width:
cand.append((round(float(f[i]), 3), round(float(prom[i]), 1), round((b - a + 1) * df, 3)))
cand.sort(key=lambda c: -c[1])
out = []
for c in cand:
if all(abs(c[0] - o[0]) > 0.5 for o in out):
out.append(c)
return sorted(out)
def band_power(f, P, lo, hi, lines=(), margin=1.0):
"""Power of [lo, hi) without ±margin around fixed lines, rescaled (lineas.potencia_banda)."""
f, P = np.asarray(f, float), np.asarray(P, float)
band = (f >= lo) & (f < hi)
clean = band.copy()
for li in lines or ():
clean &= np.abs(f - float(li[0])) > margin
if not clean.any():
return np.full(P.shape[1:], np.nan) if P.ndim > 1 else np.nan
return P[clean].sum(axis=0) * (band.sum() / clean.sum())
def hurst(x):
"""Hurst exponent by detrended fluctuation analysis (antropy)."""
import antropy
v = np.asarray(x, float)
v = v[np.isfinite(v)]
return float(antropy.detrended_fluctuation(v)) if len(v) > 4096 else np.nan