Repository navigation
[MRG] ENH: Add orthogonal power envelope correlation #5904
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
08c0af4
ENH: Add orthogonal power envelope correlation
larsoner 24c1f09
FIX: Paths, etc.
larsoner bee9dcb
FIX: Memory usage
larsoner 7069c05
FIX: Fix bugs and memory problems, add plot
larsoner bb69db1
FIX: Warning
larsoner 1dc7b37
FIX: Add refs
larsoner 6d29f4b
FIX: Refs
larsoner 510292a
FIX: Style [ci skip]
larsoner f4fb227
ENH: Add combine
larsoner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
examples/connectivity/plot_mne_inverse_envelope_correlation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
|
|
||
| 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) | ||
|
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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
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') | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.