Skip to content

EDF Importer

The EDFImporter class is responsible for importing EMG and other physiological data from EDF (European Data Format) and BDF (BioSemi Data Format) files.

Class Documentation

biosigio.importers.edf

DEDUPLICATED_LABELS_KEY = 'channel_labels_deduplicated' module-attribute

DISCONTINUOUS_VERIFIED_CONTIGUOUS_KEY = 'edf_discontinuous_verified_contiguous' module-attribute

LATE_TIMEKEEPING_ONSET = 'late_timekeeping_onset' module-attribute

MIXED_RATE_POLICIES = ('error', 'resample') module-attribute

logger = logging.getLogger(__name__) module-attribute

BaseImporter

Bases: ABC

Base class for EMG data importers.

Source code in biosigio/importers/base.py
class BaseImporter(ABC):
    """Base class for EMG data importers."""

    @abstractmethod
    def load(self, filepath: str) -> Recording:
        """
        Load EMG data from file.

        Args:
            filepath: Path to the input file

        Returns:
            Recording: Recording object containing the loaded data
        """
        pass

load(filepath) abstractmethod

Load EMG data from file.

Args: filepath: Path to the input file

Returns: Recording: Recording object containing the loaded data

Source code in biosigio/importers/base.py
@abstractmethod
def load(self, filepath: str) -> Recording:
    """
    Load EMG data from file.

    Args:
        filepath: Path to the input file

    Returns:
        Recording: Recording object containing the loaded data
    """
    pass

EDFImporter

Bases: BaseImporter

Importer for EDF/EDF+/BDF format files.

Source code in biosigio/importers/edf.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
class EDFImporter(BaseImporter):
    """Importer for EDF/EDF+/BDF format files."""

    def _determine_channel_type(self, label: str, transducer: str) -> str:
        """
        Determine channel type based on label and transducer info.

        Args:
            label: Channel label from EDF header
            transducer: Transducer type from EDF header

        Returns:
            str: Channel type ('EMG', 'ACC', 'GYRO', etc.)
        """
        label = label.upper()
        transducer = transducer.upper()

        if "EMG" in label or "EMG" in transducer:
            return "EMG"
        elif "EEG" in label or "EEG" in transducer:
            return "EEG"
        elif "ECG" in label or "EKG" in label or "ECG" in transducer:
            return "ECG"
        elif "EOG" in label or "EOG" in transducer:
            return "EOG"
        elif "ACC" in label or "ACCELEROMETER" in transducer:
            return "ACC"
        elif "GYRO" in label or "GYROSCOPE" in transducer:
            return "GYRO"
        elif "TRIG" in label or "TRIGGER" in transducer:
            return "TRIG"
        else:
            return "OTHER"

    def _extract_metadata(self, edf_reader: pyedflib.EdfReader) -> dict:
        """
        Extract metadata from EDF file header.

        Args:
            edf_reader: pyedflib EdfReader instance

        Returns:
            dict: Dictionary containing file metadata
        """
        header = edf_reader.getHeader()
        signals_headers = edf_reader.getSignalHeaders()

        metadata = {
            "recording_info": {
                "startdate": header.get("startdate", None),
                "patientcode": header.get("patientcode", ""),
                "gender": header.get("gender", ""),
                "birthdate": header.get("birthdate", ""),
                "patient_name": header.get("patient_name", ""),
                "patient_additional": header.get("patient_additional", ""),
                "admincode": header.get("admincode", ""),
                "technician": header.get("technician", ""),
                "equipment": header.get("equipment", ""),
                "recording_additional": header.get("recording_additional", ""),
            },
            "file_info": {
                "filetype": header.get("filetype", 0),  # 0: EDF, 1: EDF+, 2: BDF+
                "number_of_signals": len(signals_headers),
                "file_duration": header.get("file_duration", 0),
                "datarecord_duration": header.get("datarecord_duration", 0),
            },
        }

        return metadata

    def _read_signal_data(
        self, edf_reader: pyedflib.EdfReader, signal_idx: int
    ) -> tuple[np.ndarray, dict]:
        """
        Read signal data and header information for a specific channel.

        Args:
            edf_reader: pyedflib EdfReader instance
            signal_idx: Index of the signal to read

        Returns:
            tuple: (signal_data, signal_info)
        """
        # Get signal header
        signal_header = edf_reader.getSignalHeaders()[signal_idx]

        # Read the signal data
        signal_data = edf_reader.readSignal(signal_idx)

        # Extract signal information
        signal_info = {
            "label": cast(str, signal_header["label"]).strip(),
            "transducer": cast(str, signal_header.get("transducer", "")).strip(),
            "physical_dimension": cast(str, signal_header.get("dimension", "")).strip() or "n/a",
            "physical_min": signal_header["physical_min"],
            "physical_max": signal_header["physical_max"],
            "digital_min": signal_header["digital_min"],
            "digital_max": signal_header["digital_max"],
            "prefilter": cast(str, signal_header.get("prefilter", "")).strip() or "n/a",
            "sample_frequency": signal_header["sample_frequency"],
        }

        return signal_data, signal_info

    def _events_from_annotations(
        self, onsets: np.ndarray, durations: np.ndarray, descriptions: np.ndarray
    ) -> pd.DataFrame:
        """Turn EDF+/BDF+ annotations (events) into an events DataFrame.

        ``pyedflib.EdfReader.readAnnotations`` parses the dedicated annotations
        channel and returns parallel arrays of onsets (seconds), durations
        (seconds), and descriptions, which is what this takes. Plain EDF (no
        annotations) yields empty arrays. Descriptions may be bytes or str
        depending on the pyedflib version; both are handled, and empty
        placeholder annotations are skipped.

        Returns:
            pd.DataFrame: events with float64 ``onset``/``duration`` and string
            ``description``, sorted by onset (matching :meth:`Recording.add_event`).
        """
        rows = []
        for onset, duration, description in zip(onsets, durations, descriptions, strict=False):
            text = (
                description.decode("utf-8", "replace")
                if isinstance(description, bytes)
                else str(description)
            )
            if text == "":
                continue  # skip empty placeholder annotations
            rows.append((float(onset), float(duration), text))

        events = pd.DataFrame(rows, columns=["onset", "duration", "description"])
        if not events.empty:
            events = events.sort_values(by="onset").reset_index(drop=True)
            events["onset"] = events["onset"].astype("float64")
            events["duration"] = events["duration"].astype("float64")
        return events

    def _collect_via_pyedflib(
        self,
        edf_reader: pyedflib.EdfReader,
        annotations: tuple[np.ndarray, np.ndarray, np.ndarray],
    ) -> tuple[list[tuple[dict, np.ndarray]], pd.DataFrame, dict, dict]:
        """Read every signal and header field from an open pyedflib reader.

        ``annotations`` is what ``edf_reader.readAnnotations()`` returns: the
        normal path asks the reader for it, while a file whose annotation walk
        pyedflib refuses (see ``_edf_tolerant.probe_timekeeping_onset``) is opened
        without annotations and passes the arrays the probe validated.

        Returns ``(signal_info, signal_data)`` pairs, events, and the
        ``recording_info`` and ``file_info`` dicts, in the shape :meth:`load` uses
        whichever path produced them.
        """
        metadata = self._extract_metadata(edf_reader)
        pairs = []
        for i in range(edf_reader.signals_in_file):
            signal_data, signal_info = self._read_signal_data(edf_reader, i)
            pairs.append((signal_info, signal_data))
        events = self._events_from_annotations(*annotations)
        return pairs, events, metadata["recording_info"], metadata["file_info"]

    def _collect_via_fallback(
        self, filepath: str, reason: str
    ) -> tuple[list[tuple[dict, np.ndarray]], pd.DataFrame, dict, dict[str, str]]:
        """Recover a file pyedflib refuses to open (see ``_edf_tolerant``).

        Returns the same ``(signal_info, signal_data)`` pairs the normal path
        builds from ``_read_signal_data``, plus events, a ``file_info`` dict and
        the fallback reader's label renames (``{new: header_label}``), so the
        rest of :meth:`load` runs unchanged regardless of which path produced
        them. The pairs already carry the de-duplicated labels, so the renames
        are only known from here.
        """
        fallback = read_edf_tolerant(filepath, reason)
        pairs = [
            (
                {
                    "label": ch.label,
                    "transducer": ch.transducer,
                    "physical_dimension": ch.physical_dimension,
                    "physical_min": ch.physical_min,
                    "physical_max": ch.physical_max,
                    "digital_min": ch.digital_min,
                    "digital_max": ch.digital_max,
                    "prefilter": ch.prefilter,
                    "sample_frequency": ch.sample_frequency,
                    "degenerate_physical_range": ch.degenerate_physical_range,
                },
                ch.data,
            )
            for ch in fallback.channels
        ]
        file_info = {
            "filetype": fallback.filetype,
            "number_of_signals": len(fallback.channels),
            "file_duration": fallback.file_duration,
            "datarecord_duration": fallback.datarecord_duration,
        }
        if fallback.verified_contiguous:
            # Labeled EDF+D/BDF+D, but every record starts where the last ended.
            file_info[DISCONTINUOUS_VERIFIED_CONTIGUOUS_KEY] = True
        return pairs, fallback.events, file_info, fallback.renamed_labels

    def load(self, filepath: str, *, mixed_rate: str = "error") -> Recording:
        """
        Load EMG data from EDF/EDF+/BDF file.

        Three conditions pyedflib's compliance checker rejects outright are
        instead recovered via a tolerant MNE-backed fallback, rescaled back to
        pyedflib-equivalent physical units (see ``_edf_tolerant`` for the full
        rationale and the unit-parity proof): a channel with
        ``physical_min == physical_max`` (issue #109), a numeric header field
        padded with NUL bytes instead of spaces, and a file marked EDF+D
        (discontinuous) whose data records are verified contiguous. An EDF+D/BDF+D
        file with a gap between records is refused with
        :class:`~biosigio.exceptions.DiscontinuousRecordingError` (issue #180).
        A fourth, an EDF+C/BDF+C recording cut out of a
        longer session whose first time-keeping onset is 1 s or more (issue
        #145), is read by pyedflib itself with its annotation walk switched off,
        after a TAL-only copy proves that is the file's only defect: no MNE, and
        the samples are exactly a compliant file's. Its ``startdate`` is the
        header's plus that onset, and ``edf_first_record_onset`` records the
        onset in seconds. A recovered read is flagged in metadata via
        ``edf_tolerant_read`` / ``edf_tolerant_read_reason``. Anything else --
        including a genuinely truncated/corrupt file -- still raises
        :class:`~biosigio.exceptions.CorruptFileError` as before. When one of the
        three MNE-backed conditions needs the fallback and MNE is not installed,
        an ``ImportError`` naming the ``meg`` extra is raised, its ``__cause__``
        the pyedflib error.

        Args:
            filepath: Path to the EDF file
            mixed_rate: Policy when the file's signals carry differing per-channel
                sampling rates (EDF/BDF allow it, e.g. polysomnography). ``"error"``
                (default) raises, since biosigIO stores one uniform grid and a
                fabricated common grid would be unfaithful; ``"resample"`` upsamples
                the slower channels to the fastest rate (a lossy derived view -- the
                original rate is kept on each channel as ``original_sample_frequency``).

        Returns:
            Recording: Recording object containing the loaded data
        """
        if mixed_rate not in MIXED_RATE_POLICIES:
            raise ValueError(f"mixed_rate must be one of {MIXED_RATE_POLICIES}, got {mixed_rate!r}")
        edf_reader: pyedflib.EdfReader | None = None
        # An OSError the late-onset probe raises is the host's (the scratch copy it
        # could not create or write, whatever the errno), never the file's: the
        # handler below lets that exact exception out untyped.
        probe_failure: OSError | None = None
        try:
            fallback_reason: str | None
            first_onset: float | None = None
            recording_info: dict
            try:
                edf_reader = pyedflib.EdfReader(filepath)
            except Exception as open_exc:
                # pyedflib hides an OS refusal (EACCES, EIO) behind its own
                # errno-less message; recover the real OSError so the handler
                # below propagates it as the host condition it is.
                raise_host_open_error(filepath, open_exc)
                fallback_reason = classify_pyedflib_error(open_exc)
                if fallback_reason is None:
                    # EDFlib words a late first time-keeping onset like any other
                    # bad annotation list. When that is provably the only defect,
                    # pyedflib itself reads the file with its annotation walk
                    # switched off: no MNE, and the samples are a normal read's.
                    try:
                        late = probe_timekeeping_onset(filepath, open_exc)
                    except OSError as host_error:
                        probe_failure = host_error
                        raise
                    if late is None:
                        raise
                    fallback_reason = LATE_TIMEKEEPING_ONSET
                    first_onset = late.first_onset
                    edf_reader = pyedflib.EdfReader(
                        filepath, annotations_mode=pyedflib.DO_NOT_READ_ANNOTATIONS
                    )
                    pairs, events, recording_info, file_info = self._collect_via_pyedflib(
                        edf_reader, late.annotations
                    )
                    fallback_renames = {}
                    # The header's start date is the session's; this recording
                    # starts at its first record, `first_onset` seconds later.
                    recording_info["startdate"] = late.startdate
                else:
                    try:
                        pairs, events, file_info, fallback_renames = self._collect_via_fallback(
                            filepath, fallback_reason
                        )
                    except ImportError as import_err:
                        # MNE (the `meg` extra) isn't installed. That is this
                        # environment, not the file, so it stays an ImportError
                        # (untyped, as the streaming source raises it) rather than
                        # becoming a permanent read failure; the pyedflib error it
                        # would have recovered from is its __cause__.
                        logger.warning(
                            "EDF/BDF file %s is recoverable by the tolerant reader, but that "
                            "needs MNE-Python (the 'meg' extra), which is not installed.",
                            filepath,
                        )
                        raise ImportError(
                            f"EDF/BDF file {filepath} can only be read by the tolerant "
                            "reader, which needs MNE-Python: install the 'meg' extra "
                            f"({import_err})"
                        ) from open_exc
                    recording_info = {}
            else:
                fallback_reason = None
                fallback_renames = {}
                pairs, events, recording_info, file_info = self._collect_via_pyedflib(
                    edf_reader, edf_reader.readAnnotations()
                )

            # Create Recording object
            rec = Recording()

            # Extract and store metadata
            for key, value in recording_info.items():
                if value:  # Only store non-empty values
                    rec.set_metadata(key, value)
            for key, value in file_info.items():
                rec.set_metadata(key, value)

            # Store source file information
            rec.set_metadata("source_file", filepath)

            # A Recording is keyed by label, so a repeated header label would
            # silently overwrite a channel; suffix duplicates as MNE does. The
            # header's own label stays untouched in signal_info. Every rename is
            # recorded on the Recording (and so in a Zarr store's metadata), not
            # only logged.
            labels, renames = unique_channel_labels(
                [info["label"] for info, _ in pairs], filepath=filepath
            )
            renames = {**fallback_renames, **renames}
            if renames:
                rec.set_metadata(DEDUPLICATED_LABELS_KEY, renames)

            # Read every signal up front so a mixed per-channel rate is detected
            # before any channel is added: channels of differing native length
            # cannot share the Recording's single time grid, so add_channel would
            # raise mid-load. Each entry: (label, signal_info, signal_data,
            # channel_type).
            collected: list[tuple[str, dict, np.ndarray, str]] = []
            for label, (signal_info, signal_data) in zip(labels, pairs, strict=True):
                channel_type = self._determine_channel_type(label, signal_info["transducer"])
                collected.append((label, signal_info, signal_data, channel_type))

            rates = {info["sample_frequency"] for _, info, _, _ in collected}
            target_rate: float | None = None
            n_out = 0
            if len(rates) > 1:
                if mixed_rate == "error":
                    raise MixedSamplingRateError(
                        "EDF/BDF recording has mixed per-channel sampling rates "
                        f"({sorted(rates)} Hz); biosigIO stores one uniform grid. This "
                        "is a real BIDS montage (e.g. polysomnography: EEG ~200 Hz + "
                        'SpO2/respiration ~12.5 Hz). Pass mixed_rate="resample" to '
                        "upsample the slower channels to the fastest rate for a single-"
                        "grid serving copy (lossy: a derived view, not the faithful "
                        'source), or read channels[ch]["sample_frequency"] per channel '
                        "to handle the rates yourself."
                    )
                # resample: lift every slower channel onto the fastest channel's grid.
                target_rate = max(rates)
                n_out = max(len(data) for _, _, data, _ in collected)

            # Add channels (resampling the slow ones first when mixed_rate="resample").
            for label, signal_info, signal_data, channel_type in collected:
                native = float(signal_info["sample_frequency"])
                freq = native
                resampled = target_rate is not None and native != target_rate
                if resampled:
                    signal_data = _resample_to_length(signal_data, n_out)
                    freq = float(target_rate)  # type: ignore[arg-type]  # non-None when resampled

                rec.add_channel(
                    label=label,
                    data=signal_data,
                    sample_frequency=freq,
                    physical_dimension=signal_info["physical_dimension"],
                    prefilter=signal_info["prefilter"],
                    channel_type=channel_type,
                )

                # Store additional channel-specific metadata
                channel_metadata = {
                    "physical_min": signal_info["physical_min"],
                    "physical_max": signal_info["physical_max"],
                    "digital_min": signal_info["digital_min"],
                    "digital_max": signal_info["digital_max"],
                    "transducer": signal_info["transducer"],
                }
                if resampled:
                    # Preserve the true acquisition rate (metadata loss is data loss).
                    channel_metadata["original_sample_frequency"] = native
                if signal_info.get("degenerate_physical_range"):
                    # physical_min == physical_max: the scale factor is undefined
                    # and the fallback path emitted a constant channel (see
                    # _edf_tolerant.read_edf_tolerant). Flag it the same way
                    # nonfinite_samples flags a suspect channel, so downstream
                    # consumers (e.g. the Zarr exporter) can tell this channel's
                    # data is a physically-forced constant, not a measurement.
                    channel_metadata["degenerate_physical_range"] = True
                rec.channels[label].update(channel_metadata)

            if target_rate is not None:
                # Flag the recording as a resampled derived view so downstream
                # consumers (and humans) know the grid is fabricated, not native.
                rec.set_metadata("mixed_rate_resampled", True)
                rec.set_metadata("mixed_rate_target_hz", float(target_rate))

            if fallback_reason is not None:
                # Flag that this recording only loaded because of a tolerant
                # recovery (see module docstring / _edf_tolerant), so downstream
                # consumers can tell a recovered read from a fully-compliant one.
                rec.set_metadata("edf_tolerant_read", True)
                rec.set_metadata("edf_tolerant_read_reason", fallback_reason)
                if first_onset is not None:
                    # Seconds from the session's start to this recording's first
                    # record: the file was cut out of a longer session, and its
                    # `startdate` already includes this offset.
                    rec.set_metadata("edf_first_record_onset", first_onset)

            # Events (EDF+/BDF+ annotations) survive the import->export->import
            # round-trip (issue #47): assigned directly (not via add_event) for a
            # single sort, since both `_events_from_annotations` and the fallback's
            # `_events_from_mne_annotations` already return the same schema
            # add_event produces (float64 onset/duration, sorted by onset). Left
            # as the empty __init__ frame when none exist.
            if not events.empty:
                rec.events = events

            return rec

        except ImportError:
            # Only the tolerant fallback's missing `meg` extra raises this (see
            # above): an environment problem, never typed as a file failure.
            raise
        except Exception as e:
            # Resource exhaustion (MemoryError -- incl. numpy's _ArrayMemoryError
            # from the per-channel readSignal loop above -- or a thread/allocation
            # -exhaustion OSError/RuntimeError) is a host condition, not a file
            # problem: propagate it unchanged rather than reclassifying it as a
            # permanent read failure (issue #123; see
            # biosigio.exceptions.is_resource_exhaustion). This also covers an
            # EdfReader-open failure above that classify_pyedflib_error found no
            # recoverable cause for, which reaches here via a bare re-raise. The
            # late-onset probe's own OSError (see `probe_failure` above) leaves the
            # same way.
            if is_resource_exhaustion(e) or e is probe_failure:
                raise
            # Typed classification: a truncated/non-compliant EDF (pyedflib's
            # "Filesize" check) becomes CorruptFileError so callers can surface a
            # specific reason. A BiosigIOError (e.g. the mixed_rate policy error)
            # passes through unchanged.
            raise classify_read_error(e, filepath) from e

        finally:
            # An exception from the try body (e.g. a MemoryError from the
            # readSignal loop) can be propagating through this finally right
            # now. pyedflib's close() is a C-extension call that can itself
            # fail on a saturated host; unguarded, that failure would REPLACE
            # the propagating exception outright. is_resource_exhaustion's
            # __cause__/__context__ walk (biosigio.exceptions) can recover a
            # masked exception when the replacement is a NEW raised exception,
            # but that is strictly worse than not masking it at all -- so
            # cleanup here never raises, only logs.
            if edf_reader is not None:
                try:
                    edf_reader.close()
                except Exception as close_exc:
                    logger.warning("EDF reader close() failed for %s: %s", filepath, close_exc)

load(filepath, *, mixed_rate='error')

Load EMG data from EDF/EDF+/BDF file.

Three conditions pyedflib's compliance checker rejects outright are instead recovered via a tolerant MNE-backed fallback, rescaled back to pyedflib-equivalent physical units (see _edf_tolerant for the full rationale and the unit-parity proof): a channel with physical_min == physical_max (issue #109), a numeric header field padded with NUL bytes instead of spaces, and a file marked EDF+D (discontinuous) whose data records are verified contiguous. An EDF+D/BDF+D file with a gap between records is refused with :class:~biosigio.exceptions.DiscontinuousRecordingError (issue #180). A fourth, an EDF+C/BDF+C recording cut out of a longer session whose first time-keeping onset is 1 s or more (issue

145), is read by pyedflib itself with its annotation walk switched off,

after a TAL-only copy proves that is the file's only defect: no MNE, and the samples are exactly a compliant file's. Its startdate is the header's plus that onset, and edf_first_record_onset records the onset in seconds. A recovered read is flagged in metadata via edf_tolerant_read / edf_tolerant_read_reason. Anything else -- including a genuinely truncated/corrupt file -- still raises :class:~biosigio.exceptions.CorruptFileError as before. When one of the three MNE-backed conditions needs the fallback and MNE is not installed, an ImportError naming the meg extra is raised, its __cause__ the pyedflib error.

Args: filepath: Path to the EDF file mixed_rate: Policy when the file's signals carry differing per-channel sampling rates (EDF/BDF allow it, e.g. polysomnography). "error" (default) raises, since biosigIO stores one uniform grid and a fabricated common grid would be unfaithful; "resample" upsamples the slower channels to the fastest rate (a lossy derived view -- the original rate is kept on each channel as original_sample_frequency).

Returns: Recording: Recording object containing the loaded data

Source code in biosigio/importers/edf.py
def load(self, filepath: str, *, mixed_rate: str = "error") -> Recording:
    """
    Load EMG data from EDF/EDF+/BDF file.

    Three conditions pyedflib's compliance checker rejects outright are
    instead recovered via a tolerant MNE-backed fallback, rescaled back to
    pyedflib-equivalent physical units (see ``_edf_tolerant`` for the full
    rationale and the unit-parity proof): a channel with
    ``physical_min == physical_max`` (issue #109), a numeric header field
    padded with NUL bytes instead of spaces, and a file marked EDF+D
    (discontinuous) whose data records are verified contiguous. An EDF+D/BDF+D
    file with a gap between records is refused with
    :class:`~biosigio.exceptions.DiscontinuousRecordingError` (issue #180).
    A fourth, an EDF+C/BDF+C recording cut out of a
    longer session whose first time-keeping onset is 1 s or more (issue
    #145), is read by pyedflib itself with its annotation walk switched off,
    after a TAL-only copy proves that is the file's only defect: no MNE, and
    the samples are exactly a compliant file's. Its ``startdate`` is the
    header's plus that onset, and ``edf_first_record_onset`` records the
    onset in seconds. A recovered read is flagged in metadata via
    ``edf_tolerant_read`` / ``edf_tolerant_read_reason``. Anything else --
    including a genuinely truncated/corrupt file -- still raises
    :class:`~biosigio.exceptions.CorruptFileError` as before. When one of the
    three MNE-backed conditions needs the fallback and MNE is not installed,
    an ``ImportError`` naming the ``meg`` extra is raised, its ``__cause__``
    the pyedflib error.

    Args:
        filepath: Path to the EDF file
        mixed_rate: Policy when the file's signals carry differing per-channel
            sampling rates (EDF/BDF allow it, e.g. polysomnography). ``"error"``
            (default) raises, since biosigIO stores one uniform grid and a
            fabricated common grid would be unfaithful; ``"resample"`` upsamples
            the slower channels to the fastest rate (a lossy derived view -- the
            original rate is kept on each channel as ``original_sample_frequency``).

    Returns:
        Recording: Recording object containing the loaded data
    """
    if mixed_rate not in MIXED_RATE_POLICIES:
        raise ValueError(f"mixed_rate must be one of {MIXED_RATE_POLICIES}, got {mixed_rate!r}")
    edf_reader: pyedflib.EdfReader | None = None
    # An OSError the late-onset probe raises is the host's (the scratch copy it
    # could not create or write, whatever the errno), never the file's: the
    # handler below lets that exact exception out untyped.
    probe_failure: OSError | None = None
    try:
        fallback_reason: str | None
        first_onset: float | None = None
        recording_info: dict
        try:
            edf_reader = pyedflib.EdfReader(filepath)
        except Exception as open_exc:
            # pyedflib hides an OS refusal (EACCES, EIO) behind its own
            # errno-less message; recover the real OSError so the handler
            # below propagates it as the host condition it is.
            raise_host_open_error(filepath, open_exc)
            fallback_reason = classify_pyedflib_error(open_exc)
            if fallback_reason is None:
                # EDFlib words a late first time-keeping onset like any other
                # bad annotation list. When that is provably the only defect,
                # pyedflib itself reads the file with its annotation walk
                # switched off: no MNE, and the samples are a normal read's.
                try:
                    late = probe_timekeeping_onset(filepath, open_exc)
                except OSError as host_error:
                    probe_failure = host_error
                    raise
                if late is None:
                    raise
                fallback_reason = LATE_TIMEKEEPING_ONSET
                first_onset = late.first_onset
                edf_reader = pyedflib.EdfReader(
                    filepath, annotations_mode=pyedflib.DO_NOT_READ_ANNOTATIONS
                )
                pairs, events, recording_info, file_info = self._collect_via_pyedflib(
                    edf_reader, late.annotations
                )
                fallback_renames = {}
                # The header's start date is the session's; this recording
                # starts at its first record, `first_onset` seconds later.
                recording_info["startdate"] = late.startdate
            else:
                try:
                    pairs, events, file_info, fallback_renames = self._collect_via_fallback(
                        filepath, fallback_reason
                    )
                except ImportError as import_err:
                    # MNE (the `meg` extra) isn't installed. That is this
                    # environment, not the file, so it stays an ImportError
                    # (untyped, as the streaming source raises it) rather than
                    # becoming a permanent read failure; the pyedflib error it
                    # would have recovered from is its __cause__.
                    logger.warning(
                        "EDF/BDF file %s is recoverable by the tolerant reader, but that "
                        "needs MNE-Python (the 'meg' extra), which is not installed.",
                        filepath,
                    )
                    raise ImportError(
                        f"EDF/BDF file {filepath} can only be read by the tolerant "
                        "reader, which needs MNE-Python: install the 'meg' extra "
                        f"({import_err})"
                    ) from open_exc
                recording_info = {}
        else:
            fallback_reason = None
            fallback_renames = {}
            pairs, events, recording_info, file_info = self._collect_via_pyedflib(
                edf_reader, edf_reader.readAnnotations()
            )

        # Create Recording object
        rec = Recording()

        # Extract and store metadata
        for key, value in recording_info.items():
            if value:  # Only store non-empty values
                rec.set_metadata(key, value)
        for key, value in file_info.items():
            rec.set_metadata(key, value)

        # Store source file information
        rec.set_metadata("source_file", filepath)

        # A Recording is keyed by label, so a repeated header label would
        # silently overwrite a channel; suffix duplicates as MNE does. The
        # header's own label stays untouched in signal_info. Every rename is
        # recorded on the Recording (and so in a Zarr store's metadata), not
        # only logged.
        labels, renames = unique_channel_labels(
            [info["label"] for info, _ in pairs], filepath=filepath
        )
        renames = {**fallback_renames, **renames}
        if renames:
            rec.set_metadata(DEDUPLICATED_LABELS_KEY, renames)

        # Read every signal up front so a mixed per-channel rate is detected
        # before any channel is added: channels of differing native length
        # cannot share the Recording's single time grid, so add_channel would
        # raise mid-load. Each entry: (label, signal_info, signal_data,
        # channel_type).
        collected: list[tuple[str, dict, np.ndarray, str]] = []
        for label, (signal_info, signal_data) in zip(labels, pairs, strict=True):
            channel_type = self._determine_channel_type(label, signal_info["transducer"])
            collected.append((label, signal_info, signal_data, channel_type))

        rates = {info["sample_frequency"] for _, info, _, _ in collected}
        target_rate: float | None = None
        n_out = 0
        if len(rates) > 1:
            if mixed_rate == "error":
                raise MixedSamplingRateError(
                    "EDF/BDF recording has mixed per-channel sampling rates "
                    f"({sorted(rates)} Hz); biosigIO stores one uniform grid. This "
                    "is a real BIDS montage (e.g. polysomnography: EEG ~200 Hz + "
                    'SpO2/respiration ~12.5 Hz). Pass mixed_rate="resample" to '
                    "upsample the slower channels to the fastest rate for a single-"
                    "grid serving copy (lossy: a derived view, not the faithful "
                    'source), or read channels[ch]["sample_frequency"] per channel '
                    "to handle the rates yourself."
                )
            # resample: lift every slower channel onto the fastest channel's grid.
            target_rate = max(rates)
            n_out = max(len(data) for _, _, data, _ in collected)

        # Add channels (resampling the slow ones first when mixed_rate="resample").
        for label, signal_info, signal_data, channel_type in collected:
            native = float(signal_info["sample_frequency"])
            freq = native
            resampled = target_rate is not None and native != target_rate
            if resampled:
                signal_data = _resample_to_length(signal_data, n_out)
                freq = float(target_rate)  # type: ignore[arg-type]  # non-None when resampled

            rec.add_channel(
                label=label,
                data=signal_data,
                sample_frequency=freq,
                physical_dimension=signal_info["physical_dimension"],
                prefilter=signal_info["prefilter"],
                channel_type=channel_type,
            )

            # Store additional channel-specific metadata
            channel_metadata = {
                "physical_min": signal_info["physical_min"],
                "physical_max": signal_info["physical_max"],
                "digital_min": signal_info["digital_min"],
                "digital_max": signal_info["digital_max"],
                "transducer": signal_info["transducer"],
            }
            if resampled:
                # Preserve the true acquisition rate (metadata loss is data loss).
                channel_metadata["original_sample_frequency"] = native
            if signal_info.get("degenerate_physical_range"):
                # physical_min == physical_max: the scale factor is undefined
                # and the fallback path emitted a constant channel (see
                # _edf_tolerant.read_edf_tolerant). Flag it the same way
                # nonfinite_samples flags a suspect channel, so downstream
                # consumers (e.g. the Zarr exporter) can tell this channel's
                # data is a physically-forced constant, not a measurement.
                channel_metadata["degenerate_physical_range"] = True
            rec.channels[label].update(channel_metadata)

        if target_rate is not None:
            # Flag the recording as a resampled derived view so downstream
            # consumers (and humans) know the grid is fabricated, not native.
            rec.set_metadata("mixed_rate_resampled", True)
            rec.set_metadata("mixed_rate_target_hz", float(target_rate))

        if fallback_reason is not None:
            # Flag that this recording only loaded because of a tolerant
            # recovery (see module docstring / _edf_tolerant), so downstream
            # consumers can tell a recovered read from a fully-compliant one.
            rec.set_metadata("edf_tolerant_read", True)
            rec.set_metadata("edf_tolerant_read_reason", fallback_reason)
            if first_onset is not None:
                # Seconds from the session's start to this recording's first
                # record: the file was cut out of a longer session, and its
                # `startdate` already includes this offset.
                rec.set_metadata("edf_first_record_onset", first_onset)

        # Events (EDF+/BDF+ annotations) survive the import->export->import
        # round-trip (issue #47): assigned directly (not via add_event) for a
        # single sort, since both `_events_from_annotations` and the fallback's
        # `_events_from_mne_annotations` already return the same schema
        # add_event produces (float64 onset/duration, sorted by onset). Left
        # as the empty __init__ frame when none exist.
        if not events.empty:
            rec.events = events

        return rec

    except ImportError:
        # Only the tolerant fallback's missing `meg` extra raises this (see
        # above): an environment problem, never typed as a file failure.
        raise
    except Exception as e:
        # Resource exhaustion (MemoryError -- incl. numpy's _ArrayMemoryError
        # from the per-channel readSignal loop above -- or a thread/allocation
        # -exhaustion OSError/RuntimeError) is a host condition, not a file
        # problem: propagate it unchanged rather than reclassifying it as a
        # permanent read failure (issue #123; see
        # biosigio.exceptions.is_resource_exhaustion). This also covers an
        # EdfReader-open failure above that classify_pyedflib_error found no
        # recoverable cause for, which reaches here via a bare re-raise. The
        # late-onset probe's own OSError (see `probe_failure` above) leaves the
        # same way.
        if is_resource_exhaustion(e) or e is probe_failure:
            raise
        # Typed classification: a truncated/non-compliant EDF (pyedflib's
        # "Filesize" check) becomes CorruptFileError so callers can surface a
        # specific reason. A BiosigIOError (e.g. the mixed_rate policy error)
        # passes through unchanged.
        raise classify_read_error(e, filepath) from e

    finally:
        # An exception from the try body (e.g. a MemoryError from the
        # readSignal loop) can be propagating through this finally right
        # now. pyedflib's close() is a C-extension call that can itself
        # fail on a saturated host; unguarded, that failure would REPLACE
        # the propagating exception outright. is_resource_exhaustion's
        # __cause__/__context__ walk (biosigio.exceptions) can recover a
        # masked exception when the replacement is a NEW raised exception,
        # but that is strictly worse than not masking it at all -- so
        # cleanup here never raises, only logs.
        if edf_reader is not None:
            try:
                edf_reader.close()
            except Exception as close_exc:
                logger.warning("EDF reader close() failed for %s: %s", filepath, close_exc)

MixedSamplingRateError

Bases: BiosigIOError

An EDF/BDF carries differing per-channel sampling rates and the caller's mixed_rate policy is "error" (the default). Not a read failure -- the caller can re-read with mixed_rate="resample". The serving pipeline does exactly that, so this rarely surfaces to users.

Source code in biosigio/exceptions.py
class MixedSamplingRateError(BiosigIOError):
    """An EDF/BDF carries differing per-channel sampling rates and the caller's
    ``mixed_rate`` policy is ``"error"`` (the default). Not a read failure -- the
    caller can re-read with ``mixed_rate="resample"``. The serving pipeline does
    exactly that, so this rarely surfaces to users."""

    code = "mixed_sampling_rate"

Recording

Core biosignal recording: signals + channels + events + metadata.

Modality-agnostic container for EEG / EMG / iEEG / MEG / stim / marker data imported from any supported format.

Attributes: signals (pd.DataFrame): Raw signal data with time as index. metadata (dict): Metadata dictionary containing recording information. channels (dict): Channel information including type, unit, sampling frequency. events (pd.DataFrame): Annotations or events associated with the signals, with columns 'onset', 'duration', 'description'.

Source code in biosigio/core/emg.py
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
class Recording:
    """
    Core biosignal recording: signals + channels + events + metadata.

    Modality-agnostic container for EEG / EMG / iEEG / MEG / stim / marker data
    imported from any supported format.

    Attributes:
        signals (pd.DataFrame): Raw signal data with time as index.
        metadata (dict): Metadata dictionary containing recording information.
        channels (dict): Channel information including type, unit, sampling frequency.
        events (pd.DataFrame): Annotations or events associated with the signals,
                               with columns 'onset', 'duration', 'description'.
    """

    def __init__(self):
        """Initialize an empty recording."""
        self.signals = None
        self.metadata = {}
        self.channels = {}
        # Initialize events as an empty DataFrame with specified columns
        self.events = pd.DataFrame(columns=["onset", "duration", "description"])

    def plot_signals(
        self,
        channels=None,
        time_range=None,
        offset_scale=0.8,
        uniform_scale=True,
        detrend=False,
        grid=True,
        title=None,
        show=True,
        plt_module=None,
    ):
        """
        Plot signals in a single plot with vertical offsets.

        Args:
            channels: List of channels to plot. If None, plot all channels.
            time_range: Tuple of (start_time, end_time) to plot. If None, plot all data.
            offset_scale: Portion of allocated space each signal can use (0.0 to 1.0).
            uniform_scale: Whether to use the same scale for all signals.
            detrend: Whether to remove mean from signals before plotting.
            grid: Whether to show grid lines.
            title: Optional title for the figure.
            show: Whether to display the plot.
            plt_module: Matplotlib pyplot module to use.
        """
        # Delegate to the static plotting function in visualization module
        static_plot_signals(
            rec_object=self,
            channels=channels,
            time_range=time_range,
            offset_scale=offset_scale,
            uniform_scale=uniform_scale,
            detrend=detrend,
            grid=grid,
            title=title,
            show=show,
            plt_module=plt_module,
        )

    @classmethod
    def _infer_importer(cls, filepath: str) -> ImporterName:
        """
        Infer the importer to use based on the file extension.
        """
        # rstrip path separators so a Zarr store passed as a directory with a
        # trailing slash (e.g. "rec.zarr/") still resolves by its ".zarr" suffix.
        extension = os.path.splitext(filepath.rstrip("/\\"))[1].lower()
        if extension in {".edf", ".bdf"}:
            return "edf"
        elif extension in {".set"}:
            return "eeglab"
        elif extension in {".otb", ".otb+"}:
            return "otb"
        elif extension in {".csv", ".txt"}:
            return "csv"
        elif extension in {".hea", ".dat", ".atr"}:
            return "wfdb"
        elif extension in {".xdf", ".xdfz"}:
            return "xdf"
        elif extension in {".fif", ".ds", ".con", ".sqd", ".kdf"}:
            # MEG via MNE: .fif (Neuromag/FIF), CTF .ds directory, KIT/Yokogawa
            # .con/.sqd/.kdf. The MEGImporter dispatches on extension internally.
            return "meg"
        elif extension in {".vhdr"}:
            return "brainvision"
        elif extension == ".mefd":
            # MEF3 (a directory, like CTF .ds) is a distinct iEEG modality with its
            # own MNE/pymef version floor -- see importers/mef3.py -- so it is its
            # own importer name rather than folding into "meg".
            return "mef3"
        elif extension == "" and os.path.isdir(filepath.rstrip("/\\")):
            # 4D/BTi ships as a directory with NO extension, so it cannot be
            # recognized above; fall back to content-based detection. Lazy
            # import: avoids importing the importers package (and MNE) just to
            # infer a name, and avoids a core<->importers import cycle.
            #
            # _resolve_bti_reader_kwargs is the ONE place that decides "is this
            # a valid BTi layout" and raises UnsupportedFormatError if not --
            # shared with MEGImporter._read_raw and the streaming path (see
            # importers/meg.py's module docstring) so there is exactly one
            # raise site to keep correct, not one per call site.
            from ..importers.meg import _resolve_bti_reader_kwargs

            _resolve_bti_reader_kwargs(filepath.rstrip("/\\"))
            return "meg"
        elif extension in {".parquet", ".feather", ".arrow"}:
            return "tabular"
        elif extension in {
            ".rhd",
            ".rhs",
            ".ns1",
            ".ns2",
            ".ns3",
            ".ns4",
            ".ns5",
            ".ns6",
            ".smr",
            ".smrx",
            ".plx",
            ".pl2",
            ".trc",
            ".ncs",
        }:
            return "neo"
        elif extension == ".zarr":
            return "zarr"
        else:
            raise UnsupportedFormatError(f"Unsupported file extension: {extension!r}")

    @classmethod
    def from_file(
        cls,
        filepath: str,
        importer: ImporterName | None = None,
        force_csv: bool = False,
        bids_channels: "str | os.PathLike | pd.DataFrame | None" = "auto",
        mixed_rate: str = "error",
        *,
        allow_partial_frame: bool = False,
        **kwargs,
    ) -> "Recording":
        """
        The method to create a Recording object from file.

        Args:
            filepath: Path to the input file
            importer: Name of the importer to use. Can be one of the following:
                - 'trigno': Delsys Trigno EMG system (CSV)
                - 'otb': OTB/OTB+ EMG system (OTB, OTB+)
                - 'eeglab': EEGLAB .set files (SET)
                - 'edf': EDF/EDF+/BDF/BDF+ format (EDF, BDF)
                - 'csv': Generic CSV (or TXT) files with columnar data
                - 'wfdb': Waveform Database (WFDB)
                - 'xdf': XDF format (multi-stream Lab Streaming Layer files)
                - 'meg': MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi
                  directory (no extension, detected by content); requires the
                  'meg' extra)
                - 'brainvision': BrainVision .vhdr via MNE (requires the 'meg' extra)
                - 'mef3': MEF3 iEEG via MNE (.mefd directory; requires the 'mef3'
                  extra -- mne>=1.12 plus pymef, stricter than the 'meg' extra)
                - 'tabular': biosigIO Parquet/Arrow/Feather (requires the 'arrow' extra)
                - 'neo': proprietary electrophysiology formats via python-neo
                  (Intan, Blackrock, Spike2, Plexon, Micromed, Neuralynx, ...;
                  requires the 'neo' extra)
                - 'zarr': biosigIO Zarr serving store (requires the 'zarr' extra)
                If None, the importer will be inferred from the file extension.
                Automatic import is supported for CSV/TXT files.
            force_csv: If True and importer is 'csv', forces using the generic CSV
                      importer even if the file appears to match a specialized format.
            bids_channels: Which BIDS ``_channels.tsv`` to apply over the
                      importer's inferred per-channel type/units. 'auto'
                      (default) looks for the sibling sidecar next to the file;
                      'off' (or None) disables the lookup; a path or a pandas
                      DataFrame is used as given, for a recording whose sidecar
                      is not adjacent to it (a filtered copy on scratch, say).
                      Adopting a declared unit converts the samples into it, not
                      just the label. ``stream_to_zarr`` takes the same argument
                      with the same meanings, so the in-memory and streaming
                      export paths agree on a recording (issue #127).
            mixed_rate: Policy for an EDF/BDF file whose signals carry differing
                      per-channel sampling rates (ignored for every other format,
                      which is single-rate). 'error' (default) raises -- biosigIO
                      stores one uniform grid and will not fabricate a common one
                      silently. 'resample' upsamples the slower channels to the
                      fastest rate (a lossy derived view; each channel keeps its
                      native rate as ``original_sample_frequency``).
            allow_partial_frame: BrainVision only (ignored for every other format).
                      A binary data file whose size is not a whole number of frames
                      raises ``CorruptFileError`` by default. True reads the whole
                      frames of a MULTIPLEXED file that ends in a partial frame (and
                      declares no positive ``DataPoints=``), with a ``UserWarning``
                      naming the file and the dropped byte count; the count is kept in
                      the metadata as ``brainvision_dropped_bytes``. Vectorized data,
                      a file smaller than a positive ``DataPoints=`` and a file that
                      holds no whole frame are still refused. Keyword-only.
                      ``stream_to_zarr`` takes the same argument.
            **kwargs: Additional arguments passed to the importer.
                For XDF files, useful kwargs include:
                - stream_names: List of stream names to import
                - stream_types: List of stream types to import (e.g., ["EMG", "EXG"])
                - stream_ids: List of stream IDs to import

        Returns:
            Recording: New Recording object with loaded data
        """
        if importer is None:
            importer = cls._infer_importer(filepath)

        importers = {
            "trigno": "TrignoImporter",  # CSV with Delsys Trigno Headers
            "otb": "OTBImporter",  # OTB/OTB+ EMG system data
            "edf": "EDFImporter",  # EDF/EDF+/BDF format
            "eeglab": "EEGLABImporter",  # EEGLAB .set files
            "csv": "CSVImporter",  # Generic CSV/Text files
            "wfdb": "WFDBImporter",  # Waveform Database format
            "xdf": "XDFImporter",  # XDF multi-stream format
            "meg": "MEGImporter",  # MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi)
            "brainvision": "BrainVisionImporter",  # BrainVision via MNE (.vhdr)
            "mef3": "MEF3Importer",  # MEF3 iEEG via MNE (.mefd; requires the 'mef3' extra)
            "tabular": "TabularImporter",  # biosigIO Parquet / Arrow / Feather
            "neo": "NeoImporter",  # proprietary ephys via python-neo
            "zarr": "ZarrImporter",  # biosigIO Zarr serving store
        }

        if importer not in importers:
            raise ValueError(
                f"Unsupported importer: {importer}. "
                f"Available importers: {list(importers.keys())}\n"
                "- trigno: Delsys Trigno EMG system\n"
                "- otb: OTB/OTB+ EMG system\n"
                "- edf: EDF/EDF+/BDF format\n"
                "- eeglab: EEGLAB .set files\n"
                "- csv: Generic CSV/Text files\n"
                "- wfdb: Waveform Database\n"
                "- xdf: XDF multi-stream format\n"
                "- meg: MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi directory)\n"
                "- brainvision: BrainVision via MNE (.vhdr)\n"
                "- mef3: MEF3 iEEG via MNE (.mefd directory; requires the 'mef3' extra)\n"
                "- tabular: biosigIO Parquet/Arrow/Feather (.parquet, .feather, .arrow)\n"
                "- neo: proprietary electrophysiology formats via python-neo "
                "(Intan, Blackrock, Spike2, Plexon, Micromed, Neuralynx, ...)\n"
                "- zarr: biosigIO Zarr serving store (.zarr)"
            )

        # If using CSV importer and force_csv is set, pass it as force_generic
        if importer == "csv":
            kwargs["force_generic"] = force_csv

        # mixed_rate is only meaningful for EDF/BDF, the one format whose signals may
        # carry differing per-channel sampling rates; forward it there and nowhere
        # else (so the default "error" never reaches an importer that can't use it).
        if importer == "edf":
            kwargs["mixed_rate"] = mixed_rate

        # allow_partial_frame likewise only means something to the BrainVision reader.
        if importer == "brainvision":
            kwargs["allow_partial_frame"] = allow_partial_frame

        # Import the appropriate importer class
        importer_module = __import__(
            f"biosigio.importers.{importer}", globals(), locals(), [importers[importer]]
        )
        importer_class = getattr(importer_module, importers[importer])

        # Create importer instance and load data
        rec = importer_class().load(filepath, **kwargs)

        # Record provenance: which format this recording came from. setdefault so a
        # re-imported serialization file (tabular/zarr) keeps the ORIGINAL
        # source_format restored from its metadata rather than being relabeled.
        rec.metadata.setdefault("source_format", importer)

        # In a BIDS layout, the sibling _channels.tsv is the authoritative source
        # of per-channel type/units; apply it over the importer's header/label
        # guesses unless explicitly disabled with bids_channels="off". The
        # argument is interpreted by bids.resolve_channels_tsv, shared with
        # stream_to_zarr so the two export paths cannot read it differently.
        from ..bids import apply_channels_tsv, resolve_channels_tsv

        channels_tsv = resolve_channels_tsv(filepath, bids_channels)
        if channels_tsv is not None:
            apply_channels_tsv(rec, channels_tsv)

        return rec

    def select_channels(
        self,
        channels: str | Iterable[str] | None = None,
        channel_type: str | None = None,
        inplace: bool = False,
        *,
        modality: str | None = None,
    ) -> "Recording":
        """
        Select specific channels from the data and return a new Recording object.

        Args:
            channels: Channel name, or an iterable of channel names (list, tuple,
                    set, dict keys, numpy array, pandas Index or Series), to select. If
                    None and channel_type is specified, selects all channels of
                    that type. The new recording keeps the order the iterable
                    yields, so a set gives an arbitrary column order; pass a list
                    when the order matters.
            channel_type: Type of channels to select ('EMG', 'ACC', 'GYRO', etc.).
                        If specified with channels, filters the selection to only
                        channels of this type.

        Returns:
            Recording: A new Recording object containing only the selected channels

        Raises:
            ValueError: If no selection is given, a named channel does not exist,
                a name is listed more than once, or no channel matches the type
                or modality filter.

        Examples:
            # Select specific channels
            new_rec = rec.select_channels(['EMG1', 'ACC1'])

            # Select all EMG channels
            emg_only = rec.select_channels(channel_type='EMG')

            # Select specific EMG channels only, this example does not select ACC channels
            emg_subset = rec.select_channels(['EMG1', 'ACC1'], channel_type='EMG')
        """
        if self.signals is None:
            raise ValueError("No signals loaded")

        if channels is None and channel_type is None and modality is None:
            raise ValueError("Specify at least one of: channels, channel_type, or modality.")

        # If type/modality specified but no channels, select all matching channels
        if channels is None and channel_type is not None:
            channels = self.get_channels_by_type(channel_type)
            if not channels:
                raise ValueError(f"No channels found of type: {channel_type}")
        elif channels is None and modality is not None:
            channels = self.get_channels_by_modality(modality)
            if not channels:
                raise ValueError(f"No channels found of modality: {modality}")
        elif isinstance(channels, str):
            channels = [channels]

        if channels is None:
            raise ValueError("Specify at least one of: channels, channel_type, or modality.")

        # Any iterable of names is accepted (a list, tuple, dict keys, a numpy
        # array, a pandas Index or Series); materialize it once so it can be
        # counted and iterated again below.
        channels = list(channels)

        # A name listed twice would copy its column twice into the new signal
        # frame while the channel dict keeps one entry, leaving a Recording whose
        # signals and channels disagree.
        repeated = [str(ch) for ch, n in Counter(channels).items() if n > 1]
        if repeated:
            raise ValueError(f"Channels listed more than once: {repeated}")

        # Validate channels exist
        if not all(ch in self.signals.columns for ch in channels):
            missing = [ch for ch in channels if ch not in self.signals.columns]
            raise ValueError(f"Channels not found: {missing}")

        # Filter by type if specified
        if channel_type is not None:
            channels = [ch for ch in channels if self.channels[ch]["channel_type"] == channel_type]
            if not channels:
                raise ValueError(f"None of the selected channels are of type: {channel_type}")

        # Filter by modality if specified
        if modality is not None:
            canonical_modality = validate_modality(modality)
            channels = [
                ch for ch in channels if self.channels[ch].get("modality") == canonical_modality
            ]
            if not channels:
                raise ValueError(f"None of the selected channels are of modality: {modality}")

        # Create new Recording object
        new_rec = Recording()

        # Copy selected signals and channels
        new_rec.signals = self.signals[channels].copy()
        new_rec.channels = {ch: self.channels[ch].copy() for ch in channels}

        # Copy metadata
        new_rec.metadata = self.metadata.copy()

        if not inplace:
            return new_rec
        else:
            self.signals = new_rec.signals
            self.channels = new_rec.channels
            self.metadata = new_rec.metadata
            return self

    def resample(self, target_rate: float) -> "Recording":
        """Return a NEW, anti-aliased down-sampled copy of this recording.

        Low-resolution demos need a smaller, lighter recording; this rebuilds the
        uniform signal grid at ``target_rate`` using a polyphase resampler
        (``scipy.signal.resample_poly``), which applies a Kaiser-windowed sinc
        anti-alias FIR before decimation. A naive stride-decimation would fold
        energy above the new Nyquist back into the band (aliasing); resample_poly
        removes that energy first, so no aliasing occurs.

        Non-destructive: ``self`` is left untouched and a new Recording is returned,
        mirroring ``select_channels``'s copy semantics.

        Resampling factors come from the integer source/target rates:
        ``g = gcd(int(src), int(target)); up = int(target)//g; down = int(src)//g``
        and ``resample_poly(x, up, down)`` runs once, vectorized over all channels
        along ``axis=0``.

        Args:
            target_rate: Desired sampling rate in Hz. Must be <= the source rate
                (this is a DOWN-sampling helper). A target equal to the source
                returns an unchanged copy; a target above it raises ``ValueError``
                rather than silently up-sampling (up-sampling cannot recover
                detail and is out of scope for the low-res pipeline).

        Returns:
            Recording: A new Recording with the resampled signals, each channel's
                ``sample_frequency`` set to the achieved rate (source * up / down,
                which equals ``target_rate`` for integer rates), and channel/recording
                metadata and events preserved. Events are unchanged because their
                onsets/durations are in SECONDS, which stay valid under any rate
                change (only the per-sample grid shrinks, not wall-clock time).

        Raises:
            ValueError: If no signals are loaded, if channels do not share a single
                ``sample_frequency`` (biosigio stores one uniform grid; mixed-rate
                resampling is out of scope), or if ``target_rate`` exceeds the
                source rate.
        """
        from math import gcd

        from scipy.signal import resample_poly

        if self.signals is None:
            raise ValueError("No signals loaded")

        if target_rate <= 0:
            raise ValueError(f"target_rate must be positive, got {target_rate}")

        # biosigio stores all channels on one uniform-length grid; a per-channel rate
        # mix is out of scope here, matching the exporter's single-rate guard.
        distinct_rates = {info["sample_frequency"] for info in self.channels.values()}
        if len(distinct_rates) > 1:
            raise ValueError(
                "Resampling requires a single sampling rate across all channels, but "
                f"multiple were found: {sorted(distinct_rates)} Hz. biosigio stores one "
                "uniform grid; resample each rate group separately."
            )

        source_rate = float(next(iter(distinct_rates)))

        # Down-sampling only: refuse to up-sample/alias; an equal rate is a no-op
        # copy so callers can resample unconditionally without special-casing.
        if target_rate > source_rate:
            raise ValueError(
                f"target_rate {target_rate} Hz exceeds source rate {source_rate} Hz; "
                "resample() only down-samples (low-res). Up-sampling is out of scope."
            )

        new_rec = Recording()
        new_rec.channels = {ch: info.copy() for ch, info in self.channels.items()}
        new_rec.metadata = self.metadata.copy()
        # Onsets/durations are in SECONDS, so they remain valid after the grid
        # changes; copy them through unchanged.
        new_rec.events = self.events.copy() if self.events is not None else self.events

        if target_rate == source_rate:
            # No grid change: copy signals through untouched (fresh RangeIndex for
            # consistency with the resampled path).
            new_rec.signals = self.signals.copy().reset_index(drop=True)
            return new_rec

        # Rational resampling factors from the integer rates.
        src_i = int(round(source_rate))
        tgt_i = int(round(target_rate))
        g = gcd(src_i, tgt_i)
        up = tgt_i // g
        down = src_i // g

        # The achieved rate is exactly source * up / down. Store THAT, not the
        # requested float, so the metadata can never disagree with the data (a
        # non-integer or odd target snaps to the nearest achievable rational rate;
        # warn so the caller knows). This avoids silently writing e.g. 99.5 Hz
        # onto a grid that resample_poly actually produced at 100 Hz.
        actual_rate = source_rate * up / down
        if abs(actual_rate - target_rate) > 1e-9:
            logging.warning(
                "Requested resample to %g Hz; nearest achievable rational rate is "
                "%g Hz, which is what is stored on the channels.",
                target_rate,
                actual_rate,
            )

        columns = list(self.signals.columns)
        data = self.signals.to_numpy(dtype=float)
        # resample_poly over axis=0 resamples every channel column at once with the
        # shared anti-alias FIR.
        resampled = resample_poly(data, up, down, axis=0)

        new_rec.signals = pd.DataFrame(resampled, columns=columns)
        new_rec.signals.index = pd.RangeIndex(len(new_rec.signals))
        for info in new_rec.channels.values():
            info["sample_frequency"] = actual_rate

        return new_rec

    def get_channel_types(self) -> list[str]:
        """
        Get list of unique channel types in the data.

        Returns:
            List of channel types (e.g., ['EMG', 'ACC', 'GYRO'])
        """
        return list({info["channel_type"] for info in self.channels.values()})

    def get_channels_by_type(self, channel_type: str) -> list[str]:
        """
        Get list of channels of a specific type.

        Args:
            channel_type: Type of channels to get ('EMG', 'ACC', 'GYRO', etc.)

        Returns:
            List of channel names of the specified type
        """
        return [ch for ch, info in self.channels.items() if info["channel_type"] == channel_type]

    def get_modalities(self) -> list[str]:
        """
        Get the list of unique modalities present in the data.

        Returns:
            List of modalities (e.g., ['EEG', 'EMG', 'MISC']).
        """
        return list(
            {info.get("modality") for info in self.channels.values() if info.get("modality")}
        )

    def get_channels_by_modality(self, modality: str) -> list[str]:
        """
        Get the channels belonging to a given modality.

        Args:
            modality: Modality to filter by ('EEG', 'EMG', 'IEEG', 'MEG', 'BEH', 'MISC').

        Returns:
            List of channel names of the specified modality.
        """
        canonical_modality = validate_modality(modality)
        return [
            ch for ch, info in self.channels.items() if info.get("modality") == canonical_modality
        ]

    def to_edf(
        self,
        filepath: str,
        method: str = "both",
        fft_noise_range: tuple | None = None,
        svd_rank: int | None = None,
        precision_threshold: float = 0.01,
        format: Literal["auto", "edf", "bdf"] = "auto",
        bypass_analysis: bool | None = None,
        verify: bool = False,
        verify_tolerance: float = 1e-6,
        verify_channel_map: dict[str, str] | None = None,
        verify_plot: bool = False,
        events_df: pd.DataFrame | None = None,
        create_channels_tsv: bool = True,
        clip_outliers: bool | str = "auto",
        **kwargs,
    ) -> dict | None:
        """
        Export the recording to EDF/BDF format, optionally including events.

        Args:
            filepath: Path to save the EDF/BDF file
            method: Method for signal analysis ('svd', 'fft', or 'both')
                'svd': Uses Singular Value Decomposition for noise floor estimation
                'fft': Uses Fast Fourier Transform for noise floor estimation
                'both': Uses both methods and takes the minimum noise floor (default)
            fft_noise_range: Optional tuple (min_freq, max_freq) specifying frequency range for noise in FFT method
            svd_rank: Optional manual rank cutoff for signal/noise separation in SVD method
            precision_threshold: Maximum acceptable precision loss percentage (default: 0.01%)
            format: Format to use ('auto', 'edf', or 'bdf'). Default is 'auto'.
                    If 'edf' or 'bdf' is specified, that format will be used directly.
                    If 'auto', the format (EDF/16-bit or BDF/24-bit) is chosen based
                    on signal analysis to minimize precision loss while preferring EDF
                    if sufficient.
            bypass_analysis: If True, skip signal analysis step when format is explicitly
                             set to 'edf' or 'bdf'. If None (default), analysis is skipped
                             automatically when format is forced. Set to False to force
                             analysis even with a specified format. Ignored if format='auto'.
            verify: If True, reload the exported file and compare signals with the original
                    to check for data integrity loss. Results are printed. (default: False)
            verify_tolerance: Absolute tolerance used when comparing signals during verification. (default: 1e-6)
            verify_channel_map: Optional dictionary mapping original channel names (keys)
                                to reloaded channel names (values) for verification.
                                Used if `verify` is True and channel names might differ.
            verify_plot: If True and verify is True, plots a comparison of original vs reloaded signals.
            events_df: Optional DataFrame with events ('onset', 'duration', 'description').
                      If None, uses self.events. (This provides flexibility)
            create_channels_tsv: If True, create a BIDS-compliant channels.tsv file (default: True)
            clip_outliers: Singularity handling for the per-channel physical window.
                'auto' (default) keeps the full range losslessly but clips rare extreme
                outliers to a robust window only when keeping them would crater the bulk
                signal's resolution at the chosen format (with a warning); True always
                clips to the robust window; False never clips. See EDFExporter.export for
                the advanced ``outlier_sigmas`` / ``min_effective_bits`` knobs.
            **kwargs: Additional arguments for the EDF exporter

        Returns:
            Union[str, None]: If verify is True, returns a string with verification results.
                             Otherwise, returns None.

        Raises:
            ValueError: If no signals are loaded
        """
        from ..exporters.edf import EDFExporter  # Local import

        if self.signals is None:
            raise ValueError("No signals loaded")

        # --- Determine if analysis should be bypassed ---
        final_bypass_analysis = False
        if format.lower() == "auto":
            if bypass_analysis is True:
                logging.warning(
                    "bypass_analysis=True ignored because format='auto'. Analysis is required."
                )
            # Analysis is always needed for 'auto' format
            final_bypass_analysis = False
        elif format.lower() in ["edf", "bdf"]:
            if bypass_analysis is None:
                # Default behaviour: skip analysis if format is forced
                final_bypass_analysis = True
                msg = (
                    f"Format forced to '{format}'. Skipping signal analysis for faster export. "
                    "Set bypass_analysis=False to force analysis."
                )
                logging.log(logging.CRITICAL, msg)
            elif bypass_analysis is True:
                final_bypass_analysis = True
                logging.log(logging.CRITICAL, "bypass_analysis=True set. Skipping signal analysis.")
            else:  # bypass_analysis is False
                final_bypass_analysis = False
                logging.info(
                    f"Format forced to '{format}' but bypass_analysis=False. Performing signal analysis."
                )
        else:
            # Should not happen if Literal type hint works, but good practice
            logging.warning(
                f"Unknown format '{format}'. Defaulting to 'auto' behavior (analysis enabled)."
            )
            format = "auto"
            final_bypass_analysis = False

        # Determine which events DataFrame to use
        if events_df is None:
            events_to_export = self.events
        else:
            events_to_export = events_df

        # Combine parameters
        all_params: dict[str, Any] = {
            "precision_threshold": precision_threshold,
            "method": method,
            "fft_noise_range": fft_noise_range,
            "svd_rank": svd_rank,
            "format": format,
            "bypass_analysis": final_bypass_analysis,
            "events_df": events_to_export,  # Pass the events dataframe
            "create_channels_tsv": create_channels_tsv,
            "clip_outliers": clip_outliers,
            **kwargs,
        }

        EDFExporter.export(self, filepath, **all_params)

        verification_report_dict = None
        if verify:
            logging.info(f"Verification requested. Reloading exported file: {filepath}")
            try:
                # Reload the exported file
                reloaded_rec = Recording.from_file(filepath, importer="edf")

                logging.info("Comparing original signals with reloaded signals...")
                # Compare signals using the imported function
                verification_results = compare_signals(
                    self, reloaded_rec, tolerance=verify_tolerance, channel_map=verify_channel_map
                )

                # Generate and log report using the imported function
                report_verification_results(verification_results, verify_tolerance)
                verification_report_dict = verification_results

                # Plot comparison using imported function if requested
                summary = verification_results.get("channel_summary", {})
                comparison_mode = summary.get("comparison_mode", "unknown")
                compared_count = sum(1 for k in verification_results if k != "channel_summary")

                if verify_plot and compared_count > 0 and comparison_mode != "failed":
                    plot_comparison(self, reloaded_rec, channel_map=verify_channel_map)
                elif verify_plot:
                    logging.warning(
                        "Skipping verification plot: No channels were successfully compared."
                    )

            except Exception as e:
                logging.error(f"Verification failed during reload or comparison: {e}")
                verification_report_dict = {
                    "error": str(e),
                    "channel_summary": {"comparison_mode": "failed"},
                }

        return verification_report_dict

    def to_parquet(self, filepath: str) -> str:
        """Export to a self-describing biosigIO Parquet file.

        Signals are stored as a columnar table (channels = columns, time index
        preserved); channels/events/metadata travel in the file's schema metadata,
        so ``Recording.from_file`` round-trips it losslessly. Great for analytics
        (DuckDB/Polars/pandas/Spark). Requires the ``arrow`` extra (pyarrow).

        Args:
            filepath: Output ``.parquet`` path.

        Returns:
            str: The written file path.
        """
        from ..exporters.tabular import TabularExporter

        return TabularExporter.to_parquet(self, filepath)

    def to_arrow(self, filepath: str) -> str:
        """Export to a biosigIO Arrow/Feather file (fast zero-copy IPC).

        Same self-describing schema as :meth:`to_parquet`; round-trips via
        ``Recording.from_file``. Requires the ``arrow`` extra (pyarrow).

        Args:
            filepath: Output ``.feather`` / ``.arrow`` path.

        Returns:
            str: The written file path.
        """
        from ..exporters.tabular import TabularExporter

        return TabularExporter.to_arrow(self, filepath)

    def to_zarr(self, filepath: str, *, exclude_subject_info: bool = False, **kwargs) -> str:
        """Export to a sharded Zarr v3 serving store with a min/max view pyramid.

        Writes one cloud-native store that serves viewing, inference, and training
        from a single conversion: ``level 0`` of each ``(modality, rate)`` group is
        the anti-aliased, per-modality-resampled inference signal, with a min/max
        render pyramid above it (flagged not-for-inference). A derived serving copy,
        not the archival source (BIDS/EDF stay authoritative). Requires the ``zarr``
        extra (zarr v3). See :class:`~biosigio.exporters.zarr.ZarrExporter` for the
        tuning knobs (``modality_rates``, ``dtype``, level-0 chunk/shard sizing,
        ``view_chunk_columns`` for the view pyramid, ...).

        Args:
            filepath: Output store path (``.zarr`` appended if missing).
            exclude_subject_info: Remove the members named in
                :data:`~biosigio.exporters.subject_info.SUBJECT_INFO_KEYS` (subject
                identity and phenotype, operator and administrative free text,
                identifying provenance) from the store's ``recording_metadata``,
                reduce ``source_file`` and ``bti_pdf_file`` to their final path
                component, and mark the store root with ``subject_info_excluded``.
                This recording's own metadata is not changed. Default False keeps
                them, as earlier releases did.
            **kwargs: Forwarded to :meth:`ZarrExporter.export`.

        Returns:
            str: The written store path.
        """
        from ..exporters.zarr import ZarrExporter

        # The empty-signal guard lives once, in ZarrExporter.export ("No signals
        # loaded"), matching the tabular path; no duplicate guard here.
        return ZarrExporter.export(
            self, filepath, exclude_subject_info=exclude_subject_info, **kwargs
        )

    def set_metadata(self, key: str, value: Any) -> None:
        """
        Set metadata value.

        Args:
            key: Metadata key
            value: Metadata value
        """
        self.metadata[key] = value

    def get_metadata(self, key: str) -> Any:
        """
        Get metadata value.

        Args:
            key: Metadata key

        Returns:
            Value associated with the key
        """
        return self.metadata.get(key)

    def has_metadata(self, key: str) -> bool:
        """Return True if ``key`` is present in the recording metadata."""
        return key in self.metadata

    def get_n_channels(self) -> int:
        """Number of channels in the recording."""
        return len(self.channels)

    def get_n_samples(self) -> int:
        """Number of time samples per channel (0 if no signals are loaded)."""
        return 0 if self.signals is None else len(self.signals)

    def get_sampling_frequency(self) -> float:
        """Sampling frequency in Hz, when all channels share a single rate.

        Raises:
            ValueError: if no channels are loaded, or channels have differing
                sampling frequencies; for a mixed-rate recording read
                ``channels[ch]["sample_frequency"]`` per channel instead.
        """
        if not self.channels:
            raise ValueError("No channels loaded")
        rates = {info["sample_frequency"] for info in self.channels.values()}
        if len(rates) > 1:
            raise ValueError(
                "Channels have differing sampling frequencies; read "
                "channels[ch]['sample_frequency'] per channel instead."
            )
        return float(next(iter(rates)))

    def get_duration(self) -> float:
        """Total recording duration in seconds (n_samples / sampling_frequency).

        Computed from the time index spacing, so it is the full window length
        (one sample period longer than the last sample's timestamp). Returns 0.0
        when fewer than two samples are loaded (a single sample has no inferable
        sample period).
        """
        if self.signals is None or len(self.signals) < 2:
            return 0.0
        index = self.signals.index
        sample_period = float(index[1] - index[0])
        return len(index) * sample_period

    def add_channel(
        self,
        label: str,
        data: np.ndarray,
        sample_frequency: float,
        physical_dimension: str,
        channel_type: str,
        *,
        modality: str | None = None,
        prefilter: str = "n/a",
    ) -> None:
        """
        Add a new channel to the recording.

        Args:
            label: Channel label or name (as per EDF specification)
            data: Channel data
            sample_frequency: Sampling frequency in Hz (as per EDF specification)
            physical_dimension: Physical dimension/unit of measurement (as per EDF specification)
            channel_type: BIDS channel type ('EEG', 'EMG', 'ECG', 'ACC', 'SEEG', ...).
                Required; validated against the modality vocabulary. There is no
                default (a missing type must be explicit, e.g. 'OTHER'/'MISC').
            modality: Coarse modality ('EEG', 'EMG', 'IEEG', 'MEG', 'BEH', 'MISC').
                If None, it is inferred from ``channel_type``.
            prefilter: Pre-filtering applied to the channel (keyword-only).

        Raises:
            ValueError: If a channel with ``label`` already exists; channels are
                keyed by label, so adding it again would silently replace one.
                This used to overwrite the existing channel. ``set_channel``
                updates an existing channel's metadata only and cannot replace
                its samples, and Recording has no remove-channel method; to
                replace the samples, assign ``rec.signals[label] = new_data``
                (same length as the recording), or add the new data under a
                different label.
        """
        if label in self.channels:
            raise ValueError(
                f"Channel {label!r} already exists; channel labels must be unique. "
                "set_channel updates metadata only and cannot replace data; to "
                f"replace the samples assign rec.signals[{label!r}] = new_data, or "
                "add the new data under a different label"
            )
        canonical_type = validate_channel_type(channel_type)
        canonical_modality = (
            infer_modality_from_channel_type(canonical_type)
            if modality is None
            else validate_modality(modality)
        )

        if self.signals is None:
            # Create DataFrame with time index
            time = np.arange(len(data)) / sample_frequency
            self.signals = pd.DataFrame(index=time)

        self.signals[label] = data
        self.channels[label] = {
            "sample_frequency": sample_frequency,
            "physical_dimension": physical_dimension,
            "prefilter": prefilter,
            "channel_type": canonical_type,
            "modality": canonical_modality,
        }

    def set_channel(
        self,
        label: str,
        *,
        channel_type: str | None = None,
        modality: str | None = None,
        physical_dimension: str | None = None,
        prefilter: str | None = None,
    ) -> None:
        """
        Update metadata of an existing channel (the supported relabel path).

        Args:
            label: Existing channel label.
            channel_type: New BIDS channel type (validated). When given without an
                explicit ``modality``, the modality is re-derived from it.
            modality: New coarse modality (validated).
            physical_dimension: New physical unit.
            prefilter: New prefilter string.

        Raises:
            KeyError: If ``label`` is not an existing channel.
            ValueError: If ``channel_type`` or ``modality`` is not in the
                modality vocabulary.
        """
        if label not in self.channels:
            raise KeyError(f"Channel not found: {label}")
        info = self.channels[label]
        if channel_type is not None:
            info["channel_type"] = validate_channel_type(channel_type)
            if modality is None:
                info["modality"] = infer_modality_from_channel_type(info["channel_type"])
        if modality is not None:
            info["modality"] = validate_modality(modality)
        if physical_dimension is not None:
            info["physical_dimension"] = physical_dimension
        if prefilter is not None:
            info["prefilter"] = prefilter

    def add_event(self, onset: float, duration: float, description: str) -> None:
        """
        Add an event/annotation to the recording.

        Args:
            onset: Event onset time in seconds.
            duration: Event duration in seconds.
            description: Event description string.
        """
        new_event = pd.DataFrame(
            [{"onset": float(onset), "duration": float(duration), "description": description}]
        )
        # Avoid concatenating onto the empty, object-dtype events frame, which
        # would coerce the numeric columns to object. Start from the typed
        # new_event when there are no existing events.
        if self.events is None or self.events.empty:
            self.events = new_event
        else:
            self.events = pd.concat([self.events, new_event], ignore_index=True)
        # Sort events by onset time for consistency
        self.events = self.events.sort_values(by="onset").reset_index(drop=True)

__init__()

Initialize an empty recording.

Source code in biosigio/core/emg.py
def __init__(self):
    """Initialize an empty recording."""
    self.signals = None
    self.metadata = {}
    self.channels = {}
    # Initialize events as an empty DataFrame with specified columns
    self.events = pd.DataFrame(columns=["onset", "duration", "description"])

add_channel(label, data, sample_frequency, physical_dimension, channel_type, *, modality=None, prefilter='n/a')

Add a new channel to the recording.

Args: label: Channel label or name (as per EDF specification) data: Channel data sample_frequency: Sampling frequency in Hz (as per EDF specification) physical_dimension: Physical dimension/unit of measurement (as per EDF specification) channel_type: BIDS channel type ('EEG', 'EMG', 'ECG', 'ACC', 'SEEG', ...). Required; validated against the modality vocabulary. There is no default (a missing type must be explicit, e.g. 'OTHER'/'MISC'). modality: Coarse modality ('EEG', 'EMG', 'IEEG', 'MEG', 'BEH', 'MISC'). If None, it is inferred from channel_type. prefilter: Pre-filtering applied to the channel (keyword-only).

Raises: ValueError: If a channel with label already exists; channels are keyed by label, so adding it again would silently replace one. This used to overwrite the existing channel. set_channel updates an existing channel's metadata only and cannot replace its samples, and Recording has no remove-channel method; to replace the samples, assign rec.signals[label] = new_data (same length as the recording), or add the new data under a different label.

Source code in biosigio/core/emg.py
def add_channel(
    self,
    label: str,
    data: np.ndarray,
    sample_frequency: float,
    physical_dimension: str,
    channel_type: str,
    *,
    modality: str | None = None,
    prefilter: str = "n/a",
) -> None:
    """
    Add a new channel to the recording.

    Args:
        label: Channel label or name (as per EDF specification)
        data: Channel data
        sample_frequency: Sampling frequency in Hz (as per EDF specification)
        physical_dimension: Physical dimension/unit of measurement (as per EDF specification)
        channel_type: BIDS channel type ('EEG', 'EMG', 'ECG', 'ACC', 'SEEG', ...).
            Required; validated against the modality vocabulary. There is no
            default (a missing type must be explicit, e.g. 'OTHER'/'MISC').
        modality: Coarse modality ('EEG', 'EMG', 'IEEG', 'MEG', 'BEH', 'MISC').
            If None, it is inferred from ``channel_type``.
        prefilter: Pre-filtering applied to the channel (keyword-only).

    Raises:
        ValueError: If a channel with ``label`` already exists; channels are
            keyed by label, so adding it again would silently replace one.
            This used to overwrite the existing channel. ``set_channel``
            updates an existing channel's metadata only and cannot replace
            its samples, and Recording has no remove-channel method; to
            replace the samples, assign ``rec.signals[label] = new_data``
            (same length as the recording), or add the new data under a
            different label.
    """
    if label in self.channels:
        raise ValueError(
            f"Channel {label!r} already exists; channel labels must be unique. "
            "set_channel updates metadata only and cannot replace data; to "
            f"replace the samples assign rec.signals[{label!r}] = new_data, or "
            "add the new data under a different label"
        )
    canonical_type = validate_channel_type(channel_type)
    canonical_modality = (
        infer_modality_from_channel_type(canonical_type)
        if modality is None
        else validate_modality(modality)
    )

    if self.signals is None:
        # Create DataFrame with time index
        time = np.arange(len(data)) / sample_frequency
        self.signals = pd.DataFrame(index=time)

    self.signals[label] = data
    self.channels[label] = {
        "sample_frequency": sample_frequency,
        "physical_dimension": physical_dimension,
        "prefilter": prefilter,
        "channel_type": canonical_type,
        "modality": canonical_modality,
    }

add_event(onset, duration, description)

Add an event/annotation to the recording.

Args: onset: Event onset time in seconds. duration: Event duration in seconds. description: Event description string.

Source code in biosigio/core/emg.py
def add_event(self, onset: float, duration: float, description: str) -> None:
    """
    Add an event/annotation to the recording.

    Args:
        onset: Event onset time in seconds.
        duration: Event duration in seconds.
        description: Event description string.
    """
    new_event = pd.DataFrame(
        [{"onset": float(onset), "duration": float(duration), "description": description}]
    )
    # Avoid concatenating onto the empty, object-dtype events frame, which
    # would coerce the numeric columns to object. Start from the typed
    # new_event when there are no existing events.
    if self.events is None or self.events.empty:
        self.events = new_event
    else:
        self.events = pd.concat([self.events, new_event], ignore_index=True)
    # Sort events by onset time for consistency
    self.events = self.events.sort_values(by="onset").reset_index(drop=True)

from_file(filepath, importer=None, force_csv=False, bids_channels='auto', mixed_rate='error', *, allow_partial_frame=False, **kwargs) classmethod

The method to create a Recording object from file.

Args: filepath: Path to the input file importer: Name of the importer to use. Can be one of the following: - 'trigno': Delsys Trigno EMG system (CSV) - 'otb': OTB/OTB+ EMG system (OTB, OTB+) - 'eeglab': EEGLAB .set files (SET) - 'edf': EDF/EDF+/BDF/BDF+ format (EDF, BDF) - 'csv': Generic CSV (or TXT) files with columnar data - 'wfdb': Waveform Database (WFDB) - 'xdf': XDF format (multi-stream Lab Streaming Layer files) - 'meg': MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi directory (no extension, detected by content); requires the 'meg' extra) - 'brainvision': BrainVision .vhdr via MNE (requires the 'meg' extra) - 'mef3': MEF3 iEEG via MNE (.mefd directory; requires the 'mef3' extra -- mne>=1.12 plus pymef, stricter than the 'meg' extra) - 'tabular': biosigIO Parquet/Arrow/Feather (requires the 'arrow' extra) - 'neo': proprietary electrophysiology formats via python-neo (Intan, Blackrock, Spike2, Plexon, Micromed, Neuralynx, ...; requires the 'neo' extra) - 'zarr': biosigIO Zarr serving store (requires the 'zarr' extra) If None, the importer will be inferred from the file extension. Automatic import is supported for CSV/TXT files. force_csv: If True and importer is 'csv', forces using the generic CSV importer even if the file appears to match a specialized format. bids_channels: Which BIDS _channels.tsv to apply over the importer's inferred per-channel type/units. 'auto' (default) looks for the sibling sidecar next to the file; 'off' (or None) disables the lookup; a path or a pandas DataFrame is used as given, for a recording whose sidecar is not adjacent to it (a filtered copy on scratch, say). Adopting a declared unit converts the samples into it, not just the label. stream_to_zarr takes the same argument with the same meanings, so the in-memory and streaming export paths agree on a recording (issue #127). mixed_rate: Policy for an EDF/BDF file whose signals carry differing per-channel sampling rates (ignored for every other format, which is single-rate). 'error' (default) raises -- biosigIO stores one uniform grid and will not fabricate a common one silently. 'resample' upsamples the slower channels to the fastest rate (a lossy derived view; each channel keeps its native rate as original_sample_frequency). allow_partial_frame: BrainVision only (ignored for every other format). A binary data file whose size is not a whole number of frames raises CorruptFileError by default. True reads the whole frames of a MULTIPLEXED file that ends in a partial frame (and declares no positive DataPoints=), with a UserWarning naming the file and the dropped byte count; the count is kept in the metadata as brainvision_dropped_bytes. Vectorized data, a file smaller than a positive DataPoints= and a file that holds no whole frame are still refused. Keyword-only. stream_to_zarr takes the same argument. **kwargs: Additional arguments passed to the importer. For XDF files, useful kwargs include: - stream_names: List of stream names to import - stream_types: List of stream types to import (e.g., ["EMG", "EXG"]) - stream_ids: List of stream IDs to import

Returns: Recording: New Recording object with loaded data

Source code in biosigio/core/emg.py
@classmethod
def from_file(
    cls,
    filepath: str,
    importer: ImporterName | None = None,
    force_csv: bool = False,
    bids_channels: "str | os.PathLike | pd.DataFrame | None" = "auto",
    mixed_rate: str = "error",
    *,
    allow_partial_frame: bool = False,
    **kwargs,
) -> "Recording":
    """
    The method to create a Recording object from file.

    Args:
        filepath: Path to the input file
        importer: Name of the importer to use. Can be one of the following:
            - 'trigno': Delsys Trigno EMG system (CSV)
            - 'otb': OTB/OTB+ EMG system (OTB, OTB+)
            - 'eeglab': EEGLAB .set files (SET)
            - 'edf': EDF/EDF+/BDF/BDF+ format (EDF, BDF)
            - 'csv': Generic CSV (or TXT) files with columnar data
            - 'wfdb': Waveform Database (WFDB)
            - 'xdf': XDF format (multi-stream Lab Streaming Layer files)
            - 'meg': MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi
              directory (no extension, detected by content); requires the
              'meg' extra)
            - 'brainvision': BrainVision .vhdr via MNE (requires the 'meg' extra)
            - 'mef3': MEF3 iEEG via MNE (.mefd directory; requires the 'mef3'
              extra -- mne>=1.12 plus pymef, stricter than the 'meg' extra)
            - 'tabular': biosigIO Parquet/Arrow/Feather (requires the 'arrow' extra)
            - 'neo': proprietary electrophysiology formats via python-neo
              (Intan, Blackrock, Spike2, Plexon, Micromed, Neuralynx, ...;
              requires the 'neo' extra)
            - 'zarr': biosigIO Zarr serving store (requires the 'zarr' extra)
            If None, the importer will be inferred from the file extension.
            Automatic import is supported for CSV/TXT files.
        force_csv: If True and importer is 'csv', forces using the generic CSV
                  importer even if the file appears to match a specialized format.
        bids_channels: Which BIDS ``_channels.tsv`` to apply over the
                  importer's inferred per-channel type/units. 'auto'
                  (default) looks for the sibling sidecar next to the file;
                  'off' (or None) disables the lookup; a path or a pandas
                  DataFrame is used as given, for a recording whose sidecar
                  is not adjacent to it (a filtered copy on scratch, say).
                  Adopting a declared unit converts the samples into it, not
                  just the label. ``stream_to_zarr`` takes the same argument
                  with the same meanings, so the in-memory and streaming
                  export paths agree on a recording (issue #127).
        mixed_rate: Policy for an EDF/BDF file whose signals carry differing
                  per-channel sampling rates (ignored for every other format,
                  which is single-rate). 'error' (default) raises -- biosigIO
                  stores one uniform grid and will not fabricate a common one
                  silently. 'resample' upsamples the slower channels to the
                  fastest rate (a lossy derived view; each channel keeps its
                  native rate as ``original_sample_frequency``).
        allow_partial_frame: BrainVision only (ignored for every other format).
                  A binary data file whose size is not a whole number of frames
                  raises ``CorruptFileError`` by default. True reads the whole
                  frames of a MULTIPLEXED file that ends in a partial frame (and
                  declares no positive ``DataPoints=``), with a ``UserWarning``
                  naming the file and the dropped byte count; the count is kept in
                  the metadata as ``brainvision_dropped_bytes``. Vectorized data,
                  a file smaller than a positive ``DataPoints=`` and a file that
                  holds no whole frame are still refused. Keyword-only.
                  ``stream_to_zarr`` takes the same argument.
        **kwargs: Additional arguments passed to the importer.
            For XDF files, useful kwargs include:
            - stream_names: List of stream names to import
            - stream_types: List of stream types to import (e.g., ["EMG", "EXG"])
            - stream_ids: List of stream IDs to import

    Returns:
        Recording: New Recording object with loaded data
    """
    if importer is None:
        importer = cls._infer_importer(filepath)

    importers = {
        "trigno": "TrignoImporter",  # CSV with Delsys Trigno Headers
        "otb": "OTBImporter",  # OTB/OTB+ EMG system data
        "edf": "EDFImporter",  # EDF/EDF+/BDF format
        "eeglab": "EEGLABImporter",  # EEGLAB .set files
        "csv": "CSVImporter",  # Generic CSV/Text files
        "wfdb": "WFDBImporter",  # Waveform Database format
        "xdf": "XDFImporter",  # XDF multi-stream format
        "meg": "MEGImporter",  # MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi)
        "brainvision": "BrainVisionImporter",  # BrainVision via MNE (.vhdr)
        "mef3": "MEF3Importer",  # MEF3 iEEG via MNE (.mefd; requires the 'mef3' extra)
        "tabular": "TabularImporter",  # biosigIO Parquet / Arrow / Feather
        "neo": "NeoImporter",  # proprietary ephys via python-neo
        "zarr": "ZarrImporter",  # biosigIO Zarr serving store
    }

    if importer not in importers:
        raise ValueError(
            f"Unsupported importer: {importer}. "
            f"Available importers: {list(importers.keys())}\n"
            "- trigno: Delsys Trigno EMG system\n"
            "- otb: OTB/OTB+ EMG system\n"
            "- edf: EDF/EDF+/BDF format\n"
            "- eeglab: EEGLAB .set files\n"
            "- csv: Generic CSV/Text files\n"
            "- wfdb: Waveform Database\n"
            "- xdf: XDF multi-stream format\n"
            "- meg: MEG via MNE (.fif, CTF .ds, KIT .con/.sqd/.kdf, 4D/BTi directory)\n"
            "- brainvision: BrainVision via MNE (.vhdr)\n"
            "- mef3: MEF3 iEEG via MNE (.mefd directory; requires the 'mef3' extra)\n"
            "- tabular: biosigIO Parquet/Arrow/Feather (.parquet, .feather, .arrow)\n"
            "- neo: proprietary electrophysiology formats via python-neo "
            "(Intan, Blackrock, Spike2, Plexon, Micromed, Neuralynx, ...)\n"
            "- zarr: biosigIO Zarr serving store (.zarr)"
        )

    # If using CSV importer and force_csv is set, pass it as force_generic
    if importer == "csv":
        kwargs["force_generic"] = force_csv

    # mixed_rate is only meaningful for EDF/BDF, the one format whose signals may
    # carry differing per-channel sampling rates; forward it there and nowhere
    # else (so the default "error" never reaches an importer that can't use it).
    if importer == "edf":
        kwargs["mixed_rate"] = mixed_rate

    # allow_partial_frame likewise only means something to the BrainVision reader.
    if importer == "brainvision":
        kwargs["allow_partial_frame"] = allow_partial_frame

    # Import the appropriate importer class
    importer_module = __import__(
        f"biosigio.importers.{importer}", globals(), locals(), [importers[importer]]
    )
    importer_class = getattr(importer_module, importers[importer])

    # Create importer instance and load data
    rec = importer_class().load(filepath, **kwargs)

    # Record provenance: which format this recording came from. setdefault so a
    # re-imported serialization file (tabular/zarr) keeps the ORIGINAL
    # source_format restored from its metadata rather than being relabeled.
    rec.metadata.setdefault("source_format", importer)

    # In a BIDS layout, the sibling _channels.tsv is the authoritative source
    # of per-channel type/units; apply it over the importer's header/label
    # guesses unless explicitly disabled with bids_channels="off". The
    # argument is interpreted by bids.resolve_channels_tsv, shared with
    # stream_to_zarr so the two export paths cannot read it differently.
    from ..bids import apply_channels_tsv, resolve_channels_tsv

    channels_tsv = resolve_channels_tsv(filepath, bids_channels)
    if channels_tsv is not None:
        apply_channels_tsv(rec, channels_tsv)

    return rec

get_channel_types()

Get list of unique channel types in the data.

Returns: List of channel types (e.g., ['EMG', 'ACC', 'GYRO'])

Source code in biosigio/core/emg.py
def get_channel_types(self) -> list[str]:
    """
    Get list of unique channel types in the data.

    Returns:
        List of channel types (e.g., ['EMG', 'ACC', 'GYRO'])
    """
    return list({info["channel_type"] for info in self.channels.values()})

get_channels_by_modality(modality)

Get the channels belonging to a given modality.

Args: modality: Modality to filter by ('EEG', 'EMG', 'IEEG', 'MEG', 'BEH', 'MISC').

Returns: List of channel names of the specified modality.

Source code in biosigio/core/emg.py
def get_channels_by_modality(self, modality: str) -> list[str]:
    """
    Get the channels belonging to a given modality.

    Args:
        modality: Modality to filter by ('EEG', 'EMG', 'IEEG', 'MEG', 'BEH', 'MISC').

    Returns:
        List of channel names of the specified modality.
    """
    canonical_modality = validate_modality(modality)
    return [
        ch for ch, info in self.channels.items() if info.get("modality") == canonical_modality
    ]

get_channels_by_type(channel_type)

Get list of channels of a specific type.

Args: channel_type: Type of channels to get ('EMG', 'ACC', 'GYRO', etc.)

Returns: List of channel names of the specified type

Source code in biosigio/core/emg.py
def get_channels_by_type(self, channel_type: str) -> list[str]:
    """
    Get list of channels of a specific type.

    Args:
        channel_type: Type of channels to get ('EMG', 'ACC', 'GYRO', etc.)

    Returns:
        List of channel names of the specified type
    """
    return [ch for ch, info in self.channels.items() if info["channel_type"] == channel_type]

get_duration()

Total recording duration in seconds (n_samples / sampling_frequency).

Computed from the time index spacing, so it is the full window length (one sample period longer than the last sample's timestamp). Returns 0.0 when fewer than two samples are loaded (a single sample has no inferable sample period).

Source code in biosigio/core/emg.py
def get_duration(self) -> float:
    """Total recording duration in seconds (n_samples / sampling_frequency).

    Computed from the time index spacing, so it is the full window length
    (one sample period longer than the last sample's timestamp). Returns 0.0
    when fewer than two samples are loaded (a single sample has no inferable
    sample period).
    """
    if self.signals is None or len(self.signals) < 2:
        return 0.0
    index = self.signals.index
    sample_period = float(index[1] - index[0])
    return len(index) * sample_period

get_metadata(key)

Get metadata value.

Args: key: Metadata key

Returns: Value associated with the key

Source code in biosigio/core/emg.py
def get_metadata(self, key: str) -> Any:
    """
    Get metadata value.

    Args:
        key: Metadata key

    Returns:
        Value associated with the key
    """
    return self.metadata.get(key)

get_modalities()

Get the list of unique modalities present in the data.

Returns: List of modalities (e.g., ['EEG', 'EMG', 'MISC']).

Source code in biosigio/core/emg.py
def get_modalities(self) -> list[str]:
    """
    Get the list of unique modalities present in the data.

    Returns:
        List of modalities (e.g., ['EEG', 'EMG', 'MISC']).
    """
    return list(
        {info.get("modality") for info in self.channels.values() if info.get("modality")}
    )

get_n_channels()

Number of channels in the recording.

Source code in biosigio/core/emg.py
def get_n_channels(self) -> int:
    """Number of channels in the recording."""
    return len(self.channels)

get_n_samples()

Number of time samples per channel (0 if no signals are loaded).

Source code in biosigio/core/emg.py
def get_n_samples(self) -> int:
    """Number of time samples per channel (0 if no signals are loaded)."""
    return 0 if self.signals is None else len(self.signals)

get_sampling_frequency()

Sampling frequency in Hz, when all channels share a single rate.

Raises: ValueError: if no channels are loaded, or channels have differing sampling frequencies; for a mixed-rate recording read channels[ch]["sample_frequency"] per channel instead.

Source code in biosigio/core/emg.py
def get_sampling_frequency(self) -> float:
    """Sampling frequency in Hz, when all channels share a single rate.

    Raises:
        ValueError: if no channels are loaded, or channels have differing
            sampling frequencies; for a mixed-rate recording read
            ``channels[ch]["sample_frequency"]`` per channel instead.
    """
    if not self.channels:
        raise ValueError("No channels loaded")
    rates = {info["sample_frequency"] for info in self.channels.values()}
    if len(rates) > 1:
        raise ValueError(
            "Channels have differing sampling frequencies; read "
            "channels[ch]['sample_frequency'] per channel instead."
        )
    return float(next(iter(rates)))

has_metadata(key)

Return True if key is present in the recording metadata.

Source code in biosigio/core/emg.py
def has_metadata(self, key: str) -> bool:
    """Return True if ``key`` is present in the recording metadata."""
    return key in self.metadata

plot_signals(channels=None, time_range=None, offset_scale=0.8, uniform_scale=True, detrend=False, grid=True, title=None, show=True, plt_module=None)

Plot signals in a single plot with vertical offsets.

Args: channels: List of channels to plot. If None, plot all channels. time_range: Tuple of (start_time, end_time) to plot. If None, plot all data. offset_scale: Portion of allocated space each signal can use (0.0 to 1.0). uniform_scale: Whether to use the same scale for all signals. detrend: Whether to remove mean from signals before plotting. grid: Whether to show grid lines. title: Optional title for the figure. show: Whether to display the plot. plt_module: Matplotlib pyplot module to use.

Source code in biosigio/core/emg.py
def plot_signals(
    self,
    channels=None,
    time_range=None,
    offset_scale=0.8,
    uniform_scale=True,
    detrend=False,
    grid=True,
    title=None,
    show=True,
    plt_module=None,
):
    """
    Plot signals in a single plot with vertical offsets.

    Args:
        channels: List of channels to plot. If None, plot all channels.
        time_range: Tuple of (start_time, end_time) to plot. If None, plot all data.
        offset_scale: Portion of allocated space each signal can use (0.0 to 1.0).
        uniform_scale: Whether to use the same scale for all signals.
        detrend: Whether to remove mean from signals before plotting.
        grid: Whether to show grid lines.
        title: Optional title for the figure.
        show: Whether to display the plot.
        plt_module: Matplotlib pyplot module to use.
    """
    # Delegate to the static plotting function in visualization module
    static_plot_signals(
        rec_object=self,
        channels=channels,
        time_range=time_range,
        offset_scale=offset_scale,
        uniform_scale=uniform_scale,
        detrend=detrend,
        grid=grid,
        title=title,
        show=show,
        plt_module=plt_module,
    )

resample(target_rate)

Return a NEW, anti-aliased down-sampled copy of this recording.

Low-resolution demos need a smaller, lighter recording; this rebuilds the uniform signal grid at target_rate using a polyphase resampler (scipy.signal.resample_poly), which applies a Kaiser-windowed sinc anti-alias FIR before decimation. A naive stride-decimation would fold energy above the new Nyquist back into the band (aliasing); resample_poly removes that energy first, so no aliasing occurs.

Non-destructive: self is left untouched and a new Recording is returned, mirroring select_channels's copy semantics.

Resampling factors come from the integer source/target rates: g = gcd(int(src), int(target)); up = int(target)//g; down = int(src)//g and resample_poly(x, up, down) runs once, vectorized over all channels along axis=0.

Args: target_rate: Desired sampling rate in Hz. Must be <= the source rate (this is a DOWN-sampling helper). A target equal to the source returns an unchanged copy; a target above it raises ValueError rather than silently up-sampling (up-sampling cannot recover detail and is out of scope for the low-res pipeline).

Returns: Recording: A new Recording with the resampled signals, each channel's sample_frequency set to the achieved rate (source * up / down, which equals target_rate for integer rates), and channel/recording metadata and events preserved. Events are unchanged because their onsets/durations are in SECONDS, which stay valid under any rate change (only the per-sample grid shrinks, not wall-clock time).

Raises: ValueError: If no signals are loaded, if channels do not share a single sample_frequency (biosigio stores one uniform grid; mixed-rate resampling is out of scope), or if target_rate exceeds the source rate.

Source code in biosigio/core/emg.py
def resample(self, target_rate: float) -> "Recording":
    """Return a NEW, anti-aliased down-sampled copy of this recording.

    Low-resolution demos need a smaller, lighter recording; this rebuilds the
    uniform signal grid at ``target_rate`` using a polyphase resampler
    (``scipy.signal.resample_poly``), which applies a Kaiser-windowed sinc
    anti-alias FIR before decimation. A naive stride-decimation would fold
    energy above the new Nyquist back into the band (aliasing); resample_poly
    removes that energy first, so no aliasing occurs.

    Non-destructive: ``self`` is left untouched and a new Recording is returned,
    mirroring ``select_channels``'s copy semantics.

    Resampling factors come from the integer source/target rates:
    ``g = gcd(int(src), int(target)); up = int(target)//g; down = int(src)//g``
    and ``resample_poly(x, up, down)`` runs once, vectorized over all channels
    along ``axis=0``.

    Args:
        target_rate: Desired sampling rate in Hz. Must be <= the source rate
            (this is a DOWN-sampling helper). A target equal to the source
            returns an unchanged copy; a target above it raises ``ValueError``
            rather than silently up-sampling (up-sampling cannot recover
            detail and is out of scope for the low-res pipeline).

    Returns:
        Recording: A new Recording with the resampled signals, each channel's
            ``sample_frequency`` set to the achieved rate (source * up / down,
            which equals ``target_rate`` for integer rates), and channel/recording
            metadata and events preserved. Events are unchanged because their
            onsets/durations are in SECONDS, which stay valid under any rate
            change (only the per-sample grid shrinks, not wall-clock time).

    Raises:
        ValueError: If no signals are loaded, if channels do not share a single
            ``sample_frequency`` (biosigio stores one uniform grid; mixed-rate
            resampling is out of scope), or if ``target_rate`` exceeds the
            source rate.
    """
    from math import gcd

    from scipy.signal import resample_poly

    if self.signals is None:
        raise ValueError("No signals loaded")

    if target_rate <= 0:
        raise ValueError(f"target_rate must be positive, got {target_rate}")

    # biosigio stores all channels on one uniform-length grid; a per-channel rate
    # mix is out of scope here, matching the exporter's single-rate guard.
    distinct_rates = {info["sample_frequency"] for info in self.channels.values()}
    if len(distinct_rates) > 1:
        raise ValueError(
            "Resampling requires a single sampling rate across all channels, but "
            f"multiple were found: {sorted(distinct_rates)} Hz. biosigio stores one "
            "uniform grid; resample each rate group separately."
        )

    source_rate = float(next(iter(distinct_rates)))

    # Down-sampling only: refuse to up-sample/alias; an equal rate is a no-op
    # copy so callers can resample unconditionally without special-casing.
    if target_rate > source_rate:
        raise ValueError(
            f"target_rate {target_rate} Hz exceeds source rate {source_rate} Hz; "
            "resample() only down-samples (low-res). Up-sampling is out of scope."
        )

    new_rec = Recording()
    new_rec.channels = {ch: info.copy() for ch, info in self.channels.items()}
    new_rec.metadata = self.metadata.copy()
    # Onsets/durations are in SECONDS, so they remain valid after the grid
    # changes; copy them through unchanged.
    new_rec.events = self.events.copy() if self.events is not None else self.events

    if target_rate == source_rate:
        # No grid change: copy signals through untouched (fresh RangeIndex for
        # consistency with the resampled path).
        new_rec.signals = self.signals.copy().reset_index(drop=True)
        return new_rec

    # Rational resampling factors from the integer rates.
    src_i = int(round(source_rate))
    tgt_i = int(round(target_rate))
    g = gcd(src_i, tgt_i)
    up = tgt_i // g
    down = src_i // g

    # The achieved rate is exactly source * up / down. Store THAT, not the
    # requested float, so the metadata can never disagree with the data (a
    # non-integer or odd target snaps to the nearest achievable rational rate;
    # warn so the caller knows). This avoids silently writing e.g. 99.5 Hz
    # onto a grid that resample_poly actually produced at 100 Hz.
    actual_rate = source_rate * up / down
    if abs(actual_rate - target_rate) > 1e-9:
        logging.warning(
            "Requested resample to %g Hz; nearest achievable rational rate is "
            "%g Hz, which is what is stored on the channels.",
            target_rate,
            actual_rate,
        )

    columns = list(self.signals.columns)
    data = self.signals.to_numpy(dtype=float)
    # resample_poly over axis=0 resamples every channel column at once with the
    # shared anti-alias FIR.
    resampled = resample_poly(data, up, down, axis=0)

    new_rec.signals = pd.DataFrame(resampled, columns=columns)
    new_rec.signals.index = pd.RangeIndex(len(new_rec.signals))
    for info in new_rec.channels.values():
        info["sample_frequency"] = actual_rate

    return new_rec

select_channels(channels=None, channel_type=None, inplace=False, *, modality=None)

Select specific channels from the data and return a new Recording object.

Args: channels: Channel name, or an iterable of channel names (list, tuple, set, dict keys, numpy array, pandas Index or Series), to select. If None and channel_type is specified, selects all channels of that type. The new recording keeps the order the iterable yields, so a set gives an arbitrary column order; pass a list when the order matters. channel_type: Type of channels to select ('EMG', 'ACC', 'GYRO', etc.). If specified with channels, filters the selection to only channels of this type.

Returns: Recording: A new Recording object containing only the selected channels

Raises: ValueError: If no selection is given, a named channel does not exist, a name is listed more than once, or no channel matches the type or modality filter.

Examples: # Select specific channels new_rec = rec.select_channels(['EMG1', 'ACC1'])

# Select all EMG channels
emg_only = rec.select_channels(channel_type='EMG')

# Select specific EMG channels only, this example does not select ACC channels
emg_subset = rec.select_channels(['EMG1', 'ACC1'], channel_type='EMG')
Source code in biosigio/core/emg.py
def select_channels(
    self,
    channels: str | Iterable[str] | None = None,
    channel_type: str | None = None,
    inplace: bool = False,
    *,
    modality: str | None = None,
) -> "Recording":
    """
    Select specific channels from the data and return a new Recording object.

    Args:
        channels: Channel name, or an iterable of channel names (list, tuple,
                set, dict keys, numpy array, pandas Index or Series), to select. If
                None and channel_type is specified, selects all channels of
                that type. The new recording keeps the order the iterable
                yields, so a set gives an arbitrary column order; pass a list
                when the order matters.
        channel_type: Type of channels to select ('EMG', 'ACC', 'GYRO', etc.).
                    If specified with channels, filters the selection to only
                    channels of this type.

    Returns:
        Recording: A new Recording object containing only the selected channels

    Raises:
        ValueError: If no selection is given, a named channel does not exist,
            a name is listed more than once, or no channel matches the type
            or modality filter.

    Examples:
        # Select specific channels
        new_rec = rec.select_channels(['EMG1', 'ACC1'])

        # Select all EMG channels
        emg_only = rec.select_channels(channel_type='EMG')

        # Select specific EMG channels only, this example does not select ACC channels
        emg_subset = rec.select_channels(['EMG1', 'ACC1'], channel_type='EMG')
    """
    if self.signals is None:
        raise ValueError("No signals loaded")

    if channels is None and channel_type is None and modality is None:
        raise ValueError("Specify at least one of: channels, channel_type, or modality.")

    # If type/modality specified but no channels, select all matching channels
    if channels is None and channel_type is not None:
        channels = self.get_channels_by_type(channel_type)
        if not channels:
            raise ValueError(f"No channels found of type: {channel_type}")
    elif channels is None and modality is not None:
        channels = self.get_channels_by_modality(modality)
        if not channels:
            raise ValueError(f"No channels found of modality: {modality}")
    elif isinstance(channels, str):
        channels = [channels]

    if channels is None:
        raise ValueError("Specify at least one of: channels, channel_type, or modality.")

    # Any iterable of names is accepted (a list, tuple, dict keys, a numpy
    # array, a pandas Index or Series); materialize it once so it can be
    # counted and iterated again below.
    channels = list(channels)

    # A name listed twice would copy its column twice into the new signal
    # frame while the channel dict keeps one entry, leaving a Recording whose
    # signals and channels disagree.
    repeated = [str(ch) for ch, n in Counter(channels).items() if n > 1]
    if repeated:
        raise ValueError(f"Channels listed more than once: {repeated}")

    # Validate channels exist
    if not all(ch in self.signals.columns for ch in channels):
        missing = [ch for ch in channels if ch not in self.signals.columns]
        raise ValueError(f"Channels not found: {missing}")

    # Filter by type if specified
    if channel_type is not None:
        channels = [ch for ch in channels if self.channels[ch]["channel_type"] == channel_type]
        if not channels:
            raise ValueError(f"None of the selected channels are of type: {channel_type}")

    # Filter by modality if specified
    if modality is not None:
        canonical_modality = validate_modality(modality)
        channels = [
            ch for ch in channels if self.channels[ch].get("modality") == canonical_modality
        ]
        if not channels:
            raise ValueError(f"None of the selected channels are of modality: {modality}")

    # Create new Recording object
    new_rec = Recording()

    # Copy selected signals and channels
    new_rec.signals = self.signals[channels].copy()
    new_rec.channels = {ch: self.channels[ch].copy() for ch in channels}

    # Copy metadata
    new_rec.metadata = self.metadata.copy()

    if not inplace:
        return new_rec
    else:
        self.signals = new_rec.signals
        self.channels = new_rec.channels
        self.metadata = new_rec.metadata
        return self

set_channel(label, *, channel_type=None, modality=None, physical_dimension=None, prefilter=None)

Update metadata of an existing channel (the supported relabel path).

Args: label: Existing channel label. channel_type: New BIDS channel type (validated). When given without an explicit modality, the modality is re-derived from it. modality: New coarse modality (validated). physical_dimension: New physical unit. prefilter: New prefilter string.

Raises: KeyError: If label is not an existing channel. ValueError: If channel_type or modality is not in the modality vocabulary.

Source code in biosigio/core/emg.py
def set_channel(
    self,
    label: str,
    *,
    channel_type: str | None = None,
    modality: str | None = None,
    physical_dimension: str | None = None,
    prefilter: str | None = None,
) -> None:
    """
    Update metadata of an existing channel (the supported relabel path).

    Args:
        label: Existing channel label.
        channel_type: New BIDS channel type (validated). When given without an
            explicit ``modality``, the modality is re-derived from it.
        modality: New coarse modality (validated).
        physical_dimension: New physical unit.
        prefilter: New prefilter string.

    Raises:
        KeyError: If ``label`` is not an existing channel.
        ValueError: If ``channel_type`` or ``modality`` is not in the
            modality vocabulary.
    """
    if label not in self.channels:
        raise KeyError(f"Channel not found: {label}")
    info = self.channels[label]
    if channel_type is not None:
        info["channel_type"] = validate_channel_type(channel_type)
        if modality is None:
            info["modality"] = infer_modality_from_channel_type(info["channel_type"])
    if modality is not None:
        info["modality"] = validate_modality(modality)
    if physical_dimension is not None:
        info["physical_dimension"] = physical_dimension
    if prefilter is not None:
        info["prefilter"] = prefilter

set_metadata(key, value)

Set metadata value.

Args: key: Metadata key value: Metadata value

Source code in biosigio/core/emg.py
def set_metadata(self, key: str, value: Any) -> None:
    """
    Set metadata value.

    Args:
        key: Metadata key
        value: Metadata value
    """
    self.metadata[key] = value

to_arrow(filepath)

Export to a biosigIO Arrow/Feather file (fast zero-copy IPC).

Same self-describing schema as :meth:to_parquet; round-trips via Recording.from_file. Requires the arrow extra (pyarrow).

Args: filepath: Output .feather / .arrow path.

Returns: str: The written file path.

Source code in biosigio/core/emg.py
def to_arrow(self, filepath: str) -> str:
    """Export to a biosigIO Arrow/Feather file (fast zero-copy IPC).

    Same self-describing schema as :meth:`to_parquet`; round-trips via
    ``Recording.from_file``. Requires the ``arrow`` extra (pyarrow).

    Args:
        filepath: Output ``.feather`` / ``.arrow`` path.

    Returns:
        str: The written file path.
    """
    from ..exporters.tabular import TabularExporter

    return TabularExporter.to_arrow(self, filepath)

to_edf(filepath, method='both', fft_noise_range=None, svd_rank=None, precision_threshold=0.01, format='auto', bypass_analysis=None, verify=False, verify_tolerance=1e-06, verify_channel_map=None, verify_plot=False, events_df=None, create_channels_tsv=True, clip_outliers='auto', **kwargs)

Export the recording to EDF/BDF format, optionally including events.

Args: filepath: Path to save the EDF/BDF file method: Method for signal analysis ('svd', 'fft', or 'both') 'svd': Uses Singular Value Decomposition for noise floor estimation 'fft': Uses Fast Fourier Transform for noise floor estimation 'both': Uses both methods and takes the minimum noise floor (default) fft_noise_range: Optional tuple (min_freq, max_freq) specifying frequency range for noise in FFT method svd_rank: Optional manual rank cutoff for signal/noise separation in SVD method precision_threshold: Maximum acceptable precision loss percentage (default: 0.01%) format: Format to use ('auto', 'edf', or 'bdf'). Default is 'auto'. If 'edf' or 'bdf' is specified, that format will be used directly. If 'auto', the format (EDF/16-bit or BDF/24-bit) is chosen based on signal analysis to minimize precision loss while preferring EDF if sufficient. bypass_analysis: If True, skip signal analysis step when format is explicitly set to 'edf' or 'bdf'. If None (default), analysis is skipped automatically when format is forced. Set to False to force analysis even with a specified format. Ignored if format='auto'. verify: If True, reload the exported file and compare signals with the original to check for data integrity loss. Results are printed. (default: False) verify_tolerance: Absolute tolerance used when comparing signals during verification. (default: 1e-6) verify_channel_map: Optional dictionary mapping original channel names (keys) to reloaded channel names (values) for verification. Used if verify is True and channel names might differ. verify_plot: If True and verify is True, plots a comparison of original vs reloaded signals. events_df: Optional DataFrame with events ('onset', 'duration', 'description'). If None, uses self.events. (This provides flexibility) create_channels_tsv: If True, create a BIDS-compliant channels.tsv file (default: True) clip_outliers: Singularity handling for the per-channel physical window. 'auto' (default) keeps the full range losslessly but clips rare extreme outliers to a robust window only when keeping them would crater the bulk signal's resolution at the chosen format (with a warning); True always clips to the robust window; False never clips. See EDFExporter.export for the advanced outlier_sigmas / min_effective_bits knobs. **kwargs: Additional arguments for the EDF exporter

Returns: Union[str, None]: If verify is True, returns a string with verification results. Otherwise, returns None.

Raises: ValueError: If no signals are loaded

Source code in biosigio/core/emg.py
def to_edf(
    self,
    filepath: str,
    method: str = "both",
    fft_noise_range: tuple | None = None,
    svd_rank: int | None = None,
    precision_threshold: float = 0.01,
    format: Literal["auto", "edf", "bdf"] = "auto",
    bypass_analysis: bool | None = None,
    verify: bool = False,
    verify_tolerance: float = 1e-6,
    verify_channel_map: dict[str, str] | None = None,
    verify_plot: bool = False,
    events_df: pd.DataFrame | None = None,
    create_channels_tsv: bool = True,
    clip_outliers: bool | str = "auto",
    **kwargs,
) -> dict | None:
    """
    Export the recording to EDF/BDF format, optionally including events.

    Args:
        filepath: Path to save the EDF/BDF file
        method: Method for signal analysis ('svd', 'fft', or 'both')
            'svd': Uses Singular Value Decomposition for noise floor estimation
            'fft': Uses Fast Fourier Transform for noise floor estimation
            'both': Uses both methods and takes the minimum noise floor (default)
        fft_noise_range: Optional tuple (min_freq, max_freq) specifying frequency range for noise in FFT method
        svd_rank: Optional manual rank cutoff for signal/noise separation in SVD method
        precision_threshold: Maximum acceptable precision loss percentage (default: 0.01%)
        format: Format to use ('auto', 'edf', or 'bdf'). Default is 'auto'.
                If 'edf' or 'bdf' is specified, that format will be used directly.
                If 'auto', the format (EDF/16-bit or BDF/24-bit) is chosen based
                on signal analysis to minimize precision loss while preferring EDF
                if sufficient.
        bypass_analysis: If True, skip signal analysis step when format is explicitly
                         set to 'edf' or 'bdf'. If None (default), analysis is skipped
                         automatically when format is forced. Set to False to force
                         analysis even with a specified format. Ignored if format='auto'.
        verify: If True, reload the exported file and compare signals with the original
                to check for data integrity loss. Results are printed. (default: False)
        verify_tolerance: Absolute tolerance used when comparing signals during verification. (default: 1e-6)
        verify_channel_map: Optional dictionary mapping original channel names (keys)
                            to reloaded channel names (values) for verification.
                            Used if `verify` is True and channel names might differ.
        verify_plot: If True and verify is True, plots a comparison of original vs reloaded signals.
        events_df: Optional DataFrame with events ('onset', 'duration', 'description').
                  If None, uses self.events. (This provides flexibility)
        create_channels_tsv: If True, create a BIDS-compliant channels.tsv file (default: True)
        clip_outliers: Singularity handling for the per-channel physical window.
            'auto' (default) keeps the full range losslessly but clips rare extreme
            outliers to a robust window only when keeping them would crater the bulk
            signal's resolution at the chosen format (with a warning); True always
            clips to the robust window; False never clips. See EDFExporter.export for
            the advanced ``outlier_sigmas`` / ``min_effective_bits`` knobs.
        **kwargs: Additional arguments for the EDF exporter

    Returns:
        Union[str, None]: If verify is True, returns a string with verification results.
                         Otherwise, returns None.

    Raises:
        ValueError: If no signals are loaded
    """
    from ..exporters.edf import EDFExporter  # Local import

    if self.signals is None:
        raise ValueError("No signals loaded")

    # --- Determine if analysis should be bypassed ---
    final_bypass_analysis = False
    if format.lower() == "auto":
        if bypass_analysis is True:
            logging.warning(
                "bypass_analysis=True ignored because format='auto'. Analysis is required."
            )
        # Analysis is always needed for 'auto' format
        final_bypass_analysis = False
    elif format.lower() in ["edf", "bdf"]:
        if bypass_analysis is None:
            # Default behaviour: skip analysis if format is forced
            final_bypass_analysis = True
            msg = (
                f"Format forced to '{format}'. Skipping signal analysis for faster export. "
                "Set bypass_analysis=False to force analysis."
            )
            logging.log(logging.CRITICAL, msg)
        elif bypass_analysis is True:
            final_bypass_analysis = True
            logging.log(logging.CRITICAL, "bypass_analysis=True set. Skipping signal analysis.")
        else:  # bypass_analysis is False
            final_bypass_analysis = False
            logging.info(
                f"Format forced to '{format}' but bypass_analysis=False. Performing signal analysis."
            )
    else:
        # Should not happen if Literal type hint works, but good practice
        logging.warning(
            f"Unknown format '{format}'. Defaulting to 'auto' behavior (analysis enabled)."
        )
        format = "auto"
        final_bypass_analysis = False

    # Determine which events DataFrame to use
    if events_df is None:
        events_to_export = self.events
    else:
        events_to_export = events_df

    # Combine parameters
    all_params: dict[str, Any] = {
        "precision_threshold": precision_threshold,
        "method": method,
        "fft_noise_range": fft_noise_range,
        "svd_rank": svd_rank,
        "format": format,
        "bypass_analysis": final_bypass_analysis,
        "events_df": events_to_export,  # Pass the events dataframe
        "create_channels_tsv": create_channels_tsv,
        "clip_outliers": clip_outliers,
        **kwargs,
    }

    EDFExporter.export(self, filepath, **all_params)

    verification_report_dict = None
    if verify:
        logging.info(f"Verification requested. Reloading exported file: {filepath}")
        try:
            # Reload the exported file
            reloaded_rec = Recording.from_file(filepath, importer="edf")

            logging.info("Comparing original signals with reloaded signals...")
            # Compare signals using the imported function
            verification_results = compare_signals(
                self, reloaded_rec, tolerance=verify_tolerance, channel_map=verify_channel_map
            )

            # Generate and log report using the imported function
            report_verification_results(verification_results, verify_tolerance)
            verification_report_dict = verification_results

            # Plot comparison using imported function if requested
            summary = verification_results.get("channel_summary", {})
            comparison_mode = summary.get("comparison_mode", "unknown")
            compared_count = sum(1 for k in verification_results if k != "channel_summary")

            if verify_plot and compared_count > 0 and comparison_mode != "failed":
                plot_comparison(self, reloaded_rec, channel_map=verify_channel_map)
            elif verify_plot:
                logging.warning(
                    "Skipping verification plot: No channels were successfully compared."
                )

        except Exception as e:
            logging.error(f"Verification failed during reload or comparison: {e}")
            verification_report_dict = {
                "error": str(e),
                "channel_summary": {"comparison_mode": "failed"},
            }

    return verification_report_dict

to_parquet(filepath)

Export to a self-describing biosigIO Parquet file.

Signals are stored as a columnar table (channels = columns, time index preserved); channels/events/metadata travel in the file's schema metadata, so Recording.from_file round-trips it losslessly. Great for analytics (DuckDB/Polars/pandas/Spark). Requires the arrow extra (pyarrow).

Args: filepath: Output .parquet path.

Returns: str: The written file path.

Source code in biosigio/core/emg.py
def to_parquet(self, filepath: str) -> str:
    """Export to a self-describing biosigIO Parquet file.

    Signals are stored as a columnar table (channels = columns, time index
    preserved); channels/events/metadata travel in the file's schema metadata,
    so ``Recording.from_file`` round-trips it losslessly. Great for analytics
    (DuckDB/Polars/pandas/Spark). Requires the ``arrow`` extra (pyarrow).

    Args:
        filepath: Output ``.parquet`` path.

    Returns:
        str: The written file path.
    """
    from ..exporters.tabular import TabularExporter

    return TabularExporter.to_parquet(self, filepath)

to_zarr(filepath, *, exclude_subject_info=False, **kwargs)

Export to a sharded Zarr v3 serving store with a min/max view pyramid.

Writes one cloud-native store that serves viewing, inference, and training from a single conversion: level 0 of each (modality, rate) group is the anti-aliased, per-modality-resampled inference signal, with a min/max render pyramid above it (flagged not-for-inference). A derived serving copy, not the archival source (BIDS/EDF stay authoritative). Requires the zarr extra (zarr v3). See :class:~biosigio.exporters.zarr.ZarrExporter for the tuning knobs (modality_rates, dtype, level-0 chunk/shard sizing, view_chunk_columns for the view pyramid, ...).

Args: filepath: Output store path (.zarr appended if missing). exclude_subject_info: Remove the members named in :data:~biosigio.exporters.subject_info.SUBJECT_INFO_KEYS (subject identity and phenotype, operator and administrative free text, identifying provenance) from the store's recording_metadata, reduce source_file and bti_pdf_file to their final path component, and mark the store root with subject_info_excluded. This recording's own metadata is not changed. Default False keeps them, as earlier releases did. **kwargs: Forwarded to :meth:ZarrExporter.export.

Returns: str: The written store path.

Source code in biosigio/core/emg.py
def to_zarr(self, filepath: str, *, exclude_subject_info: bool = False, **kwargs) -> str:
    """Export to a sharded Zarr v3 serving store with a min/max view pyramid.

    Writes one cloud-native store that serves viewing, inference, and training
    from a single conversion: ``level 0`` of each ``(modality, rate)`` group is
    the anti-aliased, per-modality-resampled inference signal, with a min/max
    render pyramid above it (flagged not-for-inference). A derived serving copy,
    not the archival source (BIDS/EDF stay authoritative). Requires the ``zarr``
    extra (zarr v3). See :class:`~biosigio.exporters.zarr.ZarrExporter` for the
    tuning knobs (``modality_rates``, ``dtype``, level-0 chunk/shard sizing,
    ``view_chunk_columns`` for the view pyramid, ...).

    Args:
        filepath: Output store path (``.zarr`` appended if missing).
        exclude_subject_info: Remove the members named in
            :data:`~biosigio.exporters.subject_info.SUBJECT_INFO_KEYS` (subject
            identity and phenotype, operator and administrative free text,
            identifying provenance) from the store's ``recording_metadata``,
            reduce ``source_file`` and ``bti_pdf_file`` to their final path
            component, and mark the store root with ``subject_info_excluded``.
            This recording's own metadata is not changed. Default False keeps
            them, as earlier releases did.
        **kwargs: Forwarded to :meth:`ZarrExporter.export`.

    Returns:
        str: The written store path.
    """
    from ..exporters.zarr import ZarrExporter

    # The empty-signal guard lives once, in ZarrExporter.export ("No signals
    # loaded"), matching the tabular path; no duplicate guard here.
    return ZarrExporter.export(
        self, filepath, exclude_subject_info=exclude_subject_info, **kwargs
    )

_resample_to_length(data, n_out)

Polyphase-resample a 1-D channel to exactly n_out samples.

Used only by the mixed-rate resample path to lift a slower channel onto the fastest channel's grid. The integer ratio n_out/len(data) drives a Kaiser-windowed resample_poly (the same anti-alias resampler the Zarr exporter uses), then the result is trimmed/edge-padded to the exact length so every channel stays length-aligned on the shared grid.

Source code in biosigio/importers/edf.py
def _resample_to_length(data: np.ndarray, n_out: int) -> np.ndarray:
    """Polyphase-resample a 1-D channel to exactly ``n_out`` samples.

    Used only by the mixed-rate ``resample`` path to lift a slower channel onto the
    fastest channel's grid. The integer ratio ``n_out/len(data)`` drives a
    Kaiser-windowed ``resample_poly`` (the same anti-alias resampler the Zarr
    exporter uses), then the result is trimmed/edge-padded to the exact length so
    every channel stays length-aligned on the shared grid.
    """
    from math import gcd

    from scipy.signal import resample_poly

    x = np.asarray(data, dtype=float)
    n_in = len(x)
    if n_in == 0 or n_in == n_out:
        return x
    g = gcd(n_out, n_in)
    # padtype="line" extends each edge with a ramp matching the signal's end slope,
    # not zeros. Slow physiological channels (SpO2, respiration) sit on a large DC
    # offset; default zero-padding makes a step at the boundary and the polyphase FIR
    # rings (a 95-unit SpO2 baseline overshot to ~109). "line" removes that transient.
    y = resample_poly(x, n_out // g, n_in // g, padtype="line")
    if len(y) > n_out:
        y = y[:n_out]
    elif len(y) < n_out:
        y = np.pad(y, (0, n_out - len(y)), mode="edge")
    return y

classify_pyedflib_error(exc)

Classify a pyedflib.EdfReader open failure into a recoverable reason.

Returns one of :data:DEGENERATE_PHYSICAL_RANGE, :data:MALFORMED_NUMERIC_FIELD, :data:DISCONTINUOUS_DATARECORDS, or None when the failure is not one of the three known-recoverable conditions (e.g. a genuine Filesize truncation, or a free-text/label field pyedflib also happens to validate).

Source code in biosigio/importers/_edf_tolerant.py
def classify_pyedflib_error(exc: Exception) -> str | None:
    """Classify a ``pyedflib.EdfReader`` open failure into a recoverable reason.

    Returns one of :data:`DEGENERATE_PHYSICAL_RANGE`, :data:`MALFORMED_NUMERIC_FIELD`,
    :data:`DISCONTINUOUS_DATARECORDS`, or ``None`` when the failure is not one of
    the three known-recoverable conditions (e.g. a genuine ``Filesize`` truncation,
    or a free-text/label field pyedflib also happens to validate).
    """
    low = str(exc).lower()
    if "discontinuous" in low:
        return DISCONTINUOUS_DATARECORDS
    if "physical maximum" in low or "physical minimum" in low:
        return DEGENERATE_PHYSICAL_RANGE
    if any(f"compliant ({name})" in low for name in _NUMERIC_FIELD_NAMES):
        return MALFORMED_NUMERIC_FIELD
    return None

classify_read_error(exc, filepath='')

Re-raises exc as-is when it is a host condition (see :func:is_host_condition); otherwise maps a low-level read failure to a typed biosigIO error with a stable code.

Importers call this in their except and raise ... from exc the result, so the why is decided once, where the format context lives. An exception that is already a :class:BiosigIOError is returned unchanged.

The host-condition re-raise lives here, not at each call site, so no importer can forget it: every path that would type an exception goes through this function, and an exception it re-raises keeps its own type, traceback and chain. Resource exhaustion is additionally guarded by the importers before calling this; host I/O errors (EACCES, EIO, ENOSPC, ...) rely on this check alone.

The matching is deliberately reader-agnostic (MNE and pyedflib phrase the same condition differently); unmatched failures fall through to :class:FileReadError so a caller always gets a typed error, never a bare Exception.

Source code in biosigio/exceptions.py
def classify_read_error(exc: Exception, filepath: str = "") -> BiosigIOError | NoReturn:
    """Re-raises ``exc`` as-is when it is a host condition (see
    :func:`is_host_condition`); otherwise maps a low-level read failure to a
    typed biosigIO error with a stable code.

    Importers call this in their ``except`` and ``raise ... from exc`` the result,
    so the *why* is decided once, where the format context lives. An exception
    that is already a :class:`BiosigIOError` is returned unchanged.

    The host-condition re-raise lives here, not at each call site, so no importer
    can forget it: every path that would type an exception goes through this
    function, and an exception it re-raises keeps its own type, traceback and
    chain. Resource exhaustion is additionally guarded by the importers *before*
    calling this; host I/O errors (``EACCES``, ``EIO``, ``ENOSPC``, ...) rely on
    this check alone.

    The matching is deliberately reader-agnostic (MNE and pyedflib phrase the same
    condition differently); unmatched failures fall through to :class:`FileReadError`
    so a caller always gets a typed error, never a bare ``Exception``.
    """
    if isinstance(exc, BiosigIOError):
        return exc
    if is_host_condition(exc):
        raise exc
    msg = str(exc)
    low = msg.lower()
    where = f" ({filepath})" if filepath else ""

    # Evoked / epoched / averaged derivatives -> no continuous raw time series.
    # MNE: "No raw data in <f>", "... is not a raw file", read_raw on an -ave/-epo.
    if (
        "no raw data" in low
        or "is not a raw" in low
        or "does not contain raw" in low
        or "this is not a raw" in low
    ):
        return NotContinuousRecordingError(f"No continuous raw recording{where}: {msg}")

    # Truncated / not format-compliant / incomplete set.
    # pyedflib: "... not EDF(+) or BDF(+) compliant (Filesize)"; MNE CTF/FIF:
    # incomplete .meg4; split chain: "... split-02 ... does not exist".
    if (
        "filesize" in low
        or "not edf" in low
        or "not bdf" in low
        or "compliant" in low
        or "truncate" in low  # matches "truncated" too
        or "corrupt" in low
        or ("split" in low and "does not exist" in low)
        # CTF .meg4 chopped mid-trial (read_raw_ctf): the data no longer divides
        # into whole trials -- the on004398 truncation signature.
        or "even multiple of the trial" in low
        or "not an even multiple" in low
    ):
        return CorruptFileError(f"Truncated, incomplete, or corrupt file{where}: {msg}")

    # Data that ends early. These are numpy's own messages, matched whichever
    # reader raised them, not only the FIF reader. MNE's FIF reader raises the
    # first when a tag is cut mid-sample (the buffer is no longer a whole number
    # of elements) and the second when a data buffer is cut at a sample boundary
    # (it holds fewer samples than its header declares). The message names the
    # file, not the directory it sits in.
    if (
        "buffer size must be a multiple of element size" in low
        or "cannot reshape array of size" in low
    ):
        named = f" ({_file_name(filepath)})" if filepath else ""
        return CorruptFileError(f"Truncated, incomplete, or corrupt file{named}: {msg}")

    # Recognized format, no specific cause -> generic (still typed) read error.
    return FileReadError(f"Could not read recording{where}: {msg}")

is_resource_exhaustion(exc)

Re-raises for resource exhaustion; used by classify_read_error (below) and by importers directly, before it, as their first check.

True when exc -- or something it masks -- reflects the host running out of memory, threads, or file descriptors, not a problem with the file being read.

Resource exhaustion is never a property of the file: a MemoryError (or numpy's _ArrayMemoryError, a MemoryError subclass) raised mid-read typically means the host was saturated (e.g. many parallel conversions), not that the recording is corrupt. Importers must let it -- and the thread/allocation/fd-exhaustion OSError/RuntimeError variants below -- propagate unchanged instead of reclassifying it as a permanent read failure, so a caller (e.g. NEMAR's converter) can retry instead of recording a deterministic failure. See :func:classify_read_error.

Resource exhaustion can also be MASKED by cleanup: if a MemoryError is propagating and a finally/context-manager __exit__/close() during unwinding raises its OWN exception, that second exception -- not the MemoryError -- is what a caller's except actually binds, with the MemoryError attached as __context__ (implicit chaining) or __cause__ (an explicit raise ... from). So this walks the chain -- the exception itself, then __cause__ or __context__, up to :data:_MAX_CHAIN_DEPTH links -- rather than only checking the outermost exception.

Source code in biosigio/exceptions.py
def is_resource_exhaustion(exc: BaseException) -> bool:
    """Re-raises for resource exhaustion; used by ``classify_read_error`` (below)
    and by importers directly, before it, as their first check.

    True when ``exc`` -- or something it masks -- reflects the host running out
    of memory, threads, or file descriptors, not a problem with the file being
    read.

    Resource exhaustion is never a property of the file: a ``MemoryError`` (or
    numpy's ``_ArrayMemoryError``, a ``MemoryError`` subclass) raised mid-read
    typically means the host was saturated (e.g. many parallel conversions),
    not that the recording is corrupt. Importers must let it -- and the
    thread/allocation/fd-exhaustion ``OSError``/``RuntimeError`` variants below
    -- propagate unchanged instead of reclassifying it as a permanent read
    failure, so a caller (e.g. NEMAR's converter) can retry instead of
    recording a deterministic failure. See :func:`classify_read_error`.

    Resource exhaustion can also be MASKED by cleanup: if a ``MemoryError`` is
    propagating and a ``finally``/context-manager ``__exit__``/``close()``
    during unwinding raises its OWN exception, that second exception -- not the
    ``MemoryError`` -- is what a caller's ``except`` actually binds, with the
    ``MemoryError`` attached as ``__context__`` (implicit chaining) or
    ``__cause__`` (an explicit ``raise ... from``). So this walks the chain --
    the exception itself, then ``__cause__`` or ``__context__``, up to
    :data:`_MAX_CHAIN_DEPTH` links -- rather than only checking the outermost
    exception.
    """
    seen: BaseException | None = exc
    for _ in range(_MAX_CHAIN_DEPTH):
        if seen is None:
            return False
        if isinstance(seen, MemoryError):
            return True
        if isinstance(seen, (OSError, RuntimeError)):
            if getattr(seen, "errno", None) in _RESOURCE_EXHAUSTION_ERRNOS:
                return True
            low = str(seen).lower()
            if any(s in low for s in _THREAD_OR_RESOURCE_EXHAUSTION_SUBSTRINGS):
                return True
        seen = seen.__cause__ or seen.__context__
    return False

probe_timekeeping_onset(filepath, exc)

Whether a late first time-keeping onset is the ONLY reason pyedflib refused filepath.

Called with the exception pyedflib.EdfReader(filepath) raised, after :func:classify_pyedflib_error found no MNE-recoverable cause. Returns None unless every step holds, and the caller then raises as it always did:

  1. the message is EDFlib's generic "(it contains format errors)";
  2. the header's reserved field starts with EDF+C or BDF+C (case-sensitive);
  3. the file opens with annotations switched off, which still checks the header and the file size, so the refusal came from the annotation walk;
  4. record 0's first TAL is a time-keeping onset of 1 s or more, and the header's start plus that onset is a date datetime can represent;
  5. a TAL-only copy, its onsets brought back by whole seconds, opens in pyedflib's default mode, so EDFlib has checked every TAL and the continuity.

The caller then opens filepath with annotations_mode=pyedflib.DO_NOT_READ_ANNOTATIONS and reads the samples with pyedflib exactly as for any compliant file; the events are :attr:TimekeepingOnset.annotations. No MNE is involved.

Only the file's own bytes are answered with None: a header that is not one, an onset int cannot parse or a float cannot hold, a first record whose date datetime cannot represent, EDFlib refusing the copy. Every OSError raised while reading the file or creating, writing or reading back the scratch copy propagates unchanged, whatever its errno (a missing or read-only temporary directory is ENOENT or EACCES): it says something about this host, and a caller must not record it as a permanent failure of a valid file.

Source code in biosigio/importers/_edf_tolerant.py
def probe_timekeeping_onset(filepath: str, exc: Exception) -> TimekeepingOnset | None:
    """Whether a late first time-keeping onset is the ONLY reason pyedflib refused ``filepath``.

    Called with the exception ``pyedflib.EdfReader(filepath)`` raised, after
    :func:`classify_pyedflib_error` found no MNE-recoverable cause. Returns ``None``
    unless every step holds, and the caller then raises as it always did:

    1. the message is EDFlib's generic ``"(it contains format errors)"``;
    2. the header's reserved field starts with ``EDF+C`` or ``BDF+C`` (case-sensitive);
    3. the file opens with annotations switched off, which still checks the header
       and the file size, so the refusal came from the annotation walk;
    4. record 0's first TAL is a time-keeping onset of 1 s or more, and the header's
       start plus that onset is a date ``datetime`` can represent;
    5. a TAL-only copy, its onsets brought back by whole seconds, opens in
       pyedflib's default mode, so EDFlib has checked every TAL and the continuity.

    The caller then opens ``filepath`` with
    ``annotations_mode=pyedflib.DO_NOT_READ_ANNOTATIONS`` and reads the samples
    with pyedflib exactly as for any compliant file; the events are
    :attr:`TimekeepingOnset.annotations`. No MNE is involved.

    Only the file's own bytes are answered with ``None``: a header that is not one,
    an onset ``int`` cannot parse or a float cannot hold, a first record whose date
    ``datetime`` cannot represent, EDFlib refusing the copy. Every ``OSError`` raised
    while reading the file or creating, writing or reading back the scratch copy
    propagates unchanged, whatever its ``errno`` (a missing or read-only temporary
    directory is ``ENOENT`` or ``EACCES``): it says something about this host, and
    a caller must not record it as a permanent failure of a valid file.
    """
    if not str(exc).rstrip().endswith(_GENERIC_FORMAT_ERROR):
        return None
    try:
        return _timekeeping_onset(filepath)
    except (ValueError, ArithmeticError):
        return None

raise_host_open_error(filepath, reader_exc)

Raise the OS's own error when the host, not the file, stopped pyedflib opening it.

pyedflib reports every open() the operating system refuses on an existing file (EACCES, EIO, a stale network handle, ...) as OSError(123, "... was found but can't be accessed ..."), dropping the real errno, so that failure could not be told apart from a problem with the file. Re-opening the file here recovers the real OSError; when it is a host condition (see :func:~biosigio.exceptions.is_host_condition) it is raised, chained from reader_exc, and a caller then propagates it unchanged instead of typing it. Returns normally when the file opens, or fails for another reason.

Source code in biosigio/importers/_edf_tolerant.py
def raise_host_open_error(filepath: str, reader_exc: Exception) -> None:
    """Raise the OS's own error when the host, not the file, stopped pyedflib opening it.

    pyedflib reports every ``open()`` the operating system refuses on an existing
    file (``EACCES``, ``EIO``, a stale network handle, ...) as ``OSError(123,
    "... was found but can't be accessed ...")``, dropping the real ``errno``, so
    that failure could not be told apart from a problem with the file. Re-opening
    the file here recovers the real ``OSError``; when it is a host condition (see
    :func:`~biosigio.exceptions.is_host_condition`) it is raised, chained from
    ``reader_exc``, and a caller then propagates it unchanged instead of typing
    it. Returns normally when the file opens, or fails for another reason.
    """
    from ..exceptions import is_host_condition

    try:
        with open(filepath, "rb") as fh:
            fh.read(1)
    except OSError as os_err:
        if is_host_condition(os_err):
            raise os_err from reader_exc

read_edf_tolerant(filepath, reason)

Recover an EDF/BDF file pyedflib refuses to open, in pyedflib-equivalent units.

reason is informational (one of the module-level constants); every condition is handled the same way here (read via MNE, rescale, zero out any degenerate channel), since a real file can combine more than one of them.

Opens with stim_channel=False -- see the module docstring -- so a channel MNE would otherwise auto-detect as a trigger/status channel (e.g. one literally named "Status") is calibrated the same way as any other channel instead of being given MNE's unrelated, non-calibrated trigger-code treatment, which would otherwise silently disagree with a normal pyedflib read of that one channel (issue #109's own probe file has exactly this shape: a degenerate reference channel AND a "Status" channel in the same recording).

An EDF+D/BDF+D file is checked first (:func:verify_records_contiguous): one with a gap raises :class:~biosigio.exceptions.DiscontinuousRecordingError, one whose records are contiguous is read and flagged verified_contiguous.

Raises ImportError if MNE (the meg extra) is not installed, and OSError/FileReadError for anything that turns out not to be recoverable after all: a truncation the safety net catches, a per-channel unit gain that disagrees with what biosigIO independently expects (see :func:_channel_gains), or a channel MNE read that cannot be paired back up with its header row.

Channels are paired with header rows by POSITION: MNE lists the header's signals in on-disk order minus the EDF+/BDF+ annotations channel, so the n-th name in raw.ch_names is the n-th non-annotation header row. Each pairing is still checked by name, so a reader that reorders or drops a channel fails loud rather than attaching one row's scaling to another row's data. The check accepts MNE's own renaming of a repeated label: two header rows both labelled "EEG" come back from MNE as "EEG-0" and "EEG-1". The labels returned are biosigIO's (see :func:~biosigio.importers._labels.unique_channel_labels), not MNE's, so a recovered read names its channels exactly as a normal read would.

Source code in biosigio/importers/_edf_tolerant.py
def read_edf_tolerant(filepath: str, reason: str) -> EdfFallbackRecording:
    """Recover an EDF/BDF file pyedflib refuses to open, in pyedflib-equivalent units.

    ``reason`` is informational (one of the module-level constants); every
    condition is handled the same way here (read via MNE, rescale, zero out any
    degenerate channel), since a real file can combine more than one of them.

    Opens with ``stim_channel=False`` -- see the module docstring -- so a
    channel MNE would otherwise auto-detect as a trigger/status channel (e.g.
    one literally named ``"Status"``) is calibrated the same way as any other
    channel instead of being given MNE's unrelated, non-calibrated trigger-code
    treatment, which would otherwise silently disagree with a normal pyedflib
    read of that one channel (issue #109's own probe file has exactly this
    shape: a degenerate reference channel AND a "Status" channel in the same
    recording).

    An EDF+D/BDF+D file is checked first (:func:`verify_records_contiguous`): one
    with a gap raises :class:`~biosigio.exceptions.DiscontinuousRecordingError`, one
    whose records are contiguous is read and flagged ``verified_contiguous``.

    Raises ``ImportError`` if MNE (the ``meg`` extra) is not installed, and
    ``OSError``/``FileReadError`` for anything that turns out not to be
    recoverable after all: a truncation the safety net catches, a per-channel
    unit gain that disagrees with what biosigIO independently expects (see
    :func:`_channel_gains`), or a channel MNE read that cannot be paired back
    up with its header row.

    Channels are paired with header rows by POSITION: MNE lists the header's
    signals in on-disk order minus the EDF+/BDF+ annotations channel, so the
    n-th name in ``raw.ch_names`` is the n-th non-annotation header row. Each
    pairing is still checked by name, so a reader that reorders or drops a
    channel fails loud rather than attaching one row's scaling to another
    row's data. The check accepts MNE's own renaming of a repeated label: two
    header rows both labelled ``"EEG"`` come back from MNE as ``"EEG-0"`` and
    ``"EEG-1"``. The labels returned are biosigIO's (see
    :func:`~biosigio.importers._labels.unique_channel_labels`), not MNE's, so
    a recovered read names its channels exactly as a normal read would.
    """
    from ..exceptions import FileReadError
    from ._mne_common import require_mne

    probe = probe_edf_header(filepath)
    _check_not_truncated(filepath, probe, probe.number_of_datarecords)
    # Before MNE is touched: it would concatenate the records of a gapped EDF+D file
    # onto one contiguous axis (issue #180), so a file with a gap is refused here,
    # whatever else about it sent it down this path, and without needing MNE at all.
    verified_contiguous = verify_records_contiguous(filepath, probe)

    mne = require_mne()

    # stim_channel=False: see the module docstring -- without it, MNE would
    # auto-detect a channel named e.g. "Status" as a trigger channel and give
    # it its own uncalibrated, bitmasked treatment instead of the header's
    # declared physical scaling, breaking unit parity with pyedflib for it.
    raw = mne.io.read_raw(filepath, preload=True, verbose="ERROR", stim_channel=False)
    data = raw.get_data()
    sfreq = float(raw.info["sfreq"])

    # Pair by position (see the docstring): MNE drops only the annotations
    # channel, and renames a repeated label "<label>-<suffix>".
    probed_channels = [ch for ch in probe.channels if ch["label"] not in _ANNOTATION_LABELS]
    if len(probed_channels) != len(raw.ch_names):
        raise FileReadError(
            f"{filepath}: fallback reader (MNE {mne.__version__}) read "
            f"{len(raw.ch_names)} channels but the file's own header declares "
            f"{len(probed_channels)} signal channels"
        )
    _check_channel_pairing(filepath, list(raw.ch_names), [p["label"] for p in probed_channels])
    labels, renamed = unique_channel_labels(
        [p["label"] for p in probed_channels], filepath=filepath
    )

    gains = _channel_gains(raw, [p["dimension"] for p in probed_channels])

    channels: list[EdfFallbackChannel] = []
    for i, (label, probed) in enumerate(zip(labels, probed_channels, strict=True)):
        degenerate = probed["physical_min"] == probed["physical_max"]
        if degenerate:
            # The digital-to-physical slope is 0/0; the only value the scaling
            # formula can consistently produce is the (equal) physical_min/max
            # constant itself -- 0 in the common referential-reference-channel
            # case, but not assumed to be 0 in general.
            values = np.full(data.shape[1], probed["physical_min"], dtype=np.float64)
        else:
            values = data[i] / gains[i]
        channels.append(
            EdfFallbackChannel(
                label=label,
                data=values,
                sample_frequency=sfreq,
                physical_dimension=probed["dimension"] or "n/a",
                physical_min=probed["physical_min"],
                physical_max=probed["physical_max"],
                digital_min=probed["digital_min"],
                digital_max=probed["digital_max"],
                prefilter=probed["prefilter"] or "n/a",
                transducer=probed["transducer"],
                degenerate_physical_range=degenerate,
            )
        )

    events = _events_from_mne_annotations(raw)

    is_bdf = filepath.lower().endswith(".bdf")
    is_plus = probe.reserved.upper().startswith(("EDF+", "BDF+"))
    if is_bdf:
        filetype = pyedflib.FILETYPE_BDFPLUS if is_plus else pyedflib.FILETYPE_BDF
    else:
        filetype = pyedflib.FILETYPE_EDFPLUS if is_plus else pyedflib.FILETYPE_EDF

    return EdfFallbackRecording(
        channels=channels,
        events=events,
        filetype=filetype,
        file_duration=(raw.n_times / sfreq) if sfreq else 0.0,
        datarecord_duration=probe.duration_of_data_record,
        renamed_labels=renamed,
        verified_contiguous=verified_contiguous,
    )

unique_channel_labels(labels, *, source='EDF', filepath=None)

Rename repeated channel labels the way MNE does, so no channel is dropped.

EDF does not require unique labels (CHB-MIT declares T8-P8 twice and uses - as a placeholder for several unused inputs), but a Recording is keyed by label. The same rule serves any other source that can repeat a label (a WFDB sig_name, a Zarr store published before this rule existed); source names the format and filepath the file in the warning and error text. Every occurrence of a repeated label gets a running suffix -0, -1, ...; a suffix that would collide with an existing label falls through to -a, -b, ... Unique labels are returned unchanged.

For a single repeated stem this matches MNE's _unique_channel_names name for name, so the names match a channels.tsv written by MNE-BIDS. With several repeated stems whose suffixed names interact (one stem's candidate colliding with another stem's label or suffix), the result here is deterministic, stems being processed in first-occurrence order, whereas MNE iterates a set of stems, so its result can differ from this one and from run to run.

Returns: (labels, renames): the de-duplicated labels, in input order, and {new_label: original_label} for every label that was changed (empty when all labels were already unique). Callers record a non-empty mapping under :data:DEDUPLICATED_LABELS_KEY so a rename is visible downstream rather than only in a log line.

Raises: ValueError: If every candidate suffix (the running number, then a..z) for an occurrence collides with an existing label.

Source code in biosigio/importers/_labels.py
def unique_channel_labels(
    labels: list[str], *, source: str = "EDF", filepath: str | None = None
) -> tuple[list[str], dict[str, str]]:
    """Rename repeated channel labels the way MNE does, so no channel is dropped.

    EDF does not require unique labels (CHB-MIT declares ``T8-P8`` twice and
    uses ``-`` as a placeholder for several unused inputs), but a Recording is
    keyed by label. The same rule serves any other source that can repeat a
    label (a WFDB ``sig_name``, a Zarr store published before this rule
    existed); ``source`` names the format and ``filepath`` the file in the
    warning and error text.
    Every occurrence of a repeated label gets a running suffix
    ``-0``, ``-1``, ...; a suffix that would collide with an existing label
    falls through to ``-a``, ``-b``, ... Unique labels are returned unchanged.

    For a single repeated stem this matches MNE's ``_unique_channel_names``
    name for name, so the names match a ``channels.tsv`` written by MNE-BIDS.
    With several repeated stems whose suffixed names interact (one stem's
    candidate colliding with another stem's label or suffix), the result here
    is deterministic, stems being processed in first-occurrence order, whereas
    MNE iterates a ``set`` of stems, so its result can differ from this one
    and from run to run.

    Returns:
        ``(labels, renames)``: the de-duplicated labels, in input order, and
        ``{new_label: original_label}`` for every label that was changed
        (empty when all labels were already unique). Callers record a
        non-empty mapping under :data:`DEDUPLICATED_LABELS_KEY` so a rename is
        visible downstream rather than only in a log line.

    Raises:
        ValueError: If every candidate suffix (the running number, then
            ``a``..``z``) for an occurrence collides with an existing label.
    """
    names = list(labels)
    dups = [name for name in dict.fromkeys(names) if names.count(name) > 1]
    if not dups:
        return names, {}
    where = f" in {filepath}" if filepath else ""
    logger.warning(
        "%s channel labels are not unique%s, found duplicates for: %s. "
        "Applying running numbers for duplicates.",
        source,
        where,
        dups,
    )
    renames: dict[str, str] = {}
    for stem in dups:
        positions = [i for i, name in enumerate(names) if name == stem]
        for idx, pos in enumerate(positions):
            for suffix in (str(idx), *"abcdefghijklmnopqrstuvwxyz"):
                candidate = f"{stem}-{suffix}"
                if candidate not in names:
                    break
            else:
                raise ValueError(
                    f"Could not de-duplicate {source} channel label {stem!r}{where}: every "
                    "suffixed candidate (the running number, then a..z) collides with an "
                    "existing label"
                )
            names[pos] = candidate
            renames[candidate] = stem
    return names, renames

Usage Example

from biosigio import Recording
from biosigio.importers.edf import EDFImporter

# Method 1: Using Recording.from_file (recommended)
rec = Recording.from_file('data.edf', importer='edf')  # Works for both .edf and .bdf

# Method 2: Using the importer directly
rec = EDFImporter().load('data.edf')

File Format Support

The EDF importer supports:

  1. EDF files (16-bit resolution)
  2. BDF files (24-bit resolution)
  3. EDF+ / BDF+ files with annotations (loaded into Recording.events)

The .edf and .bdf extensions are auto-detected by Recording.from_file.

EDF does not require unique channel labels. Repeated labels get MNE-style running suffixes (T8-P8-0, T8-P8-1) so every channel is kept; see Repeated channel labels. Three non-compliant but intact conditions pyedflib rejects are recovered through a tolerant fallback; see the EDF format page.

Channel Type Detection

The EDF importer identifies channel types from the channel label and transducer fields in the EDF header (e.g., a label or transducer containing 'EMG' is classified as EMG; 'EEG', 'ECG'/'EKG', 'EOG', 'ACC', 'GYRO', and 'TRIG' are handled similarly, otherwise OTHER).

Parameters

EDFImporter().load(filepath, *, mixed_rate="error") takes:

  • filepath (str): Path to the EDF/BDF file.
  • mixed_rate (str): What to do when channels carry different sampling rates. "error" (default) raises MixedSamplingRateError; "resample" upsamples the slower channels to the fastest rate and keeps each channel's original rate as original_sample_frequency.

The importer reads the entire file; it does not support partial/segment loading.

Return Value

The load() method returns a single Recording object with:

  1. signals: signal data with channels as columns.
  2. channels: per-channel information including:
  3. channel_type: type of channel (EMG, EEG, etc.)
  4. physical_dimension: physical unit (e.g., 'µV', 'mV')
  5. sample_frequency: sampling rate in Hz
  6. prefilter: pre-filtering string from the header
  7. physical_min / physical_max: physical value bounds
  8. digital_min / digital_max: digital value bounds
  9. transducer: transducer string from the header
  10. metadata: fields parsed from the EDF header, including patient/recording info (patientcode, patient_name, technician, equipment, startdate, ...), file_info (filetype, number_of_signals, file_duration, datarecord_duration), and source_file.

Annotations are NOT stored in metadata; see "Working with Annotations" below.

Implementation Details

The EDF importer uses the pyedflib package to:

  1. Read the EDF/BDF file header to extract metadata.
  2. Extract per-channel information and convert it to biosigIO's format.
  3. Load the signal data into a pandas DataFrame.
  4. Read any EDF+/BDF+ annotations into the Recording's events.

Working with Annotations

EDF+ / BDF+ files can contain annotations that mark events in the data. The importer reads them into Recording.events, a pandas DataFrame with onset, duration, and description columns. When the Recording is exported back to EDF/BDF, these events are written out again as EDF+ annotations.

# Load an EDF+ file with annotations
rec = Recording.from_file('data.edf', importer='edf')

# Access annotations via the events DataFrame
for _, event in rec.events.iterrows():
    print(f"Event: {event['description']} at {event['onset']}s, "
          f"duration: {event['duration']}s")