EDF reader node in the ingestion DSL: run_edf keeps each row and adds the header facts or the file's error; read.header parses the fixed EDF header without edfio

This commit is contained in:
2026-11-28 10:30:48 -06:00
parent cc95054a96
commit dce0e0c690
6 changed files with 363 additions and 5 deletions
+82 -4
View File
@@ -13,6 +13,7 @@ import io
import re
from dataclasses import dataclass
from datetime import date, datetime
from struct import Struct
import edfio
import mne
@@ -75,14 +76,91 @@ class Recording:
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:
@dataclass(frozen=True)
class Header:
patient_code: str | None
sex: str | None
birthdate: date | None
start_date: date | None
record_code: str | None
duration_s: float | None
channels: int
_FIXED = Struct("8s80s80s8s8s8s44s8s8s4s")
def _check_length(data: bytes) -> None:
if len(data) < _FIXED.size:
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
def _fixed_header(data: bytes) -> dict:
_check_length(data)
try:
signals = edfio.read_edf(edf, lazy_load_data=True).signals
(
version,
patient,
recording,
startdate,
starttime,
size,
reserved,
records,
duration,
signals,
) = (field.decode("ascii").strip() for field in _FIXED.unpack_from(data))
size, records, duration, signals = int(size), int(records), float(duration), int(signals)
if version != "0" or size != 256 * (1 + signals) or signals < 0:
raise ValueError
except ValueError as exc:
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
return dict(
version=version, patient=patient, recording=recording, startdate=startdate,
starttime=starttime, size=size, reserved=reserved, records=records,
duration=duration, signals=signals,
) # fmt: skip
def _date(value: str, fmt: str) -> date | None:
try:
return datetime.strptime(value, fmt).date()
except ValueError:
return None
def header(edf: bytes) -> Header:
"""Read the declared facts from the fixed header without opening any signals."""
fixed = _fixed_header(edf)
patient = fixed["patient"].split(maxsplit=3) + [""] * 3
recording = fixed["recording"].split(maxsplit=3) + [""] * 3
start = _date(recording[1], "%d-%b-%Y") if recording[0] == "Startdate" else None
return Header(
patient_code=None if patient[0] in ("", "X") else patient[0],
sex=patient[1] if patient[1] in ("F", "M") else None,
birthdate=_date(patient[2], "%d-%b-%Y"),
start_date=None if start == UNKNOWN_START else start,
record_code=None if recording[2] in ("", "X") else recording[2],
duration_s=None if fixed["records"] == -1 else fixed["records"] * fixed["duration"],
channels=fixed["signals"],
)
def _open(edf: bytes) -> edfio.Edf:
_check_length(edf)
try:
opened = edfio.read_edf(edf, lazy_load_data=True)
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
declared_records = int(edf[236:244])
if declared_records > opened.num_data_records:
raise FileNotValid("the EDF signal data is truncated")
return opened
def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
signals = _open(edf).signals
if not signals:
raise FileNotValid("the EDF declares zero signals")
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]