04b314ed8b
Step 3 of the plan. Spatially mixed pink noise, posterior rhythm in wake, frontal slow waves and 13 Hz spindles in sleep, blinks, EKG, mains line, channel faults (flat, frozen, clipped, bridge, loud, bursts) and BAD_ACQ_SKIP gaps, written like ktlx2edf. Read by MNE and by the director's edf_convert.leer_edf.
215 lines
8.0 KiB
Python
215 lines
8.0 KiB
Python
"""
|
|
Synthetic EDF+ studies for tests. No patient data: every signal is generated.
|
|
|
|
from synth_edf import make_edf
|
|
path = make_edf(tmp_path / "s.edf", minutes=6, bad={"flat": ["P3"], "bursts": ["P4"]})
|
|
|
|
Signal model (all in µV), designed to exercise the director's rules:
|
|
- background: spatially mixed pink noise (sources placed on the head, weights
|
|
falling with distance), so neighbouring electrodes correlate as on a real
|
|
scalp and A1/A2 follow T3/T5/F7 and T4/T6/F8;
|
|
- wake segments: a posterior rhythm at `rhythm_hz` (O1 O2 P3 P4 strongest),
|
|
blinks on Fp1 Fp2 / LOC ROC;
|
|
- sleep segments: frontal slow waves (~1 Hz, 80-200 µV) and 13 Hz spindles
|
|
(central and frontal, 0.5-2 s, every ~8 s);
|
|
- EKG: a QRS-like spike train at ~1.6 Hz;
|
|
- mains line at `line_hz`;
|
|
- `bad` channel faults: flat, frozen, clipped (saturated), bridge (pairs),
|
|
bursts (> 4x the montage in many 10 s blocks), loud (4x amplitude);
|
|
- `gaps`: zero-filled spans marked `BAD_ACQ_SKIP` (as ktlx2edf writes them).
|
|
|
|
Written like ktlx2edf: labels without prefixes, unit uV, one fixed range
|
|
±4999.9 µV, digital ±32767.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import time
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
SCALP = ("Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2").split()
|
|
EARS = ("A1", "A2")
|
|
AUX = ("LOC", "ROC", "EKG")
|
|
POSTERIOR = ("O1", "O2", "P3", "P4")
|
|
SPINDLE = ("F3", "F4", "Fz", "C3", "C4", "Cz")
|
|
FRONTAL = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8")
|
|
FULL_SCALE = 4999.9
|
|
|
|
|
|
def _positions():
|
|
import mne
|
|
# colin27_1020 replaces the deprecated standard_1020 (MNE 1.13) and has the
|
|
# old names (T3, T5, A1...) too
|
|
pos = mne.channels.make_standard_montage("colin27_1020").get_positions()["ch_pos"]
|
|
return {ch: np.asarray(pos[ch], float) for ch in SCALP + list(EARS)}
|
|
|
|
|
|
def _pink(rng, n, fs):
|
|
f = np.fft.rfftfreq(n, 1 / fs)
|
|
spec = rng.normal(size=f.size) + 1j * rng.normal(size=f.size)
|
|
spec[1:] /= np.sqrt(f[1:])
|
|
spec[0] = 0
|
|
x = np.fft.irfft(spec, n)
|
|
return x / x.std()
|
|
|
|
|
|
def _segments(states, n, fs):
|
|
lab = np.full(n, "vigilia", dtype=object)
|
|
for st, a, b in states:
|
|
lab[int(a * fs):int(b * fs)] = st
|
|
return lab
|
|
|
|
|
|
def make_signals(*, fs=250.0, minutes=6.0, states=None, rhythm_hz=7.0, line_hz=60.0,
|
|
line_uv=2.0, bad=None, seed=0):
|
|
"""Return (data µV dict label -> array, states list)."""
|
|
rng = np.random.default_rng(seed)
|
|
n = int(round(minutes * 60 * fs))
|
|
t = np.arange(n) / fs
|
|
dur = n / fs
|
|
if states is None:
|
|
states = [("vigilia", 0.0, dur / 2), ("sueno", dur / 2, dur)]
|
|
lab = _segments(states, n, fs)
|
|
wake = lab == "vigilia"
|
|
sleep = lab == "sueno"
|
|
|
|
pos = _positions()
|
|
names = SCALP + list(EARS)
|
|
n_src = 24
|
|
src_pos = rng.normal(size=(n_src, 3))
|
|
src_pos /= np.linalg.norm(src_pos, axis=1, keepdims=True)
|
|
src_pos *= np.mean([np.linalg.norm(p) for p in pos.values()])
|
|
sources = np.stack([_pink(rng, n, fs) for _ in range(n_src)])
|
|
data = {}
|
|
for ch in names:
|
|
d = np.linalg.norm(src_pos - pos[ch], axis=1)
|
|
w = np.exp(-d / 0.04)
|
|
w /= w.sum()
|
|
x = 18.0 * (w @ sources) / np.sqrt((w ** 2).sum()) / np.sqrt(n_src) * 3
|
|
x += 4.0 * _pink(rng, n, fs) # local, uncorrelated part
|
|
data[ch] = x
|
|
|
|
# posterior rhythm in wake (amplitude falls toward the front)
|
|
phase = rng.uniform(0, 2 * np.pi)
|
|
alpha = np.sin(2 * np.pi * rhythm_hz * t + phase)
|
|
for ch in names:
|
|
y = pos[ch][1] # anterior (+) / posterior (-)
|
|
amp = 30.0 if ch in POSTERIOR else 12.0 * np.exp(-(y + 0.05) * 25) if y < 0.05 else 3.0
|
|
data[ch] += amp * alpha * wake
|
|
|
|
# sleep: frontal slow waves and spindles
|
|
sw = np.zeros(n)
|
|
k = 0
|
|
while k < n:
|
|
L = int(fs * rng.uniform(0.8, 1.6))
|
|
if k + L < n and sleep[k]:
|
|
sw[k:k + L] = -rng.uniform(80, 200) * np.sin(np.pi * np.arange(L) / L)
|
|
k += L + int(fs * rng.uniform(0.2, 1.5))
|
|
spin = np.zeros(n)
|
|
for c in np.arange(5.0, dur, 8.0):
|
|
i0 = int(c * fs)
|
|
if i0 < n and sleep[i0]:
|
|
L = int(fs * rng.uniform(0.6, 1.8))
|
|
tt = np.arange(L) / fs
|
|
env = np.exp(-0.5 * ((tt - tt[-1] / 2) / (tt[-1] / 5)) ** 2)
|
|
seg = 35.0 * env * np.sin(2 * np.pi * 13.0 * tt)
|
|
spin[i0:i0 + L] += seg[: max(0, min(L, n - i0))]
|
|
for ch in names:
|
|
if ch in FRONTAL:
|
|
data[ch] += sw
|
|
elif ch in SPINDLE:
|
|
data[ch] += 0.6 * sw
|
|
if ch in SPINDLE:
|
|
data[ch] += spin
|
|
|
|
# blinks (wake) and EOG
|
|
blinks = np.zeros(n)
|
|
for c in np.arange(2.0, dur, 4.0):
|
|
i0 = int((c + rng.uniform(-0.5, 0.5)) * fs)
|
|
L = int(0.3 * fs)
|
|
if 0 <= i0 < n - L and wake[i0]:
|
|
blinks[i0:i0 + L] += 120 * np.hanning(L)
|
|
data["Fp1"] += blinks
|
|
data["Fp2"] += blinks
|
|
data["LOC"] = 0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * sw
|
|
data["ROC"] = -0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * sw
|
|
|
|
# EKG
|
|
ekg = 20 * rng.normal(size=n)
|
|
for c in np.arange(0.3, dur, 1 / 1.6):
|
|
i0 = int(c * fs)
|
|
if i0 + 10 < n:
|
|
ekg[i0:i0 + 10] += 900 * np.hanning(10)
|
|
data["EKG"] = ekg
|
|
|
|
# mains line
|
|
for ch in data:
|
|
data[ch] = data[ch] + line_uv * np.sin(2 * np.pi * line_hz * t)
|
|
|
|
_apply_faults(data, bad or {}, rng, fs)
|
|
return data, states
|
|
|
|
|
|
def _apply_faults(data, bad, rng, fs):
|
|
n = len(next(iter(data.values())))
|
|
for ch in bad.get("flat", []):
|
|
data[ch] = np.zeros(n) + rng.normal(0, 0.05, n)
|
|
for ch in bad.get("frozen", []):
|
|
x = data[ch].copy()
|
|
hold = np.repeat(x[::50], 50)[:n] # stuck value for 50 samples at a time
|
|
data[ch] = hold
|
|
for ch in bad.get("clipped", []):
|
|
data[ch] = np.clip(data[ch] * 60, -FULL_SCALE, FULL_SCALE)
|
|
for a, b in bad.get("bridge", []):
|
|
data[b] = data[a] + rng.normal(0, 0.3, n)
|
|
for ch in bad.get("loud", []):
|
|
data[ch] = data[ch] * 8
|
|
for ch in bad.get("bursts", []):
|
|
blk = int(10 * fs)
|
|
for b0 in range(0, n - blk, blk):
|
|
if rng.random() < 0.3: # 30 % of the 10 s blocks
|
|
i0 = b0 + int(rng.uniform(0, blk - fs * 3))
|
|
L = int(fs * 2.5)
|
|
data[ch][i0:i0 + L] += rng.choice([-1, 1]) * 600 * np.hanning(L) * \
|
|
np.sign(np.sin(2 * np.pi * 3 * np.arange(L) / fs))
|
|
|
|
|
|
def make_edf(path, *, fs=250.0, minutes=6.0, states=None, rhythm_hz=7.0, line_hz=60.0,
|
|
line_uv=2.0, bad=None, gaps=(), annotations=None, seed=0, channels=None,
|
|
label_prefix="") -> Path:
|
|
"""Write a synthetic EDF+ and return its path."""
|
|
from edfio import Edf, EdfAnnotation, EdfSignal
|
|
|
|
data, states = make_signals(fs=fs, minutes=minutes, states=states, rhythm_hz=rhythm_hz,
|
|
line_hz=line_hz, line_uv=line_uv, bad=bad, seed=seed)
|
|
labels = list(channels) if channels else SCALP + list(EARS) + list(AUX)
|
|
n = len(data[labels[0]])
|
|
ann = []
|
|
for a, d in gaps:
|
|
i0, i1 = int(a * fs), int((a + d) * fs)
|
|
for ch in labels:
|
|
data[ch][i0:i1] = 0.0
|
|
ann.append(EdfAnnotation(float(a), float(d), "BAD_ACQ_SKIP"))
|
|
if annotations is None:
|
|
annotations = []
|
|
for st, a, b in states:
|
|
txt = {"vigilia": "Paciente despierto", "sueno": "Dormido"}.get(st)
|
|
if txt:
|
|
annotations.append((float(a) + 0.5, None, txt))
|
|
for a, d, txt in annotations:
|
|
ann.append(EdfAnnotation(float(a), d, txt))
|
|
|
|
signals = [EdfSignal(np.clip(data[ch], -FULL_SCALE, FULL_SCALE), fs,
|
|
label=label_prefix + ch, physical_dimension="uV",
|
|
physical_range=(-FULL_SCALE, FULL_SCALE),
|
|
digital_range=(-32767, 32767))
|
|
for ch in labels]
|
|
rec_s = 1.0 if n % int(fs) == 0 else n / fs
|
|
edf = Edf(signals, starttime=time(10, 0, 0), data_record_duration=rec_s,
|
|
annotations=ann)
|
|
path = Path(path)
|
|
edf.write(path)
|
|
return path
|