"""An EDF's bytes as signals: the recognised channels in µV, their kind, the notes and dates. `edfio` reads the header first: a file under 256 bytes, an unreadable header, no signals or no recognised channel is not valid (`FileNotValid`). Channels sampled at another rate than the majority, and later duplicates of a name, are dropped rather than resampled. MNE then reads the kept channels' data (`reject_by_annotation="NaN"`: `BAD*` notes are gaps) and the notes. Labels are normalised to 10-20 names (`EEG Fp1-REF` -> `Fp1`, T7/T8/P7/P8 -> T3/T4/T5/T6) or to EKG/LOC/ROC; anything else is not a channel the analysis reads. """ 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"} # What a header's start date holds when the writer didn't know it. UNKNOWN_START = date(1985, 1, 1) class FileNotValid(ValueError): """The bytes are not an EDF the analysis can read.""" def normalize(label: str) -> str | None: """The channel's 10-20 name (or EKG/LOC/ROC), None if not a recognised channel.""" text = str(label).strip() if not text or "ANNOT" in text.upper(): return None stem = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", text, flags=re.I).split("-")[0] key = re.sub(r"[^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: """`eeg` (scalp), `ear`, `eog` or `ecg`, for a normalised name.""" 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 # (samples, channels) µV, NaN in gaps fs: float names: tuple[str, ...] annotations: tuple[tuple[float, float, str], ...] # (onset s, duration s, text) 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]: """The channels of these kinds, in file order.""" return [name for name in self.names if kind(name) in kinds] def _kept(edf: bytes) -> list[tuple[str, str]]: """(label, name) of the channels to read: recognised, at the majority rate, first of each.""" 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: # noqa: BLE001 -- any parse failure means the same 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-6 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: # notes in a Windows code page 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 * 1e6 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: """Months from birth to the recording, to one decimal; None when a date is missing or is the unknown-start placeholder, the birth is after the start or the age is over 18 years.""" 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