Skip to content

Zarr Exporter (serving store)

Exports a Recording to a sharded Zarr v3 serving store: an anti-aliased, per-modality-resampled level 0 inference signal plus a min/max view pyramid for rendering. A derived serving copy, not an archival source. Requires the zarr extra (zarr v3).

See Zarr Serving Store for the on-disk store contract and serving model.

Module Documentation

biosigio.exporters.zarr

Zarr exporter for biosignal recordings (biosigIO serving format).

Writes a single, cloud-native store that serves three jobs from one conversion: fast edge viewing, edge/batch inference, and training-time streaming. The design follows a few correctness rules:

  • level 0 of every channel group is the canonical inference signal, anti-aliased and resampled to a per-modality rate (250 Hz for EEG/MEG, 1000 Hz for iEEG/EMG by default), never upsampled.
  • A min/max view pyramid sits above level 0 (<group>/view/<L>). These levels are nonlinear envelopes for rendering only and are flagged usable_for_inference=False so nobody trains on them by mistake.
  • Heterogeneous channels (mixed types/units, and the rarer mixed native rates that BIDS allows within a modality) are grouped by (modality, native rate) so every array stays internally length-consistent. Trigger/clock channels are resampled without anti-aliasing (nearest sample) to preserve step edges.
  • Signals are stored int16 with a per-channel scale/offset by default (half the bytes of float32; ML casts on read). Pass dtype="float32" for a lossless store.

The original full-rate recording is never the source of truth here; that stays in the BIDS archive. This store is a derived serving copy, and the downsampling parameters are recorded in attrs so it is reproducible. zarr is an optional dependency (the zarr extra), imported lazily.

Layout (one root group per recording)::

/                         root attrs: provenance, modality_rates, metadata
  <modality>_<rate>hz/    one group per (modality, native rate); attrs declare
                          the pyramid and the chunk geometry
    0                     (n_ch, n_time) base signal, anti-aliased. Chunked and
                          sharded on TIME (``chunk_seconds`` / ``shard_seconds``),
                          the granularity inference and training reads want.
    view/1, view/2, ...   (2, n_ch, n_time_L) min/max envelopes. Chunked on a
                          constant COLUMN count (``view_chunk_columns``), NOT on
                          time: a viewport needs ~1-2k columns at whatever level
                          it picks, so a time-based chunk would shrink fourfold
                          per level and turn one screen into hundreds of tiny
                          requests. On a 40-minute 129-channel 250 Hz EEG
                          store measured in a transfer-efficiency audit, a
                          whole-recording view at LEVEL 4 was 594 requests for
                          1.16 MB and the LEVEL 6 minimap 148 for 77 KB; at 1024
                          columns those are 3 requests and 1. The chunk counts
                          are pinned by a test here, the byte figures are the
                          audit's and are not re-measured.
  events/                 onset, duration, code arrays + label_map attr

Every channel group declares its pyramid and geometry in attrs -- n_view_levels, view_levels, view_downsample, view_chunk_columns, chunk_seconds, shard_seconds -- so a reader plans its reads instead of probing view/1, view/2, ... until a 404. format_version stays at 2 for these: they are additive attrs plus a chunk-shape change, and every Zarr v3 reader takes chunk shapes from the array metadata it must already parse.

DEFAULT_MODALITY_RATES = {'EEG': 250, 'MEG': 250, 'IEEG': 1000, 'EMG': 1000} module-attribute

DISCRETE_CHANNEL_TYPES = frozenset({'TRIG', 'SYSCLOCK', 'CTRL'}) module-attribute

FORMAT = 'biosigio-zarr' module-attribute

FORMAT_VERSION = 2 module-attribute

SUBJECT_INFO_EXCLUDED_ATTR = 'subject_info_excluded' module-attribute

_BIOSIGIO_VERSION = '1.2.14' module-attribute

_DISCRETE_TYPES = DISCRETE_CHANNEL_TYPES module-attribute

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
    )

ZarrExporter

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

Source code in biosigio/exporters/zarr.py
class ZarrExporter:
    """Exporter to a sharded Zarr v3 store with a min/max view pyramid."""

    @staticmethod
    def export(
        rec: Recording,
        filepath: str,
        *,
        modality_rates: dict[str, int] | None = None,
        dtype: str = "int16",
        view_downsample: int = 4,
        min_view_samples: int = 512,
        max_view_levels: int = 12,
        chunk_seconds: float = 4.0,
        shard_seconds: float = 300.0,
        view_chunk_columns: int = 1024,
        compressor_level: int = 5,
        events_df=None,
        exclude_subject_info: bool = False,
    ) -> str:
        """Write ``rec`` to a Zarr store at ``filepath``.

        Args:
            rec: Source recording.
            filepath: Output store path (``.zarr`` appended if missing).
            modality_rates: Per-modality canonical rate cap. Defaults to
                :data:`DEFAULT_MODALITY_RATES`. MEG defaults to 250 Hz with EEG;
                raise its cap if you need MEG high-gamma.
            dtype: ``"int16"`` (default, scaled, half the bytes) or ``"float32"``
                (lossless).
            view_downsample: Time decimation factor between pyramid levels.
            min_view_samples: Pyramid floor. For the exact stopping rule -- and
                why the last level written can be shorter than this -- see
                :func:`~biosigio.exporters.zarr_stream._pyramid_level_lengths`.
            max_view_levels: Hard cap on pyramid depth.
            chunk_seconds: Time span per chunk of ``level 0`` (random-access
                granularity). View levels are chunked by column count instead;
                see ``view_chunk_columns``.
            shard_seconds: Time span per shard of ``level 0`` (sequential-read
                granularity for training); rounded to a whole number of chunks.
            view_chunk_columns: Columns per chunk of every ``view/*`` level
                (capped by the level's length). Must be >= 1. The default 1024
                is about one viewport, so the columns a viewport needs, at
                whichever level it picks, are a handful of requests rather than
                hundreds.
            compressor_level: zstd level for the Blosc codec.
            events_df: Optional events table; falls back to ``rec.events``.
            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 set the root attribute ``subject_info_excluded`` to
                true. Recording dates and times, events and channel information are
                kept. ``rec`` itself is not changed. Default False writes the
                metadata as earlier releases did.

        Returns:
            The store path written.
        """
        zarr = require_zarr()
        from zarr.codecs import BloscCodec

        if rec.signals is None or len(rec.channels) == 0:
            raise ValueError("No signals loaded")
        if dtype not in ("int16", "float32"):
            raise ValueError("dtype must be 'int16' or 'float32'")
        if int(view_chunk_columns) < 1:
            raise ValueError("view_chunk_columns must be >= 1")

        rates = dict(DEFAULT_MODALITY_RATES if modality_rates is None else modality_rates)
        if not filepath.endswith(".zarr"):
            filepath = filepath + ".zarr"

        store = zarr.storage.LocalStore(filepath)
        root = zarr.create_group(store=store, overwrite=True)
        compressors = [BloscCodec(cname="zstd", clevel=compressor_level)]

        # Group channels by (modality, native rate) so each array is length-
        # consistent. Preserve channel order within a group.
        groups: dict[tuple[str, int], list[str]] = {}
        for label in rec.signals.columns:
            info = rec.channels[label]
            key = (str(info.get("modality", "MISC")), int(round(info["sample_frequency"])))
            groups.setdefault(key, []).append(label)

        written_groups: list[str] = []
        for (modality, native_rate), labels in groups.items():
            target_rate = _target_rate(native_rate, modality, rates)

            # Stream channels one at a time straight into the output-dtype array.
            # The previous code held a float64 list of every channel, a float64
            # vstack copy, and the int16 copy at once (~4.5x the int16 output);
            # a 5 GB recording peaked at ~26 GB RSS and OOM'd every free CI
            # runner (#95). n_time is the post-resample length, identical for
            # every channel in the group (they share native_rate).
            n_ch = len(labels)
            n_time = max(0, int(round(len(rec.signals) * target_rate / native_rate)))
            base = np.empty((n_ch, n_time), dtype=np.int16 if dtype == "int16" else np.float32)
            scale = np.ones(n_ch, dtype=np.float64)
            offset = np.zeros(n_ch, dtype=np.float64)
            chan_meta = []
            for i, label in enumerate(labels):
                info = rec.channels[label]
                ctype = str(info.get("channel_type", "MISC")).upper()
                discrete = ctype in _DISCRETE_TYPES
                y = _resample_channel(
                    rec.signals[label].values, native_rate, target_rate, discrete=discrete
                )
                n_nonfinite = 0
                if dtype == "int16":
                    base[i], scale[i], offset[i], n_nonfinite = _quantize_int16_channel(y)
                else:
                    base[i] = y.astype(np.float32)
                del y
                meta = {
                    "label": label,
                    "channel_type": ctype,
                    "modality": modality,
                    "unit": info.get("physical_dimension", "n/a"),
                    "prefilter": info.get("prefilter", "n/a"),
                    # The true per-channel rate, not the rounded group key, so a
                    # non-integer acquisition rate is not lost (metadata loss is data loss).
                    "original_rate": float(info["sample_frequency"]),
                    "target_rate": float(target_rate),
                    "anti_aliased": bool((not discrete) and target_rate < native_rate),
                    # A channel whose NaN/inf gaps were zero-filled is lossy: keep it
                    # viewable but never inferable (int16 fill is not the real signal).
                    "usable_for_inference": (not discrete) and n_nonfinite == 0,
                    "scale": float(scale[i]),
                    "offset": float(offset[i]),
                    "row_index": i,
                }
                if n_nonfinite:
                    meta["nonfinite_samples"] = n_nonfinite
                # A unit the BIDS sidecar declared but the values contradict is
                # kept as metadata rather than asserted (see
                # biosigio.bids._decide_unit); the streaming exporter carries it
                # the same way, so the two stores stay comparable channel for
                # channel.
                if info.get("bids_unit"):
                    meta["bids_unit"] = info["bids_unit"]
                chan_meta.append(meta)

            gname = f"{modality.lower()}_{int(round(target_rate))}hz"
            # Disambiguate the rare collision of two native rates -> same target.
            if gname in written_groups:
                candidate = f"{gname}_from{int(native_rate)}"
                if candidate in written_groups:
                    raise ValueError(
                        f"Zarr group name collision: {candidate!r} is already used. Three or more "
                        f"native rates in modality {modality!r} map to the same target rate; "
                        "split the recording or widen the modality rate cap."
                    )
                gname = candidate
            written_groups.append(gname)
            grp = root.create_group(gname)

            # Min/max view pyramid (rendering only), built in digital space so it
            # shares the base scale/offset; never inference-usable. Built before the
            # group attrs so the group can DECLARE its depth (n_view_levels /
            # view_levels) and a reader never has to probe view/1..n until a 404.
            pyramid = _build_minmax_pyramid(
                base, view_downsample, min_view_samples, max_view_levels
            )
            chunk_t, shard_t = _chunk_shard_time(n_time, target_rate, chunk_seconds, shard_seconds)
            grp.attrs.update(
                {
                    "modality": modality,
                    "rate": float(target_rate),
                    "original_rate": float(native_rate),
                    "n_channels": int(n_ch),
                    "n_samples": int(n_time),
                    "channels": chan_meta,
                    "n_view_levels": len(pyramid),
                    "view_levels": list(range(1, len(pyramid) + 1)),
                    "view_downsample": int(view_downsample),
                    "view_chunk_columns": int(view_chunk_columns),
                    "chunk_seconds": float(chunk_seconds),
                    "shard_seconds": float(shard_seconds),
                }
            )

            a0 = grp.create_array(
                "0",
                shape=(n_ch, n_time),
                chunks=(n_ch, chunk_t),
                shards=(n_ch, shard_t),
                dtype=base.dtype,
                compressors=compressors,
            )
            a0[:] = base
            a0.attrs.update(
                {
                    "level": 0,
                    "rate": float(target_rate),
                    # The native acquisition rate this group came from, so a reader
                    # can tell the effective (capped) rate from the source rate
                    # without re-deriving it from the per-channel metadata.
                    "source_rate_hz": float(native_rate),
                    "downsample_factor": 1,
                    "kind": "signal",
                    "chunk_samples": int(chunk_t),
                    "shard_samples": int(shard_t),
                    "anti_aliased": any(m["anti_aliased"] for m in chan_meta),
                    # A group of only discrete channels is not inference-usable.
                    "usable_for_inference": any(m["usable_for_inference"] for m in chan_meta),
                    "scale": scale.tolist(),
                    "offset": offset.tolist(),
                    "physical_formula": "physical = digital * scale + offset",
                }
            )

            view = grp.create_group("view")
            for li, lvl in enumerate(pyramid, start=1):
                eff_factor = view_downsample**li
                ct = _view_chunk_columns(lvl.shape[2], view_chunk_columns)
                av = view.create_array(
                    str(li),
                    shape=lvl.shape,
                    chunks=(2, n_ch, ct),
                    dtype=lvl.dtype,
                    compressors=compressors,
                )
                av[:] = lvl
                av.attrs.update(
                    {
                        "level": li,
                        "downsample_factor": eff_factor,
                        "rate_effective": float(target_rate) / eff_factor,
                        "kind": "minmax_envelope",
                        "axis0": ["min", "max"],
                        "chunk_columns": int(ct),
                        "usable_for_inference": False,
                    }
                )

        # Events as onset/duration/code arrays plus a portable code->label map.
        ev = rec.events if events_df is None else events_df
        eg = root.create_group("events")
        if ev is not None and len(ev) > 0:
            onset = ev["onset"].to_numpy(dtype=np.float64)
            duration = ev["duration"].to_numpy(dtype=np.float64)
            descs = ev["description"].astype(str).to_numpy()
            uniques = list(dict.fromkeys(descs.tolist()))
            code_of = {d: i for i, d in enumerate(uniques)}
            codes = np.array([code_of[d] for d in descs], dtype=np.int32)
            for name, arr in (("onset", onset), ("duration", duration), ("code", codes)):
                a = eg.create_array(name, shape=arr.shape, chunks=arr.shape, dtype=arr.dtype)
                a[:] = arr
            eg.attrs["label_map"] = {str(i): d for i, d in enumerate(uniques)}
            eg.attrs["n_events"] = int(len(ev))
        else:
            eg.attrs["label_map"] = {}
            eg.attrs["n_events"] = 0

        # What applying the BIDS channels.tsv did to this recording's units, at
        # the root rather than buried in recording_metadata -- and written by the
        # streaming exporter too, which has no Recording to carry it.
        units_report = rec.metadata.get("channels_tsv_units")
        recording_metadata = _recording_metadata_attr(
            rec.metadata, exclude_subject_info=exclude_subject_info
        )
        root.attrs.update(
            {
                "biosigio_version": _BIOSIGIO_VERSION,
                "format": FORMAT,
                "format_version": FORMAT_VERSION,
                "source_format": rec.metadata.get("source_format", "n/a"),
                "modality_rates": rates,
                "dtype": dtype,
                "view_downsample": view_downsample,
                "view_chunk_columns": int(view_chunk_columns),
                "anti_alias_filter": "scipy.signal.resample_poly (polyphase FIR)",
                "channel_groups": written_groups,
                # Native JSON object (datetimes/numpy as typed envelopes), shared
                # with the tabular schema, so a browser/zarrita reader can consume
                # it directly without a second parse and without a lossy str() dump.
                "recording_metadata": recording_metadata,
                **({SUBJECT_INFO_EXCLUDED_ATTR: True} if exclude_subject_info else {}),
                **({} if units_report is None else {"channels_tsv_units": units_report}),
                "created_utc": _dt.datetime.now(_dt.UTC).isoformat(),
                "note": (
                    "Derived serving copy. level 0 of each group is the anti-aliased "
                    "inference signal; view/* are min/max render envelopes (not for "
                    "inference). BIDS source remains authoritative."
                ),
            }
        )
        return filepath

export(rec, filepath, *, modality_rates=None, dtype='int16', view_downsample=4, min_view_samples=512, max_view_levels=12, chunk_seconds=4.0, shard_seconds=300.0, view_chunk_columns=1024, compressor_level=5, events_df=None, exclude_subject_info=False) staticmethod

Write rec to a Zarr store at filepath.

Args: rec: Source recording. filepath: Output store path (.zarr appended if missing). modality_rates: Per-modality canonical rate cap. Defaults to :data:DEFAULT_MODALITY_RATES. MEG defaults to 250 Hz with EEG; raise its cap if you need MEG high-gamma. dtype: "int16" (default, scaled, half the bytes) or "float32" (lossless). view_downsample: Time decimation factor between pyramid levels. min_view_samples: Pyramid floor. For the exact stopping rule -- and why the last level written can be shorter than this -- see :func:~biosigio.exporters.zarr_stream._pyramid_level_lengths. max_view_levels: Hard cap on pyramid depth. chunk_seconds: Time span per chunk of level 0 (random-access granularity). View levels are chunked by column count instead; see view_chunk_columns. shard_seconds: Time span per shard of level 0 (sequential-read granularity for training); rounded to a whole number of chunks. view_chunk_columns: Columns per chunk of every view/* level (capped by the level's length). Must be >= 1. The default 1024 is about one viewport, so the columns a viewport needs, at whichever level it picks, are a handful of requests rather than hundreds. compressor_level: zstd level for the Blosc codec. events_df: Optional events table; falls back to rec.events. 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 set the root attribute subject_info_excluded to true. Recording dates and times, events and channel information are kept. rec itself is not changed. Default False writes the metadata as earlier releases did.

Returns: The store path written.

Source code in biosigio/exporters/zarr.py
@staticmethod
def export(
    rec: Recording,
    filepath: str,
    *,
    modality_rates: dict[str, int] | None = None,
    dtype: str = "int16",
    view_downsample: int = 4,
    min_view_samples: int = 512,
    max_view_levels: int = 12,
    chunk_seconds: float = 4.0,
    shard_seconds: float = 300.0,
    view_chunk_columns: int = 1024,
    compressor_level: int = 5,
    events_df=None,
    exclude_subject_info: bool = False,
) -> str:
    """Write ``rec`` to a Zarr store at ``filepath``.

    Args:
        rec: Source recording.
        filepath: Output store path (``.zarr`` appended if missing).
        modality_rates: Per-modality canonical rate cap. Defaults to
            :data:`DEFAULT_MODALITY_RATES`. MEG defaults to 250 Hz with EEG;
            raise its cap if you need MEG high-gamma.
        dtype: ``"int16"`` (default, scaled, half the bytes) or ``"float32"``
            (lossless).
        view_downsample: Time decimation factor between pyramid levels.
        min_view_samples: Pyramid floor. For the exact stopping rule -- and
            why the last level written can be shorter than this -- see
            :func:`~biosigio.exporters.zarr_stream._pyramid_level_lengths`.
        max_view_levels: Hard cap on pyramid depth.
        chunk_seconds: Time span per chunk of ``level 0`` (random-access
            granularity). View levels are chunked by column count instead;
            see ``view_chunk_columns``.
        shard_seconds: Time span per shard of ``level 0`` (sequential-read
            granularity for training); rounded to a whole number of chunks.
        view_chunk_columns: Columns per chunk of every ``view/*`` level
            (capped by the level's length). Must be >= 1. The default 1024
            is about one viewport, so the columns a viewport needs, at
            whichever level it picks, are a handful of requests rather than
            hundreds.
        compressor_level: zstd level for the Blosc codec.
        events_df: Optional events table; falls back to ``rec.events``.
        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 set the root attribute ``subject_info_excluded`` to
            true. Recording dates and times, events and channel information are
            kept. ``rec`` itself is not changed. Default False writes the
            metadata as earlier releases did.

    Returns:
        The store path written.
    """
    zarr = require_zarr()
    from zarr.codecs import BloscCodec

    if rec.signals is None or len(rec.channels) == 0:
        raise ValueError("No signals loaded")
    if dtype not in ("int16", "float32"):
        raise ValueError("dtype must be 'int16' or 'float32'")
    if int(view_chunk_columns) < 1:
        raise ValueError("view_chunk_columns must be >= 1")

    rates = dict(DEFAULT_MODALITY_RATES if modality_rates is None else modality_rates)
    if not filepath.endswith(".zarr"):
        filepath = filepath + ".zarr"

    store = zarr.storage.LocalStore(filepath)
    root = zarr.create_group(store=store, overwrite=True)
    compressors = [BloscCodec(cname="zstd", clevel=compressor_level)]

    # Group channels by (modality, native rate) so each array is length-
    # consistent. Preserve channel order within a group.
    groups: dict[tuple[str, int], list[str]] = {}
    for label in rec.signals.columns:
        info = rec.channels[label]
        key = (str(info.get("modality", "MISC")), int(round(info["sample_frequency"])))
        groups.setdefault(key, []).append(label)

    written_groups: list[str] = []
    for (modality, native_rate), labels in groups.items():
        target_rate = _target_rate(native_rate, modality, rates)

        # Stream channels one at a time straight into the output-dtype array.
        # The previous code held a float64 list of every channel, a float64
        # vstack copy, and the int16 copy at once (~4.5x the int16 output);
        # a 5 GB recording peaked at ~26 GB RSS and OOM'd every free CI
        # runner (#95). n_time is the post-resample length, identical for
        # every channel in the group (they share native_rate).
        n_ch = len(labels)
        n_time = max(0, int(round(len(rec.signals) * target_rate / native_rate)))
        base = np.empty((n_ch, n_time), dtype=np.int16 if dtype == "int16" else np.float32)
        scale = np.ones(n_ch, dtype=np.float64)
        offset = np.zeros(n_ch, dtype=np.float64)
        chan_meta = []
        for i, label in enumerate(labels):
            info = rec.channels[label]
            ctype = str(info.get("channel_type", "MISC")).upper()
            discrete = ctype in _DISCRETE_TYPES
            y = _resample_channel(
                rec.signals[label].values, native_rate, target_rate, discrete=discrete
            )
            n_nonfinite = 0
            if dtype == "int16":
                base[i], scale[i], offset[i], n_nonfinite = _quantize_int16_channel(y)
            else:
                base[i] = y.astype(np.float32)
            del y
            meta = {
                "label": label,
                "channel_type": ctype,
                "modality": modality,
                "unit": info.get("physical_dimension", "n/a"),
                "prefilter": info.get("prefilter", "n/a"),
                # The true per-channel rate, not the rounded group key, so a
                # non-integer acquisition rate is not lost (metadata loss is data loss).
                "original_rate": float(info["sample_frequency"]),
                "target_rate": float(target_rate),
                "anti_aliased": bool((not discrete) and target_rate < native_rate),
                # A channel whose NaN/inf gaps were zero-filled is lossy: keep it
                # viewable but never inferable (int16 fill is not the real signal).
                "usable_for_inference": (not discrete) and n_nonfinite == 0,
                "scale": float(scale[i]),
                "offset": float(offset[i]),
                "row_index": i,
            }
            if n_nonfinite:
                meta["nonfinite_samples"] = n_nonfinite
            # A unit the BIDS sidecar declared but the values contradict is
            # kept as metadata rather than asserted (see
            # biosigio.bids._decide_unit); the streaming exporter carries it
            # the same way, so the two stores stay comparable channel for
            # channel.
            if info.get("bids_unit"):
                meta["bids_unit"] = info["bids_unit"]
            chan_meta.append(meta)

        gname = f"{modality.lower()}_{int(round(target_rate))}hz"
        # Disambiguate the rare collision of two native rates -> same target.
        if gname in written_groups:
            candidate = f"{gname}_from{int(native_rate)}"
            if candidate in written_groups:
                raise ValueError(
                    f"Zarr group name collision: {candidate!r} is already used. Three or more "
                    f"native rates in modality {modality!r} map to the same target rate; "
                    "split the recording or widen the modality rate cap."
                )
            gname = candidate
        written_groups.append(gname)
        grp = root.create_group(gname)

        # Min/max view pyramid (rendering only), built in digital space so it
        # shares the base scale/offset; never inference-usable. Built before the
        # group attrs so the group can DECLARE its depth (n_view_levels /
        # view_levels) and a reader never has to probe view/1..n until a 404.
        pyramid = _build_minmax_pyramid(
            base, view_downsample, min_view_samples, max_view_levels
        )
        chunk_t, shard_t = _chunk_shard_time(n_time, target_rate, chunk_seconds, shard_seconds)
        grp.attrs.update(
            {
                "modality": modality,
                "rate": float(target_rate),
                "original_rate": float(native_rate),
                "n_channels": int(n_ch),
                "n_samples": int(n_time),
                "channels": chan_meta,
                "n_view_levels": len(pyramid),
                "view_levels": list(range(1, len(pyramid) + 1)),
                "view_downsample": int(view_downsample),
                "view_chunk_columns": int(view_chunk_columns),
                "chunk_seconds": float(chunk_seconds),
                "shard_seconds": float(shard_seconds),
            }
        )

        a0 = grp.create_array(
            "0",
            shape=(n_ch, n_time),
            chunks=(n_ch, chunk_t),
            shards=(n_ch, shard_t),
            dtype=base.dtype,
            compressors=compressors,
        )
        a0[:] = base
        a0.attrs.update(
            {
                "level": 0,
                "rate": float(target_rate),
                # The native acquisition rate this group came from, so a reader
                # can tell the effective (capped) rate from the source rate
                # without re-deriving it from the per-channel metadata.
                "source_rate_hz": float(native_rate),
                "downsample_factor": 1,
                "kind": "signal",
                "chunk_samples": int(chunk_t),
                "shard_samples": int(shard_t),
                "anti_aliased": any(m["anti_aliased"] for m in chan_meta),
                # A group of only discrete channels is not inference-usable.
                "usable_for_inference": any(m["usable_for_inference"] for m in chan_meta),
                "scale": scale.tolist(),
                "offset": offset.tolist(),
                "physical_formula": "physical = digital * scale + offset",
            }
        )

        view = grp.create_group("view")
        for li, lvl in enumerate(pyramid, start=1):
            eff_factor = view_downsample**li
            ct = _view_chunk_columns(lvl.shape[2], view_chunk_columns)
            av = view.create_array(
                str(li),
                shape=lvl.shape,
                chunks=(2, n_ch, ct),
                dtype=lvl.dtype,
                compressors=compressors,
            )
            av[:] = lvl
            av.attrs.update(
                {
                    "level": li,
                    "downsample_factor": eff_factor,
                    "rate_effective": float(target_rate) / eff_factor,
                    "kind": "minmax_envelope",
                    "axis0": ["min", "max"],
                    "chunk_columns": int(ct),
                    "usable_for_inference": False,
                }
            )

    # Events as onset/duration/code arrays plus a portable code->label map.
    ev = rec.events if events_df is None else events_df
    eg = root.create_group("events")
    if ev is not None and len(ev) > 0:
        onset = ev["onset"].to_numpy(dtype=np.float64)
        duration = ev["duration"].to_numpy(dtype=np.float64)
        descs = ev["description"].astype(str).to_numpy()
        uniques = list(dict.fromkeys(descs.tolist()))
        code_of = {d: i for i, d in enumerate(uniques)}
        codes = np.array([code_of[d] for d in descs], dtype=np.int32)
        for name, arr in (("onset", onset), ("duration", duration), ("code", codes)):
            a = eg.create_array(name, shape=arr.shape, chunks=arr.shape, dtype=arr.dtype)
            a[:] = arr
        eg.attrs["label_map"] = {str(i): d for i, d in enumerate(uniques)}
        eg.attrs["n_events"] = int(len(ev))
    else:
        eg.attrs["label_map"] = {}
        eg.attrs["n_events"] = 0

    # What applying the BIDS channels.tsv did to this recording's units, at
    # the root rather than buried in recording_metadata -- and written by the
    # streaming exporter too, which has no Recording to carry it.
    units_report = rec.metadata.get("channels_tsv_units")
    recording_metadata = _recording_metadata_attr(
        rec.metadata, exclude_subject_info=exclude_subject_info
    )
    root.attrs.update(
        {
            "biosigio_version": _BIOSIGIO_VERSION,
            "format": FORMAT,
            "format_version": FORMAT_VERSION,
            "source_format": rec.metadata.get("source_format", "n/a"),
            "modality_rates": rates,
            "dtype": dtype,
            "view_downsample": view_downsample,
            "view_chunk_columns": int(view_chunk_columns),
            "anti_alias_filter": "scipy.signal.resample_poly (polyphase FIR)",
            "channel_groups": written_groups,
            # Native JSON object (datetimes/numpy as typed envelopes), shared
            # with the tabular schema, so a browser/zarrita reader can consume
            # it directly without a second parse and without a lossy str() dump.
            "recording_metadata": recording_metadata,
            **({SUBJECT_INFO_EXCLUDED_ATTR: True} if exclude_subject_info else {}),
            **({} if units_report is None else {"channels_tsv_units": units_report}),
            "created_utc": _dt.datetime.now(_dt.UTC).isoformat(),
            "note": (
                "Derived serving copy. level 0 of each group is the anti-aliased "
                "inference signal; view/* are min/max render envelopes (not for "
                "inference). BIDS source remains authoritative."
            ),
        }
    )
    return filepath

_build_minmax_pyramid(base, factor, min_samples, max_levels)

Return a list of (2, n_ch, n_time_L) min/max envelope levels.

Level L is built from level L-1 (min of mins, max of maxs), so the envelope is exact at every zoom. Axis 0 is [min, max].

Source code in biosigio/exporters/zarr.py
def _build_minmax_pyramid(
    base: np.ndarray, factor: int, min_samples: int, max_levels: int
) -> list[np.ndarray]:
    """Return a list of (2, n_ch, n_time_L) min/max envelope levels.

    Level L is built from level L-1 (min of mins, max of maxs), so the envelope is
    exact at every zoom. Axis 0 is [min, max].
    """
    levels: list[np.ndarray] = []
    cur_min = base
    cur_max = base
    n_ch = base.shape[0]
    for _ in range(max_levels):
        n_time = cur_min.shape[1]
        if n_time <= min_samples:
            break
        n_out = n_time // factor
        if n_out < 1:
            break
        trim = n_out * factor
        lvl_min = cur_min[:, :trim].reshape(n_ch, n_out, factor).min(axis=2)
        lvl_max = cur_max[:, :trim].reshape(n_ch, n_out, factor).max(axis=2)
        levels.append(np.stack([lvl_min, lvl_max], axis=0))
        cur_min, cur_max = lvl_min, lvl_max
    return levels

_chunk_shard_time(n_time, rate, chunk_seconds, shard_seconds)

Pick a time chunk and a shard that is a multiple of it.

Source code in biosigio/exporters/zarr.py
def _chunk_shard_time(
    n_time: int, rate: float, chunk_seconds: float, shard_seconds: float
) -> tuple[int, int]:
    """Pick a time chunk and a shard that is a multiple of it."""
    chunk_t = max(1, min(n_time, int(round(chunk_seconds * rate))))
    k = max(1, int(round(shard_seconds / chunk_seconds)))
    n_chunks = -(-n_time // chunk_t)  # ceil
    shard_t = chunk_t * min(k, n_chunks)
    return chunk_t, shard_t

_quantize_int16_channel(row)

Map one channel (1-D float) to int16 with scale/offset.

physical = digital * scale + offset. A constant (or empty) channel gets scale=1 and the constant in offset.

Non-finite samples (NaN/inf) cannot be represented in int16. Rather than fail the whole recording for a single bad channel -- a NaN in one MISC/aux channel (an accelerometer, force plate, or sync line in a MoBI dataset) would otherwise sink the entire recording, including every good EEG channel -- the non-finite samples are zero-filled: the physical range (scale/offset) is computed over the FINITE samples only, then each non-finite sample is written as the digital code for physical 0 (clamped into range). The count of filled samples is returned so the caller can flag the channel (nonfinite_samples, and demote it to usable_for_inference=False). The fill is lossy, so it is documented rather than silent, and the BIDS source remains authoritative. Callers that must keep NaN exactly (e.g. for training) should export with dtype="float32".

Operates one channel at a time so the exporter can quantize straight into the output array without materializing a float64 copy of the whole group (#95).

Source code in biosigio/exporters/zarr.py
def _quantize_int16_channel(row: np.ndarray) -> tuple[np.ndarray, float, float, int]:
    """Map one channel (1-D float) to int16 with scale/offset.

    ``physical = digital * scale + offset``. A constant (or empty) channel gets
    scale=1 and the constant in offset.

    Non-finite samples (NaN/inf) cannot be represented in int16. Rather than fail
    the whole recording for a single bad channel -- a NaN in one MISC/aux channel
    (an accelerometer, force plate, or sync line in a MoBI dataset) would otherwise
    sink the entire recording, including every good EEG channel -- the non-finite
    samples are zero-filled: the physical range (scale/offset) is computed over the
    FINITE samples only, then each non-finite sample is written as the digital code
    for physical 0 (clamped into range). The count of filled samples is returned so
    the caller can flag the channel (``nonfinite_samples``, and demote it to
    ``usable_for_inference=False``). The fill is lossy, so it is documented rather
    than silent, and the BIDS source remains authoritative. Callers that must keep
    NaN exactly (e.g. for training) should export with ``dtype="float32"``.

    Operates one channel at a time so the exporter can quantize straight into the
    output array without materializing a float64 copy of the whole group (#95).
    """
    # Quantize in float64 regardless of the caller's dtype (the old batch path
    # cast the whole block up front); a no-op for the float64 resample output.
    row = np.asarray(row, dtype=np.float64)
    finite_mask = np.isfinite(row)
    n_nonfinite = int(row.size - int(np.count_nonzero(finite_mask))) if row.size else 0
    finite = row[finite_mask] if n_nonfinite else row
    if finite.size == 0:  # empty, or every sample non-finite: flat zero channel
        return np.zeros(row.shape, dtype=np.int16), 1.0, 0.0, n_nonfinite
    pmin = float(np.min(finite))
    pmax = float(np.max(finite))
    if pmax == pmin:  # constant channel: store the constant in offset
        return np.zeros(row.shape, dtype=np.int16), 1.0, pmin, n_nonfinite
    digital_span = _INT16_MAX - _INT16_MIN
    s = (pmax - pmin) / digital_span
    o = pmin - _INT16_MIN * s
    if n_nonfinite:  # replace NaN/inf with physical 0 before quantizing
        row = np.where(finite_mask, row, 0.0)
    digital = np.round((row - o) / s)
    return np.clip(digital, _INT16_MIN, _INT16_MAX).astype(np.int16), s, o, n_nonfinite

_recording_metadata_attr(metadata, *, exclude_subject_info)

The recording_metadata root attribute for metadata.

Shared by both writers (the in-memory one here and :func:~biosigio.exporters.zarr_stream.stream_to_zarr) so the option cannot mean different things on the two paths. Without the option this is exactly the encoding earlier releases wrote. With it, subject information is stripped twice: before encoding, so a value the encoder would refuse (bytes, say) under a member being dropped cannot fail the export, and after, so a member inside a value the encoder turns into a list or dict (an object array of dicts) is still caught. Path-valued provenance is then reduced to its final component. The input is never modified.

Source code in biosigio/exporters/zarr.py
def _recording_metadata_attr(metadata, *, exclude_subject_info: bool) -> dict:
    """The ``recording_metadata`` root attribute for ``metadata``.

    Shared by both writers (the in-memory one here and
    :func:`~biosigio.exporters.zarr_stream.stream_to_zarr`) so the option cannot
    mean different things on the two paths. Without the option this is exactly
    the encoding earlier releases wrote. With it, subject information is
    stripped twice: before encoding, so a value the encoder would refuse (bytes,
    say) under a member being dropped cannot fail the export, and after, so a
    member inside a value the encoder turns into a list or dict (an object array
    of dicts) is still caught. Path-valued provenance is then reduced to its
    final component. The input is never modified.
    """
    if not exclude_subject_info:
        return metadata_to_mapping(metadata)
    encoded = metadata_to_mapping(strip_subject_info(metadata))
    return _reduce_path_provenance(strip_subject_info(encoded))

_reduce_path_provenance(metadata)

Return a copy of metadata whose top-level :data:PATH_PROVENANCE_KEYS string values are reduced to their final path component.

/home/alice/study/sub-01_eeg.edf becomes sub-01_eeg.edf, and a BTi directory .../sub-01_task-rest_meg/ becomes sub-01_task-rest_meg. A non-string value is kept as is. The input is not modified.

Source code in biosigio/exporters/subject_info.py
def _reduce_path_provenance(metadata: Mapping[str, Any]) -> dict[str, Any]:
    """Return a copy of ``metadata`` whose top-level :data:`PATH_PROVENANCE_KEYS`
    string values are reduced to their final path component.

    ``/home/alice/study/sub-01_eeg.edf`` becomes ``sub-01_eeg.edf``, and a BTi
    directory ``.../sub-01_task-rest_meg/`` becomes ``sub-01_task-rest_meg``.
    A non-string value is kept as is. The input is not modified.
    """
    out = dict(metadata)
    for key in PATH_PROVENANCE_KEYS:
        value = out.get(key)
        if isinstance(value, str):
            out[key] = _final_component(value)
    return out

_resample_channel(x, native_rate, target_rate, *, discrete)

Resample one channel to target_rate.

Continuous channels use polyphase resampling (anti-aliased). Discrete channels use nearest-sample selection so trigger edges are not smeared.

Source code in biosigio/exporters/zarr.py
def _resample_channel(
    x: np.ndarray, native_rate: float, target_rate: float, *, discrete: bool
) -> np.ndarray:
    """Resample one channel to ``target_rate``.

    Continuous channels use polyphase resampling (anti-aliased). Discrete channels
    use nearest-sample selection so trigger edges are not smeared.
    """
    x = np.asarray(x, dtype=np.float64)
    if float(target_rate) == float(native_rate):
        return x
    n_out = int(round(len(x) * target_rate / native_rate))
    if n_out <= 0:
        return np.zeros(0, dtype=np.float64)
    if discrete:
        idx = np.minimum(
            (np.arange(n_out) * native_rate / target_rate).round().astype(int), len(x) - 1
        )
        return x[idx]
    frac = Fraction(int(round(target_rate)), int(round(native_rate)))
    y = resample_poly(x, frac.numerator, frac.denominator)
    # resample_poly length can be off by one versus the nominal target; trim or
    # pad to the exact ratio length so a group's channels stay aligned.
    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

_target_rate(native_rate, modality, modality_rates)

Canonical rate for a channel: capped by modality, never upsampled.

Source code in biosigio/exporters/zarr.py
def _target_rate(native_rate: float, modality: str, modality_rates: dict[str, int]) -> float:
    """Canonical rate for a channel: capped by modality, never upsampled."""
    cap = modality_rates.get(modality.upper())
    if cap is None:
        return float(native_rate)
    return float(min(native_rate, cap))

_view_chunk_columns(n_time_level, view_chunk_columns)

Time-chunk width (columns) for one view-pyramid level.

A constant column count, capped by the level's own length so a short level is a single chunk. Deliberately NOT time-based: view levels are read by column budget (a viewport wants ~1-2k columns at whatever level it picks), so a seconds-based rule would shrink the chunk fourfold per level and shatter one screenful into hundreds of tiny requests (about 2 KB each on the 40-minute, 129-channel, 250 Hz EEG store a transfer-efficiency audit measured). Shared by both exporters (the in-memory one here and :mod:biosigio.exporters.zarr_stream) so their geometry cannot drift.

Source code in biosigio/exporters/zarr.py
def _view_chunk_columns(n_time_level: int, view_chunk_columns: int) -> int:
    """Time-chunk width (columns) for one view-pyramid level.

    A constant column count, capped by the level's own length so a short level is
    a single chunk. Deliberately NOT time-based: view levels are read by column
    budget (a viewport wants ~1-2k columns at whatever level it picks), so a
    seconds-based rule would shrink the chunk fourfold per level and shatter one
    screenful into hundreds of tiny requests (about 2 KB each on the 40-minute,
    129-channel, 250 Hz EEG store a transfer-efficiency audit measured). Shared
    by both exporters (the
    in-memory one here and :mod:`biosigio.exporters.zarr_stream`) so their
    geometry cannot drift.
    """
    return max(1, min(int(n_time_level), int(view_chunk_columns)))

metadata_to_mapping(metadata)

Encode metadata as a JSON-native dict (datetimes/numpy as typed envelopes).

Like :func:metadata_to_json but returns the parsed object rather than a string, so it can be stored directly as a Zarr attribute that a browser / zarrita reader can consume without a second JSON parse.

Source code in biosigio/tabular_schema.py
def metadata_to_mapping(metadata) -> dict:
    """Encode metadata as a JSON-native dict (datetimes/numpy as typed envelopes).

    Like :func:`metadata_to_json` but returns the parsed object rather than a
    string, so it can be stored directly as a Zarr attribute that a browser /
    zarrita reader can consume without a second JSON parse.
    """
    return json.loads(metadata_to_json(metadata))

require_zarr()

Import zarr lazily, raising a clear install hint when it is absent.

Source code in biosigio/exporters/zarr.py
def require_zarr():
    """Import zarr lazily, raising a clear install hint when it is absent."""
    try:
        import zarr  # noqa: F401
    except ImportError as e:
        raise ImportError(
            "Zarr serving-format export/import requires zarr (v3), an optional "
            "dependency. Install it with: uv sync --extra zarr  (or, for an existing "
            "install, uv pip install 'biosigio[zarr]')."
        ) from e
    import zarr

    return zarr

strip_subject_info(metadata)

Return a copy of metadata without its subject-information members.

A member is removed when :func:is_subject_info_key matches its name, at any depth: through nested mappings (older EDF stores nested the header fields under recording_info), lists and tuples. It is removed whatever its value, an empty one or a whole nested object included, so a reader never sees the member at all. Every other member is kept, in its original order.

Matching is by member name only, and it never descends into biosigIO's own label-keyed maps, channels_tsv_units and channel_labels_deduplicated: their keys are channel labels or sidecar row names, so a channel labeled Sex keeps its entry. Anywhere else a key spelled like a member is removed, whatever it describes, and a subject's details held under an unlisted name, or inside a value (a free-text string, an event label, a channel label), are not touched. Values are never inspected; path-valued members are reduced by the writers, not here.

The input is never modified: mappings, lists and tuples are rebuilt, and the remaining leaf values are the caller's own objects, not copies. A mapping comes back as a plain dict.

Args: metadata: Recording metadata, such as Recording.metadata or the encoded recording_metadata of a store.

Returns: A new dict without the subject-information members.

Raises: TypeError: metadata is not a mapping.

Example: >>> strip_subject_info({"patientcode": "P1", "recording_info": {"Sex": "F", ... "startdate": "2020-01-01"}, "number_of_signals": 2}) {'recording_info': {'startdate': '2020-01-01'}, 'number_of_signals': 2}

Source code in biosigio/exporters/subject_info.py
def strip_subject_info(metadata: Mapping[str, Any]) -> dict[str, Any]:
    """Return a copy of ``metadata`` without its subject-information members.

    A member is removed when :func:`is_subject_info_key` matches its name, at any
    depth: through nested mappings (older EDF stores nested the header fields
    under ``recording_info``), lists and tuples. It is removed whatever its
    value, an empty one or a whole nested object included, so a reader never sees
    the member at all. Every other member is kept, in its original order.

    Matching is by member name only, and it never descends into biosigIO's own
    label-keyed maps, ``channels_tsv_units`` and ``channel_labels_deduplicated``:
    their keys are channel labels or sidecar row names, so a channel labeled
    ``Sex`` keeps its entry. Anywhere else a key spelled like a member is
    removed, whatever it describes, and a subject's details held under an
    unlisted name, or inside a value (a free-text string, an event label, a
    channel label), are not touched. Values are never inspected; path-valued
    members are reduced by the writers, not here.

    The input is never modified: mappings, lists and tuples are rebuilt, and the
    remaining leaf values are the caller's own objects, not copies. A mapping
    comes back as a plain ``dict``.

    Args:
        metadata: Recording metadata, such as ``Recording.metadata`` or the
            encoded ``recording_metadata`` of a store.

    Returns:
        A new dict without the subject-information members.

    Raises:
        TypeError: ``metadata`` is not a mapping.

    Example:
        >>> strip_subject_info({"patientcode": "P1", "recording_info": {"Sex": "F",
        ...     "startdate": "2020-01-01"}, "number_of_signals": 2})
        {'recording_info': {'startdate': '2020-01-01'}, 'number_of_signals': 2}
    """
    if not isinstance(metadata, Mapping):
        raise TypeError(f"strip_subject_info expects a mapping, got {type(metadata).__name__!r}")
    return _rebuild(metadata, strip=True)

Subject information

exclude_subject_info=True removes the members named in SUBJECT_INFO_KEYS from the store's recording_metadata (matched by normalized name at any depth, outside biosigIO's label-keyed maps), reduces source_file and bti_pdf_file to their final path component, and sets the root attribute subject_info_excluded: true, which records that the option ran rather than that the store was verified clean. It keeps recording dates and times, events, channel labels, units and prefilter text. See Subject information for the full list and the limits of matching by name.

biosigio.exporters.subject_info

Subject information in recording metadata, and the export option that drops it.

A biosigIO Zarr store holds the signal, the events, channel names, types and units, and technical recording metadata. Information about the subject (who was recorded, and their age, sex or other phenotype), operator or administrative free text, and provenance that can name a person or a local path belong at dataset scope, for example in a BIDS participants.tsv, not inside every recording's store. Several importers copy such members out of the source header into Recording.metadata, and the Zarr exporters copy that metadata into the store's recording_metadata root attribute.

exclude_subject_info=True on :meth:~biosigio.core.emg.Recording.to_zarr, :meth:~biosigio.exporters.zarr.ZarrExporter.export and :func:~biosigio.exporters.zarr_stream.stream_to_zarr removes the members named in :data:SUBJECT_INFO_KEYS (through :func:strip_subject_info), reduces the path-valued members in :data:PATH_PROVENANCE_KEYS to their final component, and marks the store with :data:SUBJECT_INFO_EXCLUDED_ATTR. It keeps everything else, including recording start dates and times, events, and per-channel labels, units and prefilter text. The default writes the metadata as earlier releases did.

PATH_PROVENANCE_KEYS = ('source_file', 'bti_pdf_file') module-attribute

SUBJECT_INFO_EXCLUDED_ATTR = 'subject_info_excluded' module-attribute

SUBJECT_INFO_KEYS = frozenset({'patientcode', 'gender', 'birthdate', 'patient_additional', 'admincode', 'technician', 'equipment', 'recording_additional', 'patient_name', 'patientname', 'sex', 'local_patient_identification', 'local_recording_identification', 'subject_info', 'his_id', 'first_name', 'last_name', 'middle_name', 'birthday', 'hand', 'weight', 'height', 'experimenter', 'patient', 'patient_id', 'participant_id', 'subject_id', 'dob', 'age', 'handedness', 'operator', 'subject', 'group', 'setname', 'filename', 'filepath', 'comments', 'record_name', 'eeglab_fdt_recovered', 'brainvision_header_recovered'}) module-attribute

_LABEL_KEYED_MEMBERS = frozenset({'channels_tsv_units', 'channel_labels_deduplicated'}) module-attribute

_NORMALIZED_KEYS = frozenset(_normalize(k) for k in SUBJECT_INFO_KEYS) module-attribute

_final_component(path)

The last component of a POSIX or Windows path, ignoring trailing separators.

Source code in biosigio/exporters/subject_info.py
def _final_component(path: str) -> str:
    """The last component of a POSIX or Windows path, ignoring trailing separators."""
    return re.split(r"[\\/]", path.rstrip("\\/"))[-1]

_normalize(key)

Casefold key and drop every non-alphanumeric character.

Source code in biosigio/exporters/subject_info.py
def _normalize(key: str) -> str:
    """Casefold ``key`` and drop every non-alphanumeric character."""
    return "".join(ch for ch in key.casefold() if ch.isalnum())

_rebuild(value, *, strip)

Rebuild mappings, lists and tuples in value; with strip, without the subject-information members.

Source code in biosigio/exporters/subject_info.py
def _rebuild(value: Any, *, strip: bool) -> Any:
    """Rebuild mappings, lists and tuples in ``value``; with ``strip``, without
    the subject-information members."""
    if isinstance(value, Mapping):
        out = {}
        for k, v in value.items():
            if strip and is_subject_info_key(k):
                continue
            out[k] = _rebuild(v, strip=strip and k not in _LABEL_KEYED_MEMBERS)
        return out
    if isinstance(value, list):
        return [_rebuild(v, strip=strip) for v in value]
    if isinstance(value, tuple):
        return tuple(_rebuild(v, strip=strip) for v in value)
    return value

_reduce_path_provenance(metadata)

Return a copy of metadata whose top-level :data:PATH_PROVENANCE_KEYS string values are reduced to their final path component.

/home/alice/study/sub-01_eeg.edf becomes sub-01_eeg.edf, and a BTi directory .../sub-01_task-rest_meg/ becomes sub-01_task-rest_meg. A non-string value is kept as is. The input is not modified.

Source code in biosigio/exporters/subject_info.py
def _reduce_path_provenance(metadata: Mapping[str, Any]) -> dict[str, Any]:
    """Return a copy of ``metadata`` whose top-level :data:`PATH_PROVENANCE_KEYS`
    string values are reduced to their final path component.

    ``/home/alice/study/sub-01_eeg.edf`` becomes ``sub-01_eeg.edf``, and a BTi
    directory ``.../sub-01_task-rest_meg/`` becomes ``sub-01_task-rest_meg``.
    A non-string value is kept as is. The input is not modified.
    """
    out = dict(metadata)
    for key in PATH_PROVENANCE_KEYS:
        value = out.get(key)
        if isinstance(value, str):
            out[key] = _final_component(value)
    return out

is_subject_info_key(key)

Whether key names a member of :data:SUBJECT_INFO_KEYS.

The match is exact on the normalized form (casefolded, every non-alphanumeric character dropped), never a substring or prefix: "Sex:" and "birth_date" match, "subjects" and "comments_total" do not. Only a string key can match.

Source code in biosigio/exporters/subject_info.py
def is_subject_info_key(key: object) -> bool:
    """Whether ``key`` names a member of :data:`SUBJECT_INFO_KEYS`.

    The match is exact on the normalized form (casefolded, every
    non-alphanumeric character dropped), never a substring or prefix: ``"Sex:"``
    and ``"birth_date"`` match, ``"subjects"`` and ``"comments_total"`` do not.
    Only a string key can match.
    """
    return isinstance(key, str) and _normalize(key) in _NORMALIZED_KEYS

strip_subject_info(metadata)

Return a copy of metadata without its subject-information members.

A member is removed when :func:is_subject_info_key matches its name, at any depth: through nested mappings (older EDF stores nested the header fields under recording_info), lists and tuples. It is removed whatever its value, an empty one or a whole nested object included, so a reader never sees the member at all. Every other member is kept, in its original order.

Matching is by member name only, and it never descends into biosigIO's own label-keyed maps, channels_tsv_units and channel_labels_deduplicated: their keys are channel labels or sidecar row names, so a channel labeled Sex keeps its entry. Anywhere else a key spelled like a member is removed, whatever it describes, and a subject's details held under an unlisted name, or inside a value (a free-text string, an event label, a channel label), are not touched. Values are never inspected; path-valued members are reduced by the writers, not here.

The input is never modified: mappings, lists and tuples are rebuilt, and the remaining leaf values are the caller's own objects, not copies. A mapping comes back as a plain dict.

Args: metadata: Recording metadata, such as Recording.metadata or the encoded recording_metadata of a store.

Returns: A new dict without the subject-information members.

Raises: TypeError: metadata is not a mapping.

Example: >>> strip_subject_info({"patientcode": "P1", "recording_info": {"Sex": "F", ... "startdate": "2020-01-01"}, "number_of_signals": 2}) {'recording_info': {'startdate': '2020-01-01'}, 'number_of_signals': 2}

Source code in biosigio/exporters/subject_info.py
def strip_subject_info(metadata: Mapping[str, Any]) -> dict[str, Any]:
    """Return a copy of ``metadata`` without its subject-information members.

    A member is removed when :func:`is_subject_info_key` matches its name, at any
    depth: through nested mappings (older EDF stores nested the header fields
    under ``recording_info``), lists and tuples. It is removed whatever its
    value, an empty one or a whole nested object included, so a reader never sees
    the member at all. Every other member is kept, in its original order.

    Matching is by member name only, and it never descends into biosigIO's own
    label-keyed maps, ``channels_tsv_units`` and ``channel_labels_deduplicated``:
    their keys are channel labels or sidecar row names, so a channel labeled
    ``Sex`` keeps its entry. Anywhere else a key spelled like a member is
    removed, whatever it describes, and a subject's details held under an
    unlisted name, or inside a value (a free-text string, an event label, a
    channel label), are not touched. Values are never inspected; path-valued
    members are reduced by the writers, not here.

    The input is never modified: mappings, lists and tuples are rebuilt, and the
    remaining leaf values are the caller's own objects, not copies. A mapping
    comes back as a plain ``dict``.

    Args:
        metadata: Recording metadata, such as ``Recording.metadata`` or the
            encoded ``recording_metadata`` of a store.

    Returns:
        A new dict without the subject-information members.

    Raises:
        TypeError: ``metadata`` is not a mapping.

    Example:
        >>> strip_subject_info({"patientcode": "P1", "recording_info": {"Sex": "F",
        ...     "startdate": "2020-01-01"}, "number_of_signals": 2})
        {'recording_info': {'startdate': '2020-01-01'}, 'number_of_signals': 2}
    """
    if not isinstance(metadata, Mapping):
        raise TypeError(f"strip_subject_info expects a mapping, got {type(metadata).__name__!r}")
    return _rebuild(metadata, strip=True)

Usage Example

from biosigio import Recording

rec = Recording.from_file("data.edf")
rec.to_zarr("out.zarr")                 # int16 by default (per-channel scale/offset)
rec.to_zarr("lossless.zarr", dtype="float32")
rec.to_zarr("no-subject.zarr", exclude_subject_info=True)