Tabular Schema (serialization)¶
The canonical, versioned biosigio schema shared by the Parquet/Arrow exporters
and the Zarr store's metadata: it serializes a Recording (signals + channels +
events + metadata) self-describingly and round-trips datetimes/numpy via typed
envelopes. See Serialization & Serving.
Module Documentation¶
biosigio.tabular_schema
¶
Canonical biosigIO tabular serialization schema (Parquet / Arrow / Feather).
A :class:~biosigio.core.emg.Recording is stored as a single columnar table whose
columns are the channel signals (the time index is preserved). All non-signal
state -- recording metadata, per-channel info, and events -- is serialized as one
JSON blob under the biosigio schema-metadata key, so the file is fully
self-describing and round-trips losslessly. The same schema backs both the
exporter and the importer (and is intended to back the future Zarr path), so it
lives here once rather than being duplicated.
pyarrow is an optional dependency (arrow extra), imported lazily.
FORMAT = 'biosigio-tabular'
module-attribute
¶
FORMAT_VERSION = 1
module-attribute
¶
METADATA_KEY = b'biosigio'
module-attribute
¶
_TYPE_KEY = '__biosigio_type__'
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
43 44 45 46 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 | |
__init__()
¶
Initialize an empty recording.
Source code in biosigio/core/emg.py
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).
Source code in biosigio/core/emg.py
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
from_file(filepath, importer=None, force_csv=False, bids_channels='auto', **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 and CTF .ds; requires the 'meg' extra) - 'brainvision': BrainVision .vhdr via MNE (requires 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: When 'auto' (default), look for a sibling BIDS _channels.tsv next to the file and apply its per-channel type/units over the importer's inferred values. Pass 'off' to disable. **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
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 | |
get_channel_types()
¶
Get list of unique channel types in the data.
Returns: List of channel types (e.g., ['EMG', 'ACC', 'GYRO'])
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
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
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
get_metadata(key)
¶
Get metadata value.
Args: key: Metadata key
Returns: Value associated with the 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
get_n_channels()
¶
get_n_samples()
¶
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
has_metadata(key)
¶
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
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
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 | |
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 list of channel names to select. If None and channel_type is specified, selects all channels of that type. 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
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
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 | |
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
set_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
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
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 | |
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
to_zarr(filepath, **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, chunk/shard sizing, ...).
Args:
filepath: Output store path (.zarr appended if missing).
**kwargs: Forwarded to :meth:ZarrExporter.export.
Returns: str: The written store path.
Source code in biosigio/core/emg.py
_json_default(obj)
¶
Encode non-JSON-native values losslessly; RAISE rather than silently coerce.
datetimes/dates become a typed envelope (reconstructed by _json_object_hook)
and numpy scalars/arrays become their Python equivalents. Anything else raises
a TypeError so unexpected metadata is surfaced, never silently str()-ified
(metadata loss is data loss).
Source code in biosigio/tabular_schema.py
_json_object_hook(d)
¶
Reconstruct typed envelopes written by :func:_json_default.
Source code in biosigio/tabular_schema.py
metadata_from_json(blob)
¶
metadata_from_mapping(obj)
¶
Reconstruct metadata from either a mapping (new) or a JSON string (legacy).
Zarr stores < 0.6 wrote recording_metadata as a JSON string; 0.6+ stores
it as a native object. Accept both so older stores still round-trip.
Source code in biosigio/tabular_schema.py
metadata_to_json(metadata)
¶
Serialize recording metadata to a JSON string, lossless for datetimes/numpy.
Shared canonical encoding (also used by the Zarr store's root attrs) so every
biosigIO format records metadata the same way and round-trips types intact,
rather than silently str()-ifying values (metadata loss is data loss).
Source code in biosigio/tabular_schema.py
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
recording_to_table(rec)
¶
Build a pyarrow Table from a Recording (signals + biosigio metadata blob).
Source code in biosigio/tabular_schema.py
require_pyarrow()
¶
Import pyarrow lazily, raising a clear install hint when it is absent.
Source code in biosigio/tabular_schema.py
table_to_recording(table)
¶
Reconstruct a Recording from a biosigIO tabular Table.