117 lines
4.0 KiB
Python
117 lines
4.0 KiB
Python
import io
|
|
import re
|
|
from dataclasses import dataclass
|
|
from datetime import date, datetime
|
|
import edfio
|
|
import mne
|
|
import numpy as np
|
|
|
|
STANDARD = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz"
|
|
CANONICAL = {name.upper(): name for name in STANDARD.split()}
|
|
RENAMED = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"}
|
|
AUXILIARY = (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC"))
|
|
EARS = {"A1", "A2"}
|
|
EOG = {"LOC", "ROC"}
|
|
UNKNOWN_START = date(1985, 1, 1)
|
|
|
|
|
|
class FileNotValid(ValueError):
|
|
pass
|
|
|
|
|
|
def normalize(label: str) -> str | None:
|
|
text = str(label).strip()
|
|
if not text or "ANNOT" in text.upper():
|
|
return None
|
|
stem = re.sub("^\\s*(EEG|ECG|EKG|EOG|EMG|POL)\\s+", "", text, flags=re.I).split("-")[0]
|
|
key = re.sub("[^A-Z0-9]", "", stem.strip().upper())
|
|
if key in CANONICAL:
|
|
name = CANONICAL[key]
|
|
return RENAMED.get(name, name)
|
|
return next((name for part, name in AUXILIARY if part in text.upper()), None)
|
|
|
|
|
|
def kind(name: str) -> str:
|
|
if name in EARS:
|
|
return "ear"
|
|
if name in EOG:
|
|
return "eog"
|
|
return "ecg" if name == "EKG" else "eeg"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Recording:
|
|
x: np.ndarray
|
|
fs: float
|
|
names: tuple[str, ...]
|
|
annotations: tuple[tuple[float, float, str], ...]
|
|
start: date | None
|
|
birthday: date | None
|
|
|
|
@property
|
|
def duration_s(self) -> float:
|
|
return len(self.x) / self.fs
|
|
|
|
def kinds(self) -> dict[str, str]:
|
|
return {name: kind(name) for name in self.names}
|
|
|
|
def of(self, *kinds: str) -> list[str]:
|
|
return [name for name in self.names if kind(name) in kinds]
|
|
|
|
|
|
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
|
if len(edf) < 256:
|
|
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
|
try:
|
|
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
|
except Exception as exc:
|
|
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
|
if not signals:
|
|
raise FileNotValid("the EDF declares zero signals")
|
|
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
|
|
named = [(label, name, rate) for label, name, rate in named if name is not None]
|
|
if not named:
|
|
raise FileNotValid("no recognised channel")
|
|
rates = [rate for _, _, rate in named]
|
|
fs = max(set(rates), key=rates.count)
|
|
kept, seen = ([], set())
|
|
for label, name, rate in named:
|
|
if abs(rate - fs) <= 1e-06 and name not in seen:
|
|
seen.add(name)
|
|
kept.append((label, name))
|
|
return kept
|
|
|
|
|
|
def read(edf: bytes) -> Recording:
|
|
kept = _kept(edf)
|
|
options = dict(include=[label for label, _ in kept], preload=True, verbose="error")
|
|
try:
|
|
raw = mne.io.read_raw_edf(io.BytesIO(edf), **options)
|
|
except Exception as exc:
|
|
if "latin1" not in str(exc):
|
|
raise
|
|
raw = mne.io.read_raw_edf(io.BytesIO(edf), encoding="latin1", **options)
|
|
raw.rename_channels({lab: name for lab, name in kept if lab in raw.ch_names and lab != name})
|
|
names = [name for name in raw.ch_names if name in {n for _, n in kept}]
|
|
x = raw.get_data(picks=names, reject_by_annotation="NaN", verbose="error").T * 1000000.0
|
|
start = raw.info.get("meas_date")
|
|
born = (raw.info.get("subject_info") or {}).get("birthday")
|
|
notes = tuple(
|
|
((float(a["onset"]), float(a["duration"]), a["description"]) for a in raw.annotations)
|
|
)
|
|
return Recording(
|
|
x=x,
|
|
fs=float(raw.info["sfreq"]),
|
|
names=tuple(names),
|
|
annotations=notes,
|
|
start=start.date() if isinstance(start, datetime) else start,
|
|
birthday=date(*born) if isinstance(born, tuple) else born,
|
|
)
|
|
|
|
|
|
def age_months(start: date | None, birthday: date | None, days_per_month: float) -> float | None:
|
|
if start is None or birthday is None or start == UNKNOWN_START or (birthday > start):
|
|
return None
|
|
months = round((start - birthday).days / days_per_month, 1)
|
|
return months if months <= 216 else None
|