""" 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