Fixed-Length Windows Extraction#

Introduction to Fixed-Length Windows Function#

In many EEG decoding tasks, such as self-supervised pre-training, it is useful to split long continuous recordings into fixed-length, overlapping or non-overlapping windows

The function braindecode.preprocessing.create_fixed_length_windows() provides an easy way to slice a continuous EEG recording into such windows.

This tutorial explains how to use it, what its parameters mean, and how it can be applied to EEG datasets.

Overview of create_fixed_length_windows#

The function:

create_fixed_length_windows(
    concat_ds,
    start_offset_samples=0,
    stop_offset_samples=None,
    window_size_samples=None,
    window_stride_samples=None,
    mapping=None,
    preload=False,
    picks=None,
    reject=None,
    flat=None,
    targets_from='metadata',
    last_target_only=True,
    lazy_metadata=False,
    on_missing='error',
    n_jobs=1,
    verbose="error",
    on_last_window=None,
)

Parameters#

concat_dsConcatDataset
  • A concat of base datasets each holding raw and description.

start_offset_samplesint (default=0)
  • Start offset from beginning of recording in samples.

stop_offset_samplesint or None (default=None)
  • Stop offset from beginning of recording in samples. If None, set to be the end of the recording.

window_size_samplesint or None
  • Window size in samples. If None, set to be the maximum possible window size, ie length of the recording, once offsets are accounted for.

window_stride_samplesint or None
  • Stride between windows in samples. If None, set to be equal to winddow_size_samples, so windows will not overlap.

on_last_window‘overlap’, ‘drop’ or None (keyword-only)
  • What to do with the last window when windows do not equally divide the continuous signal: ‘overlap’ adds a last window that overlaps the previous one, ‘drop’ leaves the incomplete end out. Must be set if window size and stride are not None. It replaces the deprecated drop_last_window (True is ‘drop’, False is ‘overlap’).

mappingdict(str: int) or None
  • Mapping from event description to target value.

preloadbool (default=False)
  • If True, preload the data of the Epochs objects.

picksstr | list | slice | None
  • Channels to include. If None, all available channels are used. See mne.Epochs.

rejectdict or None
  • Epoch rejection parameters based on peak-to-peak amplitude. If None, no rejection is done based on peak-to-peak amplitude. See mne.Epochs.

flatdict or None
  • Epoch rejection parameters based on flatness of signals. If None, no rejection based on flatness is done. See mne.Epochs.

targets_fromstr (default=’metadata’)
  • Choose where to get targets from: either ‘metadata’ or ‘events’

last_target_onlybool (default=True)
  • If True, only use the last target in the window.

lazy_metadatabool (default=False)
  • If True, metadata is not computed immediately, but only when accessed by using the _LazyDataFrame (experimental).

on_missingstr (default=’error’)
  • What to do if one or several event ids are not found in the recording. Valid keys are ‘error’ | ‘warning’ | ‘ignore’. See mne.Epochs.

n_jobsint (default=1)
  • Number of jobs to use to parallelize the windowing.

verbosebool | str | int | None
  • Control verbosity of the logging output when calling mne.Epochs.

Example 1: Basic 2-Second, 50% Overlapping Windows#

from numpy import multiply

from braindecode.datasets import MOABBDataset
from braindecode.preprocessing import (
    Filter,
    Pick,
    Preprocessor,
    create_fixed_length_windows,
    preprocess,
)
# Load the EEG dataset
dataset = MOABBDataset(dataset_name="BNCI2014_001", subject_ids=[1])
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/moabb/datasets/bnci/base.py:456: FutureWarning: Montage name 'standard_1005' is deprecated and will be removed in MNE 1.14. Use 'colin27_1005' instead.
  montage = make_standard_montage("standard_1005")

Preprocessing

preprocessors = [
    Pick(picks="eeg"),
    Preprocessor(lambda data: multiply(data, 1e6)),
    Filter(l_freq=4.0, h_freq=38.0),
]
preprocess(dataset, preprocessors)

# Sampling frequency
sfreq = dataset.datasets[0].raw.info["sfreq"]
/home/runner/work/braindecode/braindecode/braindecode/preprocessing/preprocess.py:80: UserWarning: Preprocessing choices with lambda functions cannot be saved.
  warn("Preprocessing choices with lambda functions cannot be saved.")
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 38 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 4.00
- Lower transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 3.00 Hz)
- Upper passband edge: 38.00 Hz
- Upper transition bandwidth: 9.50 Hz (-6 dB cutoff frequency: 42.75 Hz)
- Filter length: 413 samples (1.652 s)

Create windows

window_size_samples = int(sfreq * 2)  # 2-second windows
window_stride_samples = int(window_size_samples * 0.5)  # 50% overlap

windows_dataset = create_fixed_length_windows(
    concat_ds=dataset,
    start_offset_samples=0,
    stop_offset_samples=None,
    window_size_samples=window_size_samples,
    window_stride_samples=window_stride_samples,
    on_last_window="drop",
    mapping=None,
    preload=True,
    picks="eeg",  # Only EEG channels
    reject=dict(eeg=150.0),  # data are in µV (scaled above): p2p > 150 µV
    flat=None,
    targets_from="metadata",
    last_target_only=True,
    on_missing="warning",
    n_jobs=1,
    verbose="error",
)

# Let's inspect the output to better understand what we created.

# Check how many windows were created
print(f"Number of windows: {len(windows_dataset)}")

# Each window contains EEG data of fixed size
X, y, _ = windows_dataset[0]  # data, target, window indices
print(f"Window data shape: {X.shape}")
print(f"Window label: {y}")
/home/runner/work/braindecode/braindecode/braindecode/preprocessing/windowers.py:186: UserWarning: Using reject or picks or flat or dropping bad windows means mne Epochs are created, which will be substantially slower and may be deprecated in the future.
  warnings.warn(
Number of windows: 4620
Window data shape: (22, 500)
Window label: -1

Working with Targets#

In create_fixed_length_windows, targets can be derived in two ways:

  1. From the recording metadata (e.g., “session”, “condition”). This is the default when targets_from=’metadata’.

  2. From signal channels themselves when targets_from=’channels’, useful for cases like sleep staging where annotations are stored in auxiliary channels.

Additionally:

  • mapping: Optionally map target values (e.g. from “0train” / “1test” to 0 / 1).

  • last_target_only=True (default): If multiple targets are present within a window (as in time-varying labels), use only the final target value in that window.

# Example: mapping session names ("0train" and "1test") to integers. The
# targets come from the description column that ``set_target`` selects.

dataset.set_target("session")
mapping = {"0train": 0, "1test": 1}

windows_dataset = create_fixed_length_windows(
    dataset,
    window_size_samples=window_size_samples,
    window_stride_samples=window_stride_samples,
    on_last_window="drop",
    mapping=mapping,
    preload=True,
)

# View first few targets
print("Targets for first 10 windows:")
print(windows_dataset.get_metadata()["target"][:10])
Targets for first 10 windows:
0    0
1    0
2    0
3    0
4    0
5    0
6    0
7    0
8    0
9    0
Name: target, dtype: int64

Example: Rejecting Windows Based on Amplitude#

You can set rejection criteria to exclude windows with extreme values:

reject_criteria = dict(eeg=150.0)  # 150 µV max peak-to-peak (data are in µV)

windows_with_rejection = create_fixed_length_windows(
    concat_ds=dataset,
    window_size_samples=200,
    window_stride_samples=100,
    reject=reject_criteria,
    on_last_window="drop",
)

print(windows_with_rejection)
/home/runner/work/braindecode/braindecode/braindecode/preprocessing/windowers.py:186: UserWarning: Using reject or picks or flat or dropping bad windows means mne Epochs are created, which will be substantially slower and may be deprecated in the future.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
Using data from preloaded Raw for 966 events and 200 original time points ...
0 bad epochs dropped
/home/runner/work/braindecode/braindecode/braindecode/datasets/base.py:1203: UserWarning: The provided mne.Epochs object does not meet the requirements for fast epoch access. This may lead to slow data loading from disk. Consider preloading the epochs or checking the conditions in WindowsDataset._can_use_fast_get_epoch_from_raw.
  warnings.warn(
<BaseConcatDataset | 12 WindowsDataset(s) | 11592 total samples>
  Sfreq*: 250.0 Hz
  Channels*: 22 (22 EEG)
  Ch. names*: Fz, FC3, FC1, FCz, FC2, FC4, C5, C3, C1, Cz, ... (+12 more)
  Montage*: head
  (* from first recording)
  Description: 12 recordings × 3 columns [subject, session, run]
  Window: 200 samples (0.800 s)
  Targets: 2 unique ({'0train': 5796, '1test': 5796})

Example: Using lazy metadata generation#

For large datasets, it can be faster to generate metadata on-demand:

lazy_windows = create_fixed_length_windows(
    concat_ds=dataset,
    window_size_samples=200,
    window_stride_samples=100,
    on_last_window="drop",
    lazy_metadata=True,
)

print(lazy_windows)
<BaseConcatDataset | 12 EEGWindowsDataset(s) | 11592 total samples>
  Sfreq*: 250.0 Hz
  Channels*: 22 (22 EEG)
  Ch. names*: Fz, FC3, FC1, FCz, FC2, FC4, C5, C3, C1, Cz, ... (+12 more)
  Montage*: head
  (* from first recording)
  Description: 12 recordings × 3 columns [subject, session, run]

Example: Shifted Windows#

You can also create shifted windows by using start_offset_samples or stop_offset_samples. For example, start windowing 500 ms later into the recording.

/home/runner/work/braindecode/braindecode/braindecode/preprocessing/windowers.py:1426: UserWarning: Usage of offset_sample args in create_fixed_length_windows is deprecated and will be removed in future versions. Please use braindecode.preprocessing.preprocess.Preprocessor("crop", tmin, tmax) instead.
  warnings.warn(
Number of shifted windows: 4620

Visualizing the windows#

The figure draws, on the first 10 s of channel Cz in the first run:

  • A, the 2-s windows with 50 % overlap of Example 1. Consecutive windows overlap, so they alternate between two rows;

  • B, the same windows started 0.5 s later, as in the shifted example.

Panel C shows the peak-to-peak amplitude of every 2-s window of that run, taken as the largest over channels, which is the test that reject applies. A window above the dashed 150 µV threshold would be dropped and drawn in vermilion. For this subject no window reaches it, so the rejection examples above keep every window.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.transforms import blended_transform_factory

BLUE, VERMILION, GREY, INK = "#0072B2", "#D55E00", "#7F7F7F", "#14181F"
# MOABB, imported by ``braindecode.datasets``, sets a seaborn style when it is
# imported, so we go back to the matplotlib defaults before our own settings.
plt.rcdefaults()
plt.rcParams.update(
    {
        "figure.facecolor": "white",
        "axes.facecolor": "white",
        "font.family": "sans-serif",
        "font.size": 10,
        "axes.labelsize": 10,
        "axes.titlesize": 10.5,
        "xtick.labelsize": 9,
        "ytick.labelsize": 9,
        "axes.linewidth": 0.8,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "xtick.direction": "out",
        "ytick.direction": "out",
    }
)

raw = dataset.datasets[0].raw
segment_s = 10.0
n_segment = int(segment_s * sfreq)
cz = raw.get_data(picks=["Cz"])[0, :n_segment]
times = np.arange(n_segment) / sfreq
window_s = window_size_samples / sfreq
stride_s = window_stride_samples / sfreq

fig, axes = plt.subplots(3, 1, figsize=(7.5, 6.6))
for ax, (letter, name, offset_s) in zip(
    axes[:2],
    [
        ("A", "2-s windows, 50 % overlap", 0.0),
        ("B", "Shifted by 0.5 s", start_offset_seconds),
    ],
):
    # The trace fills the top of the panel and the windows sit below it.
    ax.plot(times, cz, color=INK, linewidth=0.6)
    low, high = cz.min(), cz.max()
    ax.set_ylim(low - 0.75 * (high - low), high)
    ax.spines["left"].set_bounds(low, high)
    ax.set_yticks([t for t in ax.get_yticks() if low <= t <= high])
    to_axes_y = blended_transform_factory(ax.transData, ax.transAxes)
    starts = np.arange(offset_s, segment_s - window_s + 1e-9, stride_s)
    for i, start in enumerate(starts):
        ax.broken_barh(
            [(start, window_s)],
            (0.04 + 0.14 * (i % 2), 0.1),
            transform=to_axes_y,
            facecolor=BLUE,
            alpha=0.75,
            edgecolor="white",
        )
    ax.set_xlim(0, segment_s)
    ax.set_ylabel("Cz (µV)")
    ax.set_title(f"{letter}  {name}", loc="left", fontweight="bold", color=INK)
axes[1].set_xlabel("Time (s)")

# Peak-to-peak amplitude of each 2-s window, the largest over channels.
data = raw.get_data()
win_starts = np.arange(
    0, data.shape[1] - window_size_samples + 1, window_stride_samples
)
ptp = np.array(
    [np.ptp(data[:, s : s + window_size_samples], axis=1).max() for s in win_starts]
)
rejected = ptp > reject_criteria["eeg"]
ax = axes[2]
ax.scatter(win_starts[~rejected] / sfreq, ptp[~rejected], s=8, color=GREY, linewidths=0)
ax.scatter(win_starts[rejected] / sfreq, ptp[rejected], s=12, color=VERMILION)
ax.axhline(reject_criteria["eeg"], color=GREY, linestyle="--", linewidth=0.9)
ax.text(
    win_starts[-1] / sfreq,
    reject_criteria["eeg"] + 3,
    f"Rejection threshold ({reject_criteria['eeg']:.0f} µV)",
    color=GREY,
    fontsize=8.5,
    ha="right",
    va="bottom",
)
ax.set_ylim(0, 1.2 * max(ptp.max(), reject_criteria["eeg"]))
ax.set_xlim(0, data.shape[1] / sfreq)
ax.set_xlabel("Window start (s)")
ax.set_ylabel("Peak-to-peak (µV)")
ax.set_title(
    f"C  Peak-to-peak amplitude, {rejected.sum()} of {len(ptp)} windows rejected",
    loc="left",
    fontweight="bold",
    color=INK,
)
fig.tight_layout()
plt.show()
A  2-s windows, 50 % overlap, B  Shifted by 0.5 s, C  Peak-to-peak amplitude, 0 of 385 windows rejected

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

Gallery generated by Sphinx-Gallery