Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ jobs:
if [[ $(cat $FNAME | grep -x ".*brainstorm.*bst_auditory.*" | wc -l) -gt 0 ]]; then
python -c "import mne; print(mne.datasets.brainstorm.bst_auditory.data_path(update_path=True))" --accept-brainstorm-license;
fi;
if [[ $(cat $FNAME | grep -x ".*brainstorm.*bst_resting.*" | wc -l) -gt 0 ]]; then
python -c "import mne; print(mne.datasets.brainstorm.bst_resting.data_path(update_path=True))" --accept-brainstorm-license;
fi;
if [[ $(cat $FNAME | grep -x ".*brainstorm.*bst_raw.*" | wc -l) -gt 0 ]]; then
python -c "import mne; print(mne.datasets.brainstorm.bst_raw.data_path(update_path=True))" --accept-brainstorm-license;
fi;
Expand Down
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ def reset_warnings(gallery_conf, fname):
'n_parts', 'n_features_new', 'n_components', 'n_labels', 'n_events_in',
'n_splits', 'n_scores', 'n_outputs', 'n_trials', 'n_estimators', 'n_tasks',
'nd_features', 'n_classes', 'n_targets', 'n_slices', 'n_hpi', 'n_fids',
'n_elp', 'n_pts', 'n_tris',
'n_elp', 'n_pts', 'n_tris', 'n_nodes',
# Undocumented (on purpose)
'RawKIT', 'RawEximia', 'RawEGI', 'RawEEGLAB', 'RawEDF', 'RawCTF', 'RawBTi',
'RawBrainVision',
Expand Down
1 change: 1 addition & 0 deletions doc/documentation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,7 @@ There are also **examples**, which contain a short use-case to highlight MNE-fun
auto_examples/connectivity/plot_cwt_sensor_connectivity.rst
auto_examples/connectivity/plot_mixed_source_space_connectivity.rst
auto_examples/connectivity/plot_mne_inverse_coherence_epochs.rst
auto_examples/connectivity/plot_mne_inverse_envelope_correlation.rst
auto_examples/connectivity/plot_mne_inverse_connectivity_spectrum.rst
auto_examples/connectivity/plot_mne_inverse_label_connectivity.rst
auto_examples/connectivity/plot_mne_inverse_psi_visual.rst
Expand Down
4 changes: 3 additions & 1 deletion doc/python_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -793,9 +793,11 @@ Connectivity Estimation
.. autosummary::
:toctree: generated/

degree
envelope_correlation
phase_slope_index
seed_target_indices
spectral_connectivity
phase_slope_index


.. _api_reference_statistics:
Expand Down
2 changes: 2 additions & 0 deletions doc/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Changelog

- Add data fetchers for polysomnography (PSG) recordings from Physionet (:func:`mne.datasets.sleep_physionet.age.fetch_data` and :func:`mne.datasets.sleep_physionet.temazepam.fetch_data`) by `Alex Gramfort`_ and `Joan Massich`_

- Add envelope correlation code in :func:`mne.connectivity.envelope_correlation` by `Denis Engemann`_, `Sheraz Khan`_, and `Eric Larson`_

- Add support for indexing, slicing, and iterating :class:`mne.Annotations` by `Joan Massich`_

- :meth:`mne.io.Raw.plot` now uses the lesser of ``n_channels`` and ``raw.ch_names``, by `Joan Massich`_
Expand Down
105 changes: 105 additions & 0 deletions examples/connectivity/plot_mne_inverse_envelope_correlation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""
=============================================
Compute envelope correlations in source space
=============================================

Compute envelope correlations of orthogonalized activity [1]_ [2]_ in source
space using resting state CTF data.
"""
# sphinx_gallery_thumbnail_number = 2

# Authors: Eric Larson <[email protected]>
# Sheraz Khan <[email protected]>
# Denis Engemann <[email protected]>
#
# License: BSD (3-clause)

Comment thread
larsoner marked this conversation as resolved.
Resolved
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.connectivity import envelope_correlation
from mne.minimum_norm import make_inverse_operator, apply_inverse_epochs
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

data_path = mne.datasets.brainstorm.bst_resting.data_path()
subjects_dir = op.join(data_path, 'subjects')
subject = 'bst_resting'
trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif')
src = op.join(subjects_dir, subject, 'bem', subject + '-oct-6-src.fif')
bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif')
raw_fname = op.join(data_path, 'MEG', 'bst_resting',
'subj002_spontaneous_20111102_01_AUX.ds')

##############################################################################
# Here we do some things in the name of speed, such as crop (which will
# hurt SNR) and downsample. Then we compute SSP projectors and apply them.

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, 60).load_data().pick_types(meg=True, eeg=False).resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw) # compute before band-pass of interest

##############################################################################
# Now we band-pass filter our data and create epochs.

raw.filter(14, 30, n_jobs='cuda')
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
baseline=None, reject=dict(mag=8e-13), preload=True)
del raw

##############################################################################
# Compute the forward and inverse
# -------------------------------

src = mne.read_source_spaces(src)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
inv = make_inverse_operator(epochs.info, fwd, cov)
del fwd, src

##############################################################################
# Compute label time series and do envelope correlation
# -----------------------------------------------------

labels = mne.read_labels_from_annot(subject, 'aparc_sub',
subjects_dir=subjects_dir)
stcs = apply_inverse_epochs(epochs, inv, lambda2=1. / 9., pick_ori='normal')
label_ts = mne.extract_label_time_course(
stcs, labels, inv['src'], return_generator=True)
corr = envelope_correlation(label_ts)
Comment thread
larsoner marked this conversation as resolved.
Resolved

# let's plot this matrix
fig, ax = plt.subplots(figsize=(4, 4))
ax.imshow(corr, cmap='viridis', clim=np.percentile(corr, [5, 95]))
fig.tight_layout()

##############################################################################
# Compute the degree and plot it
# ------------------------------

degree = mne.connectivity.degree(corr, 0.15)
stc = mne.labels_to_stc(labels, degree)
stc = stc.in_label(mne.Label(inv['src'][0]['vertno'], hemi='lh') +
mne.Label(inv['src'][1]['vertno'], hemi='rh'))
brain = stc.plot(
clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot',
subjects_dir=subjects_dir, views='dorsal', hemi='both',
smoothing_steps=25, time_label='Beta band')

##############################################################################
# References
# ----------
# .. [1] Hipp JF, Hawellek DJ, Corbetta M, Siegel M, Engel AK (2012)
# Large-scale cortical correlation structure of spontaneous
# oscillatory activity. Nature Neuroscience 15:884–890
# .. [2] Khan S et al. (2018). Maturation trajectories of cortical
# resting-state networks depend on the mediating frequency band.
# Neuroimage 174:57–68
26 changes: 12 additions & 14 deletions examples/inverse/plot_label_source_activations.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,18 @@
label = mne.read_label(label_fname)

stc_label = stc.in_label(label)
mean = stc.extract_label_time_course(label, src, mode='mean')
mean_flip = stc.extract_label_time_course(label, src, mode='mean_flip')
pca = stc.extract_label_time_course(label, src, mode='pca_flip')

modes = ('mean', 'mean_flip', 'pca_flip')
tcs = dict()
for mode in modes:
tcs[mode] = stc.extract_label_time_course(label, src, mode=mode)
print("Number of vertices : %d" % len(stc_label.data))

# View source activations
plt.figure()
plt.plot(1e3 * stc_label.times, stc_label.data.T, 'k', linewidth=0.5)
h0, = plt.plot(1e3 * stc_label.times, mean.T, 'r', linewidth=3)
h1, = plt.plot(1e3 * stc_label.times, mean_flip.T, 'g', linewidth=3)
h2, = plt.plot(1e3 * stc_label.times, pca.T, 'b', linewidth=3)
plt.legend([h0, h1, h2], ['mean', 'mean flip', 'PCA flip'])
plt.xlabel('Time (ms)')
plt.ylabel('Source amplitude')
plt.title('Activations in Label : %s' % label)
plt.show()
fig, ax = plt.subplots(1)
t = 1e3 * stc_label.times
ax.plot(t, stc_label.data.T, 'k', linewidth=0.5)
for mode, tc in tcs.items():
ax.plot(t, tc[0], linewidth=3, label=str(mode))
ax.legend(loc='upper right')
ax.set(xlabel='Time (ms)', ylabel='Source amplitude',
title='Activations in Label : %s' % label)
3 changes: 2 additions & 1 deletion mne/connectivity/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Spectral and effective connectivity measures."""

from .utils import seed_target_indices
from .utils import seed_target_indices, degree
from .spectral import spectral_connectivity
from .effective import phase_slope_index
from .envelope import envelope_correlation
100 changes: 100 additions & 0 deletions mne/connectivity/envelope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Authors: Eric Larson <[email protected]>
# Sheraz Khan <[email protected]>
# Denis Engemann <[email protected]>
#
# License: BSD (3-clause)

import numpy as np

from ..filter import next_fast_len
from ..utils import _validate_type


def envelope_correlation(data, combine='median'):
"""Compute the envelope correlation.

Parameters
----------
data : array-like, shape=(n_epochs, n_signals, n_times) | generator
The data from which to compute connectivity.
The array-like object can also be a list/generator of array,
each with shape (n_signals, n_times). If it's float data,
the Hilbert transform will be applied; if it's complex data,
it's assumed the Hilbert has already been applied.
combine : 'median' | None
How to combine correlation estimates across epochs.
Default is 'median'. Can be None to return without combining.

Returns
-------
corr : ndarray, shape ([n_epochs, ]n_nodes, n_nodes)
The pairwise orthogonal envelope correlations.
This matrix is symmetric. If combine is None, the array
with have three dimensions, the first of which is ``n_epochs``.

Notes
-----
This function computes the power envelope correlation between
orthogonalized signals [1]_ [2]_.

References
----------
.. [1] Hipp JF, Hawellek DJ, Corbetta M, Siegel M, Engel AK (2012)
Large-scale cortical correlation structure of spontaneous
oscillatory activity. Nature Neuroscience 15:884–890
.. [2] Khan S et al. (2018). Maturation trajectories of cortical
resting-state networks depend on the mediating frequency band.
Neuroimage 174:57–68
"""
from scipy.signal import hilbert
corrs = list()
n_nodes = None
_validate_type(combine, (str, None), 'combine')
for epoch_data in data:
if epoch_data.ndim != 2:
raise ValueError('Each entry in data must be 2D, got shape %s'
% (epoch_data.shape,))
this_n_nodes, n_times = epoch_data.shape
if n_nodes is None:
n_nodes = this_n_nodes
if this_n_nodes != n_nodes:
raise ValueError('n_nodes mismatch between epochs, got %s and %s'
% (n_nodes, this_n_nodes))
# Get the complex envelope (allowing complex inputs allows people
# to do raw.apply_hilbert if they want)
if epoch_data.dtype in (np.float32, np.float64):
n_fft = next_fast_len(n_times)
epoch_data = hilbert(epoch_data, N=n_fft, axis=-1)[..., :n_times]
if epoch_data.dtype not in (np.complex64, np.complex128):
raise ValueError('data.dtype must be float or complex, got %s'
% (epoch_data.dtype,))
data_mag = np.abs(epoch_data)
data_conj_scaled = epoch_data.conj()
data_conj_scaled /= data_mag
# subtract means
data_mag_nomean = data_mag - np.mean(data_mag, axis=-1, keepdims=True)
# compute variances using linalg.norm (square, sum, sqrt) since mean=0
data_mag_std = np.linalg.norm(data_mag_nomean, axis=-1)
data_mag_std[data_mag_std == 0] = 1
corr = np.empty((n_nodes, n_nodes))
for li, label_data in enumerate(epoch_data):
label_data_orth = (label_data * data_conj_scaled).imag
label_data_orth -= np.mean(label_data_orth, axis=-1, keepdims=True)
label_data_orth_std = np.linalg.norm(label_data_orth, axis=-1)
label_data_orth_std[label_data_orth_std == 0] = 1
# correlation is dot product divided by variances
corr[li] = np.dot(label_data_orth, data_mag_nomean[li])
corr[li] /= data_mag_std[li]
corr[li] /= label_data_orth_std
# Make it symmetric (it isn't at this point)
corr = np.abs(corr)
corrs.append((corr.T + corr) / 2.)
del corr
if combine is not None:
if combine == 'median':
corr = np.median(corrs, axis=0)
else:
raise ValueError('Unknown combine option %r' % (combine,))
else:
corr = np.array(corrs)
return corr
60 changes: 60 additions & 0 deletions mne/connectivity/tests/test_envelope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Authors: Eric Larson <[email protected]>
# Sheraz Khan <[email protected]>
# Denis Engemann <[email protected]>
#
# License: BSD (3-clause)

import numpy as np
Comment thread
larsoner marked this conversation as resolved.
Resolved
from numpy.testing import assert_allclose
import pytest
from scipy.signal import hilbert

from mne.connectivity import envelope_correlation


def _compute_corrs_orig(data):
# This is the version of the code by Sheraz and Denis.
# For this version (epochs, labels, time) must be -> (labels, time, epochs)
data = np.transpose(data, (1, 2, 0))
corr_mats = np.empty((data.shape[0], data.shape[0], data.shape[2]))
for index, label_data in enumerate(data):
label_data_orth = np.imag(label_data * (data.conj() / np.abs(data)))
label_data_orig = np.abs(label_data)
label_data_cont = np.transpose(
np.dstack((label_data_orig, np.transpose(label_data_orth,
(1, 2, 0)))), (1, 2, 0))
corr_mats[index] = np.array([np.corrcoef(dat)
for dat in label_data_cont])[:, 0, 1:].T
corr_mats = np.transpose(corr_mats, (2, 0, 1))
corr = np.median(np.array([(np.abs(corr_mat) + np.abs(corr_mat).T) / 2.
for corr_mat in corr_mats]), axis=0)
return corr


def test_envelope_correlation():
"""Test the envelope correlation function."""
rng = np.random.RandomState(0)
data = rng.randn(2, 4, 64)
data_hilbert = hilbert(data, axis=-1)
corr_orig = _compute_corrs_orig(data_hilbert)
assert (0 < corr_orig).all()
assert (corr_orig < 1).all()
# using complex data
corr = envelope_correlation(data_hilbert)
assert_allclose(corr, corr_orig)
# do Hilbert internally, and don't combine
corr = envelope_correlation(data, combine=None)
assert corr.shape == (data.shape[0],) + corr_orig.shape
corr = np.median(corr, axis=0)
assert_allclose(corr, corr_orig)
# degenerate
with pytest.raises(ValueError, match='float'):
envelope_correlation(data.astype(int))
with pytest.raises(ValueError, match='entry in data must be 2D'):
envelope_correlation(data[np.newaxis])
with pytest.raises(ValueError, match='n_nodes mismatch'):
envelope_correlation([rng.randn(2, 8), rng.randn(3, 8)])
with pytest.raises(TypeError, match='instance of str or None'):
envelope_correlation(data, 1.)
with pytest.raises(ValueError, match='Unknown combine option'):
envelope_correlation(data, 'foo')
Loading