163 lines
7.4 KiB
Python
163 lines
7.4 KiB
Python
"""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)
|