Files
tea/src/tea_modulo/export/edf_annotations.py
T
AlbertoPMDM 2b4bea0c7f export: optional KTLX -> EDF+ exporter vendored from eeg@92bc2a0
Step 2 of the plan. src/eeg/utils copied into tea_modulo.export with only the
imports changed; outside the EDF pipeline (extra `export`, script ktlx2edf).
Synthetic tests (ktlx_synth, edf export, patient) carried over: 43 pass.
2026-11-18 19:54:48 -06:00

68 lines
2.5 KiB
Python

"""
EDF+ annotations (the file's events) from sample-indexed events.
All onsets are relative to the first sample written to the file. MNE drops
annotations outside the data when it loads a file, so events before the start
or after the end are moved to the edge and the shift is written in the text.
"""
from __future__ import annotations
from collections.abc import Iterable
import numpy as np
from edfio import EdfAnnotation
# MNE's label for skipped acquisition; excluded by reject_by_annotation.
BAD_ACQ_SKIP = "BAD_ACQ_SKIP"
def runs(mask: np.ndarray) -> list[tuple[int, int]]:
"""[start, end) runs where mask is True."""
d = np.diff(mask.astype(np.int8), prepend=0, append=0)
return list(zip(np.flatnonzero(d == 1).tolist(),
np.flatnonzero(d == -1).tolist()))
def gap_annotations(valid: np.ndarray, n_pad: int,
fs: float) -> list[EdfAnnotation]:
"""BAD_ACQ_SKIP for each run of invalid samples and for the padded tail."""
out = [EdfAnnotation(a / fs, (b - a) / fs, BAD_ACQ_SKIP)
for a, b in runs(~valid)]
if n_pad:
out.append(EdfAnnotation(len(valid) / fs, n_pad / fs, BAD_ACQ_SKIP))
return out
def clamped(onset_smp: int, dur_smp: int | None, n_data: int, fs: float,
text: str) -> EdfAnnotation:
"""Annotation kept inside [0, n_data), with any shift noted in the text."""
if onset_smp < 0:
text = f"{text} [pre-start {onset_smp / fs:.1f} s]"
dur_smp = None if dur_smp is None else max(dur_smp + onset_smp, 0)
onset_smp = 0
elif onset_smp >= n_data:
text = f"{text} [post-end +{(onset_smp - n_data + 1) / fs:.1f} s]"
onset_smp, dur_smp = n_data - 1, None
if dur_smp is not None:
dur_smp = min(dur_smp, n_data - onset_smp)
return EdfAnnotation(onset_smp / fs,
dur_smp / fs if dur_smp else None, text)
def event_annotations(events: Iterable[tuple[int | None, int | None, str]],
first: int, n_data: int,
fs: float) -> list[EdfAnnotation]:
"""
(stamp, end stamp, text) events in global samples. Events without a
stamp go at 0, flagged in the text.
"""
out = []
for stamp, fin, text in events:
if stamp is None:
out.append(EdfAnnotation(0.0, None, f"{text} [no timestamp]"))
continue
dur = fin - stamp if fin is not None and fin > stamp else None
out.append(clamped(stamp - first, dur, n_data, fs, text))
return out