Files
models/tests/tea/synth_edf.py
T

127 lines
5.5 KiB
Python

"""Synthetic EDF+ studies for the EEG analysis's tests: every signal is generated, nothing comes from a patient.
`edf_bytes(minutes=4, bad=...)` returns a file the `tea` library reads as a real study:
- background: pink noise mixed over the head (sources weighted by distance), so neighbouring electrodes correlate;
- wake: a posterior rhythm at `rhythm_hz`, strongest on O1 O2 P3 P4, and blinks on Fp1 Fp2;
- sleep: frontal slow waves and 13 Hz spindles on the central and frontal electrodes;
- EKG, EOG and the mains line; states annotated as the hospital writes them ("Paciente despierto", "Dormido");
- `bad`: `flat` channels (no signal) or `loud` ones (eight times the amplitude).
Written as the hospital's converter writes them: plain labels, microvolts, one fixed range, digital ±32767.
"""
import tempfile
from datetime import date, 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
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 signals(*, fs: float, minutes: float, rhythm_hz: float, line_hz: float, bad: dict, seed: int):
rng = np.random.default_rng(seed)
n = int(round(minutes * 60 * fs))
t = np.arange(n) / fs
wake = t < t[-1] / 2
sleep = ~wake
pos = _positions()
names = SCALP + list(EARS)
src = rng.normal(size=(24, 3))
src *= np.mean([np.linalg.norm(p) for p in pos.values()]) / np.linalg.norm(src, axis=1, keepdims=True)
sources = np.stack([_pink(rng, n, fs) for _ in range(len(src))])
data = {}
for ch in names:
w = np.exp(-np.linalg.norm(src - pos[ch], axis=1) / 0.04)
w /= w.sum()
data[ch] = 18.0 * (w @ sources) / np.sqrt((w ** 2).sum()) / np.sqrt(len(src)) * 3 + 4.0 * _pink(rng, n, fs)
alpha = np.sin(2 * np.pi * rhythm_hz * t + rng.uniform(0, 2 * np.pi))
for ch in names:
y = pos[ch][1]
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
slow = np.zeros(n)
k = 0
while k < n:
length = int(fs * rng.uniform(0.8, 1.6))
if k + length < n and sleep[k]:
slow[k:k + length] = -rng.uniform(80, 200) * np.sin(np.pi * np.arange(length) / length)
k += length + int(fs * rng.uniform(0.2, 1.5))
spindles = np.zeros(n)
for c in np.arange(5.0, n / fs, 8.0):
i0 = int(c * fs)
if i0 < n and sleep[i0]:
length = int(fs * rng.uniform(0.6, 1.8))
tt = np.arange(length) / fs
seg = 35.0 * np.exp(-0.5 * ((tt - tt[-1] / 2) / (tt[-1] / 5)) ** 2) * np.sin(2 * np.pi * 13.0 * tt)
spindles[i0:i0 + length] += seg[: max(0, min(length, n - i0))]
for ch in names:
data[ch] += slow if ch in FRONTAL else 0.6 * slow if ch in SPINDLE else 0
if ch in SPINDLE:
data[ch] += spindles
blinks = np.zeros(n)
for c in np.arange(2.0, n / fs, 4.0):
i0, length = int((c + rng.uniform(-0.5, 0.5)) * fs), int(0.3 * fs)
if 0 <= i0 < n - length and wake[i0]:
blinks[i0:i0 + length] += 120 * np.hanning(length)
data["Fp1"] += blinks
data["Fp2"] += blinks
data["LOC"] = 0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
data["ROC"] = -0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
ekg = 20 * rng.normal(size=n)
for c in np.arange(0.3, n / fs, 1 / 1.6):
i0 = int(c * fs)
if i0 + 10 < n:
ekg[i0:i0 + 10] += 900 * np.hanning(10)
data["EKG"] = ekg
for ch in data:
data[ch] = data[ch] + 2.0 * np.sin(2 * np.pi * line_hz * t)
for ch in bad.get("flat", ()):
data[ch] = rng.normal(0, 0.05, n)
for ch in bad.get("loud", ()):
data[ch] = data[ch] * 8
return data, n / fs
def edf_bytes(*, fs: float = 250.0, minutes: float = 4.0, rhythm_hz: float = 7.0, line_hz: float = 60.0,
bad: dict | None = None, seed: int = 0, birthdate: date | None = None,
startdate: date | None = None) -> bytes:
"""`birthdate` and `startdate` go in the header; left out, it says `X` and the 01.01.85 placeholder."""
from edfio import Edf, EdfAnnotation, EdfSignal, Patient, Recording
data, duration = signals(fs=fs, minutes=minutes, rhythm_hz=rhythm_hz, line_hz=line_hz, bad=bad or {}, seed=seed)
labels = SCALP + list(EARS) + list(AUX)
annotations = [EdfAnnotation(0.5, None, "Paciente despierto"), EdfAnnotation(duration / 2 + 0.5, None, "Dormido")]
edf = Edf([EdfSignal(np.clip(data[ch], -FULL_SCALE, FULL_SCALE), fs, label=ch, physical_dimension="uV",
physical_range=(-FULL_SCALE, FULL_SCALE), digital_range=(-32767, 32767)) for ch in labels],
patient=Patient(birthdate=birthdate), recording=Recording(startdate=startdate),
starttime=time(10, 0, 0), data_record_duration=1.0, annotations=annotations)
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "study.edf"
edf.write(path)
return path.read_bytes()