Comprehensive Preprocessing with MNE-based Classes#

This example demonstrates the various preprocessing classes available in Braindecode that wrap MNE-Python functionality. These classes provide a convenient and type-safe way to preprocess EEG data.

# Authors: Bruno Aristimunha <b.aristimunha@gmail.com>
#
# License: BSD (3-clause)

import mne

from braindecode.datasets import MOABBDataset
from braindecode.preprocessing import (
    Anonymize,
    ApplyHilbert,
    Crop,
    Filter,
    Pick,
    Resample,
    SetEEGReference,
    SetMontage,
    preprocess,
)

Load a sample dataset#

We’ll use a small MOABB dataset for demonstration

dataset = MOABBDataset(dataset_name="BNCI2014_001", subject_ids=[1])
  0%|                                              | 0.00/42.8M [00:00<?, ?B/s]
  0%|                                     | 8.19k/42.8M [00:00<12:48, 55.7kB/s]
  0%|                                      | 64.5k/42.8M [00:00<02:54, 244kB/s]
  0%|                                       | 121k/42.8M [00:00<02:19, 305kB/s]
  0%|▏                                      | 193k/42.8M [00:00<01:54, 374kB/s]
  1%|▏                                      | 264k/42.8M [00:00<01:43, 411kB/s]
  1%|▎                                      | 360k/42.8M [00:00<01:26, 491kB/s]
  1%|▍                                      | 488k/42.8M [00:01<01:09, 610kB/s]
  1%|▌                                      | 608k/42.8M [00:01<01:02, 670kB/s]
  2%|▋                                      | 808k/42.8M [00:01<00:47, 878kB/s]
  2%|▉                                    | 1.03M/42.8M [00:01<00:39, 1.07MB/s]
  3%|█▏                                   | 1.34M/42.8M [00:01<00:30, 1.36MB/s]
  4%|█▍                                   | 1.70M/42.8M [00:01<00:24, 1.69MB/s]
  5%|█▉                                   | 2.19M/42.8M [00:01<00:18, 2.17MB/s]
  6%|██▎                                  | 2.70M/42.8M [00:02<00:15, 2.53MB/s]
  8%|██▉                                  | 3.38M/42.8M [00:02<00:12, 3.14MB/s]
  9%|███▍                                 | 3.94M/42.8M [00:02<00:11, 3.32MB/s]
 12%|████▎                                | 4.96M/42.8M [00:02<00:08, 4.38MB/s]
 13%|████▊                                | 5.63M/42.8M [00:02<00:08, 4.41MB/s]
 17%|██████▎                              | 7.25M/42.8M [00:02<00:05, 6.33MB/s]
 21%|███████▊                             | 9.06M/42.8M [00:02<00:04, 8.06MB/s]
 27%|██████████                           | 11.7M/42.8M [00:03<00:02, 10.8MB/s]
 33%|████████████▎                        | 14.3M/42.8M [00:03<00:02, 12.9MB/s]
 43%|████████████████                     | 18.6M/42.8M [00:03<00:01, 17.6MB/s]
 51%|██████████████████▋                  | 21.6M/42.8M [00:03<00:01, 18.5MB/s]
 63%|███████████████████████▍             | 27.1M/42.8M [00:03<00:00, 23.8MB/s]
 75%|███████████████████████████▊         | 32.2M/42.8M [00:03<00:00, 26.8MB/s]
 90%|█████████████████████████████████▍   | 38.7M/42.8M [00:04<00:00, 31.3MB/s]
  0%|                                              | 0.00/42.8M [00:00<?, ?B/s]
100%|██████████████████████████████████████| 42.8M/42.8M [00:00<00:00, 170GB/s]

  0%|                                              | 0.00/43.8M [00:00<?, ?B/s]
  0%|                                      | 16.4k/43.8M [00:00<06:40, 109kB/s]
  0%|                                      | 64.5k/43.8M [00:00<03:05, 235kB/s]
  0%|                                       | 121k/43.8M [00:00<02:26, 299kB/s]
  0%|▏                                      | 193k/43.8M [00:00<01:58, 369kB/s]
  1%|▏                                      | 281k/43.8M [00:00<01:37, 447kB/s]
  1%|▎                                      | 352k/43.8M [00:00<01:34, 458kB/s]
  1%|▍                                      | 472k/43.8M [00:01<01:16, 569kB/s]
  1%|▌                                      | 600k/43.8M [00:01<01:05, 659kB/s]
  2%|▋                                      | 761k/43.8M [00:01<00:54, 788kB/s]
  2%|▊                                      | 952k/43.8M [00:01<00:45, 939kB/s]
  3%|█                                    | 1.22M/43.8M [00:01<00:35, 1.19MB/s]
  3%|█▏                                   | 1.47M/43.8M [00:01<00:31, 1.35MB/s]
  4%|█▌                                   | 1.91M/43.8M [00:01<00:22, 1.82MB/s]
  5%|█▉                                   | 2.22M/43.8M [00:02<00:21, 1.90MB/s]
  7%|██▍                                  | 2.95M/43.8M [00:02<00:14, 2.79MB/s]
  8%|██▉                                  | 3.46M/43.8M [00:02<00:13, 2.96MB/s]
 11%|███▉                                 | 4.71M/43.8M [00:02<00:08, 4.58MB/s]
 14%|█████▏                               | 6.09M/43.8M [00:02<00:06, 5.96MB/s]
 19%|███████▏                             | 8.44M/43.8M [00:02<00:03, 8.86MB/s]
 25%|█████████▏                           | 10.9M/43.8M [00:03<00:02, 11.1MB/s]
 35%|████████████▊                        | 15.1M/43.8M [00:03<00:01, 16.2MB/s]
 45%|████████████████▍                    | 19.5M/43.8M [00:03<00:01, 20.1MB/s]
 59%|█████████████████████▉               | 26.0M/43.8M [00:03<00:00, 26.7MB/s]
 74%|███████████████████████████▍         | 32.5M/43.8M [00:03<00:00, 31.3MB/s]
 89%|████████████████████████████████▉    | 39.0M/43.8M [00:03<00:00, 34.4MB/s]
  0%|                                              | 0.00/43.8M [00:00<?, ?B/s]
100%|██████████████████████████████████████| 43.8M/43.8M [00:00<00:00, 213GB/s]

Signal Processing#

Apply common signal processing operations

# 1. Resample to reduce computational load
print(f"Original sampling frequency: {dataset.datasets[0].raw.info['sfreq']} Hz")
preprocessors_signal = [
    Resample(sfreq=100),  # Downsample to 100 Hz
]
preprocess(dataset, preprocessors_signal)
print(f"After resampling: {dataset.datasets[0].raw.info['sfreq']} Hz")

# 2. Remove power line noise and apply bandpass filter
preprocessors_filtering = [
    Filter(l_freq=4, h_freq=30),  # Bandpass filter 4-30 Hz
]
preprocess(dataset, preprocessors_filtering)
print("Applied bandpass filter 4-30 Hz")
Original sampling frequency: 250.0 Hz
After resampling: 100.0 Hz
Applied bandpass filter 4-30 Hz

Channel Management#

Select and manipulate channels

# 3. Pick only EEG channels
preprocessors_channels = [
    Pick(picks="eeg"),  # Select only EEG channels
]
print(f"Channels before pick: {len(dataset.datasets[0].raw.ch_names)}")
preprocess(dataset, preprocessors_channels)
print(f"Channels after pick: {len(dataset.datasets[0].raw.ch_names)}")

# 4. Rename channels (example - just for demonstration)
original_names = dataset.datasets[0].raw.ch_names[:3]
print(f"Original channel names (first 3): {original_names}")
# Note: We won't actually rename to avoid breaking the example,
# but this is how you would do it:
# preprocessors_rename = [
#     RenameChannels(mapping={'C3': 'C3_renamed', 'C4': 'C4_renamed'}),
# ]
# preprocess(dataset, preprocessors_rename)
Channels before pick: 26
Channels after pick: 22
Original channel names (first 3): ['Fz', 'FC3', 'FC1']

Reference & Montage#

Set reference and channel positions

# 5. Set EEG reference to average
preprocessors_reference = [
    SetEEGReference(ref_channels="average"),
]
preprocess(dataset, preprocessors_reference)
print("Set EEG reference to average")

# 6. Set montage for proper channel positions
montage = mne.channels.make_standard_montage("standard_1020")
preprocessors_montage = [
    SetMontage(montage=montage, match_case=False, on_missing="ignore"),
]
preprocess(dataset, preprocessors_montage)
print(
    f"Set montage, number of positions: {len(dataset.datasets[0].raw.get_montage().get_positions()['ch_pos'])}"
)
Set EEG reference to average
Set montage, number of positions: 22

Data Transformation#

Apply transformations to the data

# 7. Crop data to specific time range
preprocessors_crop = [
    Crop(tmin=0, tmax=60),  # Keep only first 60 seconds
]
print(f"Data duration before crop: {dataset.datasets[0].raw.times[-1]:.1f} s")
preprocess(dataset, preprocessors_crop)
print(f"Data duration after crop: {dataset.datasets[0].raw.times[-1]:.1f} s")
Data duration before crop: 386.9 s
Data duration after crop: 60.0 s

Metadata & Configuration#

Modify metadata and configuration

# 8. Anonymize measurement information
preprocessors_anonymize = [
    Anonymize(),
]
preprocess(dataset, preprocessors_anonymize)
print("Anonymized measurement information")
Anonymized measurement information

Advanced: Envelope Extraction#

Extract signal envelope using Hilbert transform

# 9. Compute envelope (useful for some analyses)
# Note: This modifies the data, so use carefully
preprocessors_envelope = [
    ApplyHilbert(envelope=True),
]
preprocess(dataset, preprocessors_envelope)
print("Computed signal envelope")
Computed signal envelope

Combining Multiple Preprocessing Steps#

You can combine multiple preprocessing steps in a single pipeline

print("\n" + "=" * 60)
print("Complete Preprocessing Pipeline Example")
print("=" * 60)

# Reload dataset for complete pipeline demonstration
dataset_complete = MOABBDataset(dataset_name="BNCI2014_001", subject_ids=[1])

# Set montage first (needed for interpolation)
montage = mne.channels.make_standard_montage("standard_1020")

complete_pipeline = [
    # 1. Set montage
    SetMontage(montage=montage, match_case=False, on_missing="ignore"),
    # 2. Set reference
    SetEEGReference(ref_channels="average"),
    # 3. Bandpass filter
    Filter(l_freq=4, h_freq=30),
    # 4. Downsample
    Resample(sfreq=100),
    # 5. Select only EEG channels
    Pick(picks="eeg"),
    # 6. Crop to region of interest
    Crop(tmin=0, tmax=60),
    # 7. Anonymize
    Anonymize(),
]

print(
    f"Original: {dataset_complete.datasets[0].raw.info['sfreq']} Hz, "
    f"{dataset_complete.datasets[0].raw.times[-1]:.1f} s, "
    f"{len(dataset_complete.datasets[0].raw.ch_names)} channels"
)

preprocess(dataset_complete, complete_pipeline)

print(
    f"After preprocessing: {dataset_complete.datasets[0].raw.info['sfreq']} Hz, "
    f"{dataset_complete.datasets[0].raw.times[-1]:.1f} s, "
    f"{len(dataset_complete.datasets[0].raw.ch_names)} channels"
)

print("\nPreprocessing complete!")
============================================================
Complete Preprocessing Pipeline Example
============================================================
Original: 250.0 Hz, 386.9 s, 26 channels
After preprocessing: 100.0 Hz, 60.0 s, 22 channels

Preprocessing complete!

Summary#

Braindecode provides 45 preprocessing classes that wrap MNE-Python functionality:

Signal Processing: Resample, Filter, NotchFilter, SavgolFilter, ApplyHilbert, Rescale, OversampledTemporalProjection

Channel Management: Pick, PickChannels, PickTypes, DropChannels, AddChannels, CombineChannels, RenameChannels, ReorderChannels, SetChannelTypes, InterpolateBads, InterpolateTo, InterpolateBridgedElectrodes, ComputeBridgedElectrodes, EqualizeChannels

Reference & Montage: SetEEGReference, AddReferenceChannels, SetMontage

SSP Projections: AddProj, ApplyProj, DelProj

Data Transformation: Crop, CropByAnnotations, ComputeCurrentSourceDensity, FixStimArtifact, MaxwellFilter, RealignRaw, RegressArtifact

Artifact Detection & Annotation: AnnotateAmplitude, AnnotateBreak, AnnotateMovement, AnnotateMuscleZscore, AnnotateNan

Metadata & Configuration: Anonymize, SetAnnotations, SetMeasDate, AddEvents, FixMagCoilTypes, ApplyGradientCompensation

See the API documentation for details on each class and their parameters.

Total running time of the script: (0 minutes 24.497 seconds)

Estimated memory usage: 572 MB

Gallery generated by Sphinx-Gallery