XDF Importer¶
The XDFImporter class handles importing data from XDF (Extensible Data Format) files, the native format for Lab Streaming Layer (LSL) recordings. It supports multi-stream files with different sampling rates and data types.
Class Documentation¶
emgio.importers.xdf
¶
XDF (Extensible Data Format) importer for EMG data.
XDF files can contain multiple streams (EMG, EEG, markers, etc.). This module provides tools to explore XDF contents and selectively import specific streams.
BaseImporter
¶
Bases: ABC
Base class for EMG data importers.
Source code in emgio/importers/base.py
load(filepath)
abstractmethod
¶
Load EMG data from file.
Args: filepath: Path to the input file
Returns: EMG: EMG object containing the loaded data
EMG
¶
Core EMG class for handling EMG data and metadata.
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 emgio/core/emg.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 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 | |
__init__()
¶
Source code in emgio/core/emg.py
add_channel(label, data, sample_frequency, physical_dimension, prefilter='n/a', channel_type='EMG')
¶
Add a new channel to the EMG data.
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) prefilter: Pre-filtering applied to the channel channel_type: Channel type ('EMG', 'ACC', 'GYRO', etc.)
Source code in emgio/core/emg.py
add_event(onset, duration, description)
¶
Add an event/annotation to the EMG object.
Args: onset: Event onset time in seconds. duration: Event duration in seconds. description: Event description string.
Source code in emgio/core/emg.py
from_file(filepath, importer=None, force_csv=False, **kwargs)
classmethod
¶
The method to create EMG 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) 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. **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: EMG: New EMG object with loaded data
Source code in emgio/core/emg.py
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_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 emgio/core/emg.py
get_metadata(key)
¶
Get metadata value.
Args: key: Metadata key
Returns: Value associated with the 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 EMG 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 emgio/core/emg.py
select_channels(channels=None, channel_type=None, inplace=False)
¶
Select specific channels from the data and return a new EMG 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: EMG: A new EMG object containing only the selected channels
Examples: # Select specific channels new_emg = emg.select_channels(['EMG1', 'ACC1'])
# Select all EMG channels
emg_only = emg.select_channels(channel_type='EMG')
# Select specific EMG channels only, this example does not select ACC channels
emg_subset = emg.select_channels(['EMG1', 'ACC1'], channel_type='EMG')
Source code in emgio/core/emg.py
set_metadata(key, value)
¶
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, **kwargs)
¶
Export EMG data 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)
**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 emgio/core/emg.py
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 | |
XDFImporter
¶
Bases: BaseImporter
Importer for XDF (Extensible Data Format) files.
XDF files can contain multiple data streams. This importer allows selective import of specific streams by name, type, or ID.
Example: >>> # First, explore the file >>> from emgio.importers.xdf import summarize_xdf >>> summary = summarize_xdf("recording.xdf") >>> print(summary) >>> >>> # Import specific streams >>> importer = XDFImporter() >>> emg = importer.load("recording.xdf", stream_names=["EMG_stream"]) >>> >>> # Or import by type >>> emg = importer.load("recording.xdf", stream_types=["EMG", "EXG"])
Source code in emgio/importers/xdf.py
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 | |
load(filepath, stream_names=None, stream_types=None, stream_ids=None, sync_streams=True, default_channel_type='EMG', include_timestamps=False, reference_stream=None)
¶
Load EMG data from an XDF file.
Streams can be selected by name, type, or ID. If multiple selection criteria are provided, streams matching ANY criterion are included. If no selection criteria are provided, all streams with numeric data are loaded.
Args: filepath: Path to the XDF file stream_names: List of stream names to import (case-insensitive) stream_types: List of stream types to import (e.g., ["EMG", "EXG"]) stream_ids: List of stream IDs to import sync_streams: If True, synchronize streams to common timestamps. If False, streams are loaded without synchronization. default_channel_type: Default channel type for channels without explicit type info (default: "EMG") include_timestamps: If True, add a timestamp channel for each stream named "{stream_name}_LSL_timestamps" containing the original LSL timestamps. Useful for preserving timing information when exporting to formats like EDF that require regular sampling. reference_stream: Optional stream name to use as the time base reference. If not specified, the stream with the highest sampling rate is used (recommended to avoid data loss from downsampling).
Returns: EMG: EMG object containing the loaded data
Raises: ValueError: If no matching streams found or file cannot be read ImportError: If pyxdf is not installed
Source code in emgio/importers/xdf.py
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 | |
XDFStreamInfo
dataclass
¶
Information about a single XDF stream.
Source code in emgio/importers/xdf.py
__str__()
¶
Human-readable string representation.
Source code in emgio/importers/xdf.py
XDFSummary
dataclass
¶
Summary of an XDF file's contents.
Source code in emgio/importers/xdf.py
_determine_channel_type_from_label(label)
¶
Determine channel type based on label naming conventions.
Source code in emgio/importers/xdf.py
summarize_xdf(filepath)
¶
Summarize the contents of an XDF file without fully loading all data.
This function loads the XDF file and extracts metadata about all streams, including channel names, types, sampling rates, and data shapes. Use this to explore an XDF file before deciding which streams to import.
Args: filepath: Path to the XDF file
Returns: XDFSummary: Object containing information about all streams in the file
Example: >>> summary = summarize_xdf("recording.xdf") >>> print(summary) >>> # Find EMG streams >>> emg_streams = summary.get_streams_by_type("EMG")
Source code in emgio/importers/xdf.py
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 | |
Usage Examples¶
Basic Loading¶
from emgio import EMG
from emgio.importers.xdf import XDFImporter
# Method 1: Using EMG.from_file (recommended)
emg = EMG.from_file('recording.xdf')
# Method 2: Using the importer directly
importer = XDFImporter()
emg = importer.load('recording.xdf')
Exploring File Contents¶
Before loading, explore what streams are available:
from emgio.importers.xdf import summarize_xdf
summary = summarize_xdf('recording.xdf')
print(summary)
# Output example:
# XDF File: recording.xdf
# ----------------------------------------
# Stream 1: MyEEG (EEG)
# Channels: 8, Rate: 256.0 Hz
# Samples: 15360, Duration: 60.0s
# Stream 2: MyEMG (EMG)
# Channels: 2, Rate: 2048.0 Hz
# Samples: 122880, Duration: 60.0s
# Stream 3: Markers (Markers)
# Channels: 1, Rate: 0.0 Hz (irregular)
# Samples: 10
Selective Stream Loading¶
# Load only specific stream types
emg = EMG.from_file('recording.xdf', stream_types=['EMG'])
# Load multiple types
emg = EMG.from_file('recording.xdf', stream_types=['EMG', 'EEG'])
# Load by stream name
emg = EMG.from_file('recording.xdf', stream_names=['MyEMGDevice'])
# Load by stream ID
emg = EMG.from_file('recording.xdf', stream_ids=[2])
Setting Default Channel Type¶
# For streams without explicit channel type metadata
emg = EMG.from_file('recording.xdf', default_channel_type='EMG')
Preserving LSL Timestamps¶
# Include original LSL timestamps as additional channels
emg = EMG.from_file('recording.xdf', include_timestamps=True)
# Each stream gets a "{stream_name}_LSL_timestamps" channel
# Useful for synchronization with other LSL-recorded data
File Format Support¶
The XDF importer supports:
- Single-stream and multi-stream XDF files
- Compressed XDF files (.xdfz)
- Numeric data types: float32, float64, int8, int16, int32, int64
- Different sampling rates across streams (with resampling)
- Channel labels from stream descriptors
Stream Selection Parameters¶
| Parameter | Type | Description |
|---|---|---|
stream_names |
list[str] |
Filter by stream names (case-insensitive) |
stream_types |
list[str] |
Filter by stream types (e.g., "EMG", "EEG") |
stream_ids |
list[int] |
Filter by stream IDs |
default_channel_type |
str |
Default type for channels without explicit type |
include_timestamps |
bool |
If True, add LSL timestamp channels for each stream |
Return Values¶
The load() method returns an EMG object with:
Signals (pandas.DataFrame)¶
- Time-indexed signal data
- Channels as columns
- Resampled to common time base if multiple streams
Channels (dict)¶
For each channel:
- channel_type: Inferred or default type
- physical_dimension: Unit (default "a.u.")
- sample_frequency: Effective sampling rate
- stream_name: Original stream name
- stream_id: Original stream ID
Metadata (dict)¶
device: "XDF"source_file: Path to the XDF filestream_count: Number of streams in filestream_names: List of all stream namesstream_types: List of all stream types
Helper Classes¶
XDFSummary¶
Provides an overview of the XDF file:
summary = summarize_xdf('recording.xdf')
# Access all streams
for stream in summary.streams:
print(f"{stream.name}: {stream.channel_count} channels")
# Find streams by type
emg_streams = summary.get_streams_by_type('EMG')
# Find stream by name
stream = summary.get_stream_by_name('MyDevice')
XDFStreamInfo¶
Contains metadata for a single stream:
stream_id: Unique stream identifiername: Stream namestream_type: Stream type (EEG, EMG, etc.)channel_count: Number of channelsnominal_srate: Declared sampling rateeffective_srate: Actual measured sampling ratechannel_format: Data format (float32, string, etc.)source_id: Source identifierhostname: Recording machine hostnamesample_count: Number of samplesduration_seconds: Recording durationchannel_labels: List of channel names
Implementation Notes¶
-
String/Marker Streams: Streams with
channel_format='string'are excluded from signal loading but appear in summaries. -
Time Alignment: When loading multiple streams, timestamps are aligned to start at 0.
-
Resampling: Multiple streams with different rates are resampled using linear interpolation to the highest rate.
-
Channel Naming: Channels are prefixed with stream name to avoid conflicts (e.g., "StreamName_ChannelLabel").