Skip to main content
Ctrl+K
Logo image

Site Navigation

  • Install
  • Documentation
  • API Reference
  • Get help
  • Development

Site Navigation

  • Install
  • Documentation
  • API Reference
  • Get help
  • Development

Section Navigation

  • Tutorials
    • Introductory 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
    • Reading data for different recording systems
      • Importing data from MEG devices
      • Importing data from EEG devices
      • Importing data from fNIRS devices
      • Working with CTF data: the Brainstorm auditory dataset
    • Working with continuous data
      • The Raw data structure: continuous data
      • Working with events
      • Annotating continuous data
      • Built-in plotting methods for Raw objects
    • Preprocessing
      • Overview of artifact detection
      • Handling bad channels
      • Rejecting bad data spans and breaks
      • 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
    • Segmenting continuous data into epochs
      • The Epochs data structure: discontinuous data
      • Regression-based baseline correction
      • Visualizing epoched data
      • Working with Epoch metadata
      • Auto-generating Epochs metadata
      • Exporting Epochs to Pandas DataFrames
      • Divide continuous data into equally-spaced epochs
    • Estimating evoked responses
      • The Evoked data structure: evoked/averaged data
      • Visualizing Evoked data
      • EEG analysis - Event-Related Potentials (ERPs)
      • Plotting whitened data
    • Time-frequency analysis
      • The Spectrum and EpochsSpectrum classes: frequency-domain data
      • Frequency and time-frequency sensor analysis
      • Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
    • Forward models and source spaces
      • FreeSurfer MRI reconstruction
      • Source alignment and coordinate frames
      • Using an automated approach to coregistration
      • Head model and forward computation
      • EEG forward operator with a template MRI
      • How MNE uses FreeSurfer’s outputs
      • Fixing BEM and head surfaces
      • Computing a covariance matrix
    • Source localization and inverses
      • The SourceEstimate data structure
      • Source localization with equivalent current dipole (ECD) fit
      • Source localization with MNE, dSPM, sLORETA, and 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 analysis of sensor data
      • 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
      • Mass-univariate twoway repeated measures ANOVA on single trial power
      • Spatiotemporal permutation F-test on full sensor data
    • Statistical analysis of source estimates
      • 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
    • Machine learning models of neural activity
      • Spectro-temporal receptive field (STRF) estimation on continuous data
      • Decoding (MVPA)
    • Clinical applications
      • Locating intracranial electrode contacts
      • Working with sEEG data
      • Working with ECoG data
      • Sleep stage classification from polysomnography (PSG) data
    • Simulation
      • Creating MNE-Python data structures from scratch
      • Corrupt known signal with point spread
      • DICS for power mapping
  • Examples
    • Input/Output
      • 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
    • Data Simulation
      • Compare simulated and estimated source activity
      • Generate simulated evoked data
      • Generate simulated raw data
      • Simulate raw data using subject anatomy
      • Generate simulated source data
    • Preprocessing
      • Cortical Signal Suppression (CSS) for removal of cortical signals
      • Define target events based on time lag, plot evoked response
      • Identify EEG Electrodes Bridged by too much Gel
      • Transform EEG data using current source density (CSD)
      • Show EOG artifact timing
      • Reduce EOG artifacts through regression
      • 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
      • Removing muscle ICA components
      • Plot sensor denoising using oversampled temporal projection
      • Shifting time-scale in evoked data
      • Remap MEG channel types
      • XDAWN Denoising
    • Visualization
      • How to convert 3D electrode positions to a 2D image
      • Plotting with mne.viz.Brain
      • Visualize channel over epochs as an image
      • Plotting EEG sensors on the scalp
      • 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
    • Time-Frequency Examples
      • 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 vs. Hilbert)
    • Statistics Examples
      • 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
    • Machine Learning (Decoding, Encoding, and MVPA)
      • 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
    • Connectivity Analysis Examples
    • Forward modeling
      • Display sensitivity maps for EEG and MEG sensors
      • Generate a left cerebellum volume source space
      • Use source space morphing
    • Inverse problem and source analysis
      • 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
      • Source localization with a custom inverse solver
      • Compute source level time-frequency timecourses using a DICS beamformer
      • 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
      • Computing source timecourses with an XFit-like multi-dipole model
      • 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
      • Plot point-spread functions (PSFs) for a volume
      • 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
    • Examples on open datasets
      • 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
  • Documentation overview
  • Time-Frequency Examples
  • Explore event-related dynamics for specific frequency bands

Note

Go to the end 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 × Time × 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 matplotlib.pyplot as plt
import numpy as np

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

Set parameters

data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = (data_path / f'sub-{subject}' / 'meg' /
             f'sub-{subject}_task-{task}_meg.fif')

# 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=None,  # 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
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)

[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done 204 out of 204 | elapsed:    2.2s finished
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Using data from preloaded Raw 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)

[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done 204 out of 204 | elapsed:    1.9s finished
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Using data from preloaded Raw 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)

[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done 204 out of 204 | elapsed:    2.0s finished
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Using data from preloaded Raw 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)

[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done 204 out of 204 | elapsed:    1.9s finished
Not setting metadata
111 matching events found
No baseline correction applied
0 projection items activated
Using data from preloaded Raw 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.colormaps['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
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 26.996 seconds)

Estimated memory usage: 824 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

previous

Compute and visualize ERDS maps

next

Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell vs. Hilbert)

On this page
  • References

© Copyright 2012–2023, MNE Developers. Last updated 2023-04-24 18:37 UTC