logo
  • Install
  • Documentation
  • API Reference
  • Get help
  • Development
v0.24 (devel) v0.23 (stable) v0.22 v0.21 v0.20 v0.19 v0.18 v0.17 v0.16 v0.15 v0.14 v0.13 v0.12 v0.11
  • Tutorials
    • Overview of MEG/EEG analysis with MNE-Python
    • Modifying data in-place
    • Parsing events from raw data
    • The Info data structure
    • Working with sensor locations
    • Configuring MNE-Python
    • Getting started with mne.Report
    • Importing data from MEG devices
    • Importing data from EEG devices
    • Importing data from fNIRS devices
    • Working with CTF data: the Brainstorm auditory dataset
    • The Raw data structure: continuous data
    • Working with events
    • Annotating continuous data
    • Built-in plotting methods for Raw objects
    • Overview of artifact detection
    • Handling bad channels
    • Rejecting bad data spans
    • Background information on filtering
    • Filtering and resampling data
    • Repairing artifacts with regression
    • Repairing artifacts with ICA
    • Background on projectors and projections
    • Repairing artifacts with SSP
    • Setting the EEG reference
    • Extracting and visualizing subject head movement
    • Signal-space separation (SSS) and Maxwell filtering
    • Preprocessing functional near-infrared spectroscopy (fNIRS) data
    • The Epochs data structure: discontinuous data
    • Visualizing epoched data
    • Working with Epoch metadata
    • Auto-generating Epochs metadata
    • Exporting Epochs to Pandas DataFrames
    • Creating epochs of equal length
    • The Evoked data structure: evoked/averaged data
    • Visualizing Evoked data
    • EEG processing and Event Related Potentials (ERPs)
    • Plotting whitened data
    • Frequency and time-frequency sensor analysis
    • Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
    • FreeSurfer MRI reconstruction
    • Source alignment and coordinate frames
    • Head model and forward computation
    • EEG forward operator with a template MRI
    • How MNE uses FreeSurfer’s outputs
    • Editing BEM surfaces in Blender
    • Computing a covariance matrix
    • The SourceEstimate data structure
    • Source localization with equivalent current dipole (ECD) fit
    • Source localization with MNE/dSPM/sLORETA/eLORETA
    • The role of dipole orientations in distributed source localization
    • Computing various MNE solutions
    • Source reconstruction using an LCMV beamformer
    • Visualize source time courses (stcs)
    • EEG source localization given electrode locations on an MRI
    • Brainstorm Elekta phantom dataset tutorial
    • Brainstorm CTF phantom dataset tutorial
    • 4D Neuroimaging/BTi phantom dataset tutorial
    • Statistical inference
    • Visualising statistical significance thresholds on EEG data
    • Non-parametric 1 sample cluster statistic on single trial power
    • Non-parametric between conditions cluster statistic on single trial power
    • Spatiotemporal permutation F-test on full sensor data
    • Permutation t-test on source data with spatio-temporal clustering
    • 2 samples permutation test on source data with spatio-temporal clustering
    • Repeated measures ANOVA on source data with spatio-temporal clustering
    • Mass-univariate twoway repeated measures ANOVA on single trial power
    • Spectro-temporal receptive field (STRF) estimation on continuous data
    • Decoding (MVPA)
    • Working with sEEG data
    • Working with ECoG data
    • Sleep stage classification from polysomnography (PSG) data
    • Creating MNE-Python data structures from scratch
    • Corrupt known signal with point spread
    • DICS for power mapping
  • Examples
    • Getting averaging info from .fif files
    • How to use data in neural ensemble (NEO) format
    • Reading/Writing a noise covariance matrix
    • Reading XDF EEG data
    • Generate simulated evoked data
    • Generate simulated raw data
    • Simulate raw data using subject anatomy
    • Generate simulated source data
    • Define target events based on time lag, plot evoked response
    • Transform EEG data using current source density (CSD)
    • Show EOG artifact timing
    • Find MEG reference channel artifacts
    • Visualise NIRS artifact correction methods
    • Compare the different ICA algorithms in MNE
    • Interpolate bad channels for MEG/EEG channels
    • Maxwell filter data with movement compensation
    • Annotate movement artifacts and reestimate dev_head_t
    • Annotate muscle artifacts
    • Plot sensor denoising using oversampled temporal projection
    • Shifting time-scale in evoked data
    • Remap MEG channel types
    • XDAWN Denoising
    • How to convert 3D electrode positions to a 2D image.
    • Visualize channel over epochs as an image
    • Plotting EEG sensors on the scalp
    • How to plot topomaps the way EEGLAB does
    • Plotting topographic arrowmaps of evoked data
    • Plotting topographic maps of evoked data
    • Whitening evoked data with a noise covariance
    • Plotting sensor layouts of MEG systems
    • Plot the MNE brain and helmet
    • Plotting sensor layouts of EEG systems
    • Plot a cortical parcellation
    • Make figures more publication ready
    • Plot single trial activity, grouped by ROI and sorted by RT
    • Show noise levels from empty room data
    • Sensitivity map of SSP projections
    • Compare evoked responses for different conditions
    • Plot custom topographies for MEG sensors
    • Cross-hemisphere comparison
    • Compute a cross-spectral density (CSD) matrix
    • Compute Power Spectral Density of inverse solution from single epochs
    • Compute power and phase lock in label of the source space
    • Compute source power spectral density (PSD) in a label
    • Compute source power spectral density (PSD) of VectorView and OPM data
    • Compute induced power in the source space with dSPM
    • Temporal whitening with AR model
    • Compute and visualize ERDS maps
    • Explore event-related dynamics for specific frequency bands
    • Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell)
    • Permutation F-test on sensor data with 1D cluster level
    • FDR correction on T-test on sensor data
    • Regression on continuous data (rER[P/F])
    • Permutation T-test on sensor data
    • Analysing continuous features with binning and regression in sensor space
    • Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP)
    • Decoding in time-frequency space using Common Spatial Patterns (CSP)
    • Representational Similarity Analysis
    • Decoding source space data
    • Continuous Target Decoding with SPoC
    • Decoding sensor space data with generalization across time and conditions
    • Analysis of evoked response using ICA and PCA reduction techniques
    • XDAWN Decoding From EEG data
    • Compute effect-matched-spatial filtering (EMS)
    • Linear classifier on sensor data with plot patterns and filters
    • Receptive Field Estimation and Prediction
    • Compute Spectro-Spatial Decomposition (SSD) spatial filters
    • Compute seed-based time-frequency connectivity in sensor space
    • Compute mixed source space connectivity and visualize it using a circular graph
    • Compute coherence in source space using a MNE inverse solution
    • Compute full spectrum source space connectivity between labels
    • Compute envelope correlations in source space
    • Compute envelope correlations in volume source space
    • Compute source space connectivity and visualize it using a circular graph
    • Compute Phase Slope Index (PSI) in source space for a visual stimulus
    • Compute all-to-all connectivity in sensor space
    • Display sensitivity maps for EEG and MEG sensors
    • Generate a left cerebellum volume source space
    • Use source space morphing
    • Compute MNE-dSPM inverse solution on single epochs
    • Compute sLORETA inverse solution on raw data
    • Compute MNE-dSPM inverse solution on evoked data in volume source space
    • Demonstrate impact of whitening on source estimates
    • Source localization with a custom inverse solver
    • Compute source power using DICS beamformer
    • Compute evoked ERS source power using DICS, LCMV beamformer, and dSPM
    • Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method
    • Extracting time course from source_estimate object
    • Generate a functional label from source estimates
    • Extracting the time series of activations in a label
    • Compute sparse inverse solution with mixed norm: MxNE and irMxNE
    • Compute MNE inverse solution on evoked data with a mixed source space
    • Compute source power estimate by projecting the covariance with MNE
    • Morph surface source estimate
    • Morph volumetric source estimate
    • Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
    • Visualize source leakage among labels using a circular graph
    • Plot point-spread functions (PSFs) and cross-talk functions (CTFs)
    • Compute cross-talk functions for LCMV beamformers
    • Compute Rap-Music on evoked data
    • Reading an inverse operator
    • Reading an STC file
    • Compute spatial resolution metrics in source space
    • Compute spatial resolution metrics to compare MEG with EEG+MEG
    • Estimate data SNR using an inverse
    • Computing source space SNR
    • Compute MxNE with time-frequency sparse prior
    • Plotting the full vector-valued MNE solution
    • Brainstorm raw (median nerve) dataset
    • HF-SEF dataset
    • Single trial linear regression analysis with the LIMO dataset
    • Optically pumped magnetometer (OPM) data
    • From raw data to dSPM on SPM Faces dataset
  • Glossary
  • Implementation details
  • Design philosophy
  • Example datasets
  • Command-line tools
  • Migrating from other analysis software
  • The typical M/EEG workflow
  • How to cite MNE-Python
  • Papers citing MNE-Python
On this page
  • References

Note

Click here to download the full example code

Explore event-related dynamics for specific frequency bands¶

The objective is to show you how to explore spectrally localized effects. For this purpose we adapt the method described in 1 and use it on the somato dataset. The idea is to track the band-limited temporal evolution of spatial patterns by using the global field power (GFP).

We first bandpass filter the signals and then apply a Hilbert transform. To reveal oscillatory activity the evoked response is then subtracted from every single trial. Finally, we rectify the signals prior to averaging across trials by taking the magniude of the Hilbert. Then the GFP is computed as described in 2, using the sum of the squares but without normalization by the rank. Baselining is subsequently applied to make the GFP comparable between frequencies. The procedure is then repeated for each frequency band of interest and all GFPs are visualized. To estimate uncertainty, non-parametric confidence intervals are computed as described in 3 across channels.

The advantage of this method over summarizing the Space x Time x Frequency output of a Morlet Wavelet in frequency bands is relative speed and, more importantly, the clear-cut comparability of the spectral decomposition (the same type of filter is used across all bands).

We will use this dataset: Somatosensory

References¶

1

Riitta Hari and Riitta Salmelin. Human cortical oscillations: a neuromagnetic view through the skull. Trends in Neurosciences, 20(1):44–49, 1997. doi:10.1016/S0166-2236(96)10065-5.

2

Denis A. Engemann and Alexandre Gramfort. Automated model selection in covariance estimation and spatial whitening of MEG and EEG signals. NeuroImage, 108:328–342, 2015. doi:10.1016/j.neuroimage.2014.12.040.

3

Bradley Efron and Trevor Hastie. Computer Age Statistical Inference: Algorithms, Evidence, and Data Science. Number 5 in Institute of Mathematical Statistics Monographs. Cambridge University Press, New York, 2016. ISBN 978-1-107-14989-2. URL: https://web.stanford.edu/~hastie/CASI/.

# Authors: Denis A. Engemann <denis.engemann@gmail.com>
#          Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import somato
from mne.baseline import rescale
from mne.stats import bootstrap_confidence_interval

Set parameters

data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
                    'sub-{}_task-{}_meg.fif'.format(subject, task))

# let's explore some frequency bands
iter_freqs = [
    ('Theta', 4, 7),
    ('Alpha', 8, 12),
    ('Beta', 13, 25),
    ('Gamma', 30, 45)
]

We create average power time courses for each frequency band

# set epoching parameters
event_id, tmin, tmax = 1, -1., 3.
baseline = None

# get the header to extract events
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')

frequency_map = list()

for band, fmin, fmax in iter_freqs:
    # (re)load the data to save memory
    raw = mne.io.read_raw_fif(raw_fname)
    raw.pick_types(meg='grad', eog=True)  # we just look at gradiometers
    raw.load_data()

    # bandpass filter
    raw.filter(fmin, fmax, n_jobs=1,  # use more jobs to speed up.
               l_trans_bandwidth=1,  # make sure filter params are the same
               h_trans_bandwidth=1)  # in each band and skip "auto" option.

    # epoch
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline,
                        reject=dict(grad=4000e-13, eog=350e-6),
                        preload=True)
    # remove evoked response
    epochs.subtract_evoked()

    # get analytic signal (envelope)
    epochs.apply_hilbert(envelope=True)
    frequency_map.append(((band, fmin, fmax), epochs.average()))
    del epochs
del raw

Out:

Opening raw data file /home/circleci/mne_data/MNE-somato-data/sub-01/meg/sub-01_task-somato_meg.fif...
    Range : 237600 ... 506999 =    791.189 ...  1688.266 secs
Ready.
111 events found
Event IDs: [1]
Opening raw data file /home/circleci/mne_data/MNE-somato-data/sub-01/meg/sub-01_task-somato_meg.fif...
    Range : 237600 ... 506999 =    791.189 ...  1688.266 secs
Ready.
Reading 0 ... 269399  =      0.000 ...   897.077 secs...
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 4 - 7 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: 1.00 Hz (-6 dB cutoff frequency: 3.50 Hz)
- Upper passband edge: 7.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Filter length: 993 samples (3.307 sec)

Not setting metadata
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Loading data for 111 events and 1202 original time points ...
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
3 bad epochs dropped
Subtracting Evoked from Epochs
    The following channels are not included in the subtraction: EOG 061
[done]
Opening raw data file /home/circleci/mne_data/MNE-somato-data/sub-01/meg/sub-01_task-somato_meg.fif...
    Range : 237600 ... 506999 =    791.189 ...  1688.266 secs
Ready.
Reading 0 ... 269399  =      0.000 ...   897.077 secs...
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 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: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 993 samples (3.307 sec)

Not setting metadata
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Loading data for 111 events and 1202 original time points ...
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
3 bad epochs dropped
Subtracting Evoked from Epochs
    The following channels are not included in the subtraction: EOG 061
[done]
Opening raw data file /home/circleci/mne_data/MNE-somato-data/sub-01/meg/sub-01_task-somato_meg.fif...
    Range : 237600 ... 506999 =    791.189 ...  1688.266 secs
Ready.
Reading 0 ... 269399  =      0.000 ...   897.077 secs...
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 13 - 25 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: 13.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Upper passband edge: 25.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 25.50 Hz)
- Filter length: 993 samples (3.307 sec)

Not setting metadata
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Loading data for 111 events and 1202 original time points ...
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
3 bad epochs dropped
Subtracting Evoked from Epochs
    The following channels are not included in the subtraction: EOG 061
[done]
Opening raw data file /home/circleci/mne_data/MNE-somato-data/sub-01/meg/sub-01_task-somato_meg.fif...
    Range : 237600 ... 506999 =    791.189 ...  1688.266 secs
Ready.
Reading 0 ... 269399  =      0.000 ...   897.077 secs...
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 30 - 45 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: 30.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 29.50 Hz)
- Upper passband edge: 45.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 45.50 Hz)
- Filter length: 993 samples (3.307 sec)

Not setting metadata
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Loading data for 111 events and 1202 original time points ...
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
    Rejecting  epoch based on EOG : ['EOG 061']
3 bad epochs dropped
Subtracting Evoked from Epochs
    The following channels are not included in the subtraction: EOG 061
[done]

Now we can compute the Global Field Power We can track the emergence of spatial patterns compared to baseline for each frequency band, with a bootstrapped confidence interval.

We see dominant responses in the Alpha and Beta bands.

# Helper function for plotting spread
def stat_fun(x):
    """Return sum of squares."""
    return np.sum(x ** 2, axis=0)


# Plot
fig, axes = plt.subplots(4, 1, figsize=(10, 7), sharex=True, sharey=True)
colors = plt.get_cmap('winter_r')(np.linspace(0, 1, 4))
for ((freq_name, fmin, fmax), average), color, ax in zip(
        frequency_map, colors, axes.ravel()[::-1]):
    times = average.times * 1e3
    gfp = np.sum(average.data ** 2, axis=0)
    gfp = mne.baseline.rescale(gfp, times, baseline=(None, 0))
    ax.plot(times, gfp, label=freq_name, color=color, linewidth=2.5)
    ax.axhline(0, linestyle='--', color='grey', linewidth=2)
    ci_low, ci_up = bootstrap_confidence_interval(average.data, random_state=0,
                                                  stat_fun=stat_fun)
    ci_low = rescale(ci_low, average.times, baseline=(None, 0))
    ci_up = rescale(ci_up, average.times, baseline=(None, 0))
    ax.fill_between(times, gfp + ci_up, gfp - ci_low, color=color, alpha=0.3)
    ax.grid(True)
    ax.set_ylabel('GFP')
    ax.annotate('%s (%d-%dHz)' % (freq_name, fmin, fmax),
                xy=(0.95, 0.8),
                horizontalalignment='right',
                xycoords='axes fraction')
    ax.set_xlim(-1000, 3000)

axes.ravel()[-1].set_xlabel('Time [ms]')
time frequency global field power

Out:

Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)
Applying baseline correction (mode: mean)

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

Estimated memory usage: 830 MB

Download Python source code: time_frequency_global_field_power.py

Download Jupyter notebook: time_frequency_global_field_power.ipynb

Gallery generated by Sphinx-Gallery

Compute and visualize ERDS maps Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell)

© Copyright 2012–2021, MNE Developers. Last updated 2021-09-09 20:05 UTC