Skip to content

Commit 36aeeac

Browse files
committed
Add 0.7
1 parent fb9005f commit 36aeeac

245 files changed

Lines changed: 72765 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

v0.7/.buildinfo

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Sphinx build info version 1
2+
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
3+
config: cb7020c22ee224a00da74b26ee91ab69
4+
tags: 645f666f9bcd5a90fca523b33c5a78b7
Binary file not shown.
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
"""
2+
===============================================================================
3+
Compute mixed source space connectivity and visualize it using a circular graph
4+
===============================================================================
5+
6+
This example computes the all-to-all connectivity between 75 regions in a
7+
mixed source space based on dSPM inverse solutions and a FreeSurfer cortical
8+
parcellation. The connectivity is visualized using a circular graph which
9+
is ordered based on the locations of the regions in the axial plane.
10+
"""
11+
# Author: Annalisa Pascarella <a.pascarella@iac.cnr.it>
12+
#
13+
# License: BSD (3-clause)
14+
15+
import os.path as op
16+
17+
import matplotlib.pyplot as plt
18+
import mne
19+
import numpy as np
20+
from mne import make_forward_solution, setup_source_space, setup_volume_source_space
21+
from mne.datasets import sample
22+
from mne.io import read_raw_fif
23+
from mne.minimum_norm import apply_inverse_epochs, make_inverse_operator
24+
from mne.viz import circular_layout
25+
26+
from mne_connectivity import spectral_connectivity_epochs
27+
from mne_connectivity.viz import plot_connectivity_circle
28+
29+
# Set directories
30+
data_path = sample.data_path()
31+
subject = "sample"
32+
data_dir = op.join(data_path, "MEG", subject)
33+
subjects_dir = op.join(data_path, "subjects")
34+
bem_dir = op.join(subjects_dir, subject, "bem")
35+
36+
# Set file names
37+
fname_aseg = op.join(subjects_dir, subject, "mri", "aseg.mgz")
38+
39+
fname_model = op.join(bem_dir, "%s-5120-bem.fif" % subject)
40+
fname_bem = op.join(bem_dir, "%s-5120-bem-sol.fif" % subject)
41+
42+
fname_raw = op.join(data_dir, "sample_audvis_filt-0-40_raw.fif")
43+
fname_trans = op.join(data_dir, "sample_audvis_raw-trans.fif")
44+
fname_cov = op.join(data_dir, "ernoise-cov.fif")
45+
fname_event = op.join(data_dir, "sample_audvis_filt-0-40_raw-eve.fif")
46+
47+
# List of sub structures we are interested in. We select only the
48+
# sub structures we want to include in the source space
49+
labels_vol = [
50+
"Left-Amygdala",
51+
"Left-Thalamus-Proper",
52+
"Left-Cerebellum-Cortex",
53+
"Brain-Stem",
54+
"Right-Amygdala",
55+
"Right-Thalamus-Proper",
56+
"Right-Cerebellum-Cortex",
57+
]
58+
59+
# Setup a surface-based source space, oct5 is not very dense (just used
60+
# to speed up this example; we recommend oct6 in actual analyses)
61+
src = setup_source_space(
62+
subject, subjects_dir=subjects_dir, spacing="oct5", add_dist=False
63+
)
64+
65+
# Setup a volume source space
66+
# set pos=10.0 for speed, not very accurate; we recommend something smaller
67+
# like 5.0 in actual analyses:
68+
vol_src = setup_volume_source_space(
69+
subject,
70+
mri=fname_aseg,
71+
pos=10.0,
72+
bem=fname_model,
73+
add_interpolator=False, # just for speed, usually use True
74+
volume_label=labels_vol,
75+
subjects_dir=subjects_dir,
76+
)
77+
# Generate the mixed source space
78+
src += vol_src
79+
80+
# Load data
81+
raw = read_raw_fif(fname_raw)
82+
raw.pick_types(meg=True, eeg=False, eog=True, stim=True).load_data()
83+
events = mne.find_events(raw)
84+
noise_cov = mne.read_cov(fname_cov)
85+
86+
# compute the fwd matrix
87+
fwd = make_forward_solution(
88+
raw.info, fname_trans, src, fname_bem, mindist=5.0
89+
) # ignore sources<=5mm from innerskull
90+
del src
91+
92+
# Define epochs for left-auditory condition
93+
event_id, tmin, tmax = 1, -0.2, 0.5
94+
reject = dict(mag=4e-12, grad=4000e-13, eog=150e-6)
95+
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, reject=reject, preload=False)
96+
del raw
97+
98+
# Compute inverse solution and for each epoch
99+
snr = 1.0 # use smaller SNR for raw data
100+
inv_method = "dSPM"
101+
parc = "aparc" # the parcellation to use, e.g., 'aparc' 'aparc.a2009s'
102+
103+
lambda2 = 1.0 / snr**2
104+
105+
# Compute inverse operator
106+
inverse_operator = make_inverse_operator(
107+
epochs.info, fwd, noise_cov, depth=None, fixed=False
108+
)
109+
del fwd
110+
111+
stcs = apply_inverse_epochs(
112+
epochs, inverse_operator, lambda2, inv_method, pick_ori=None, return_generator=True
113+
)
114+
115+
# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
116+
labels_parc = mne.read_labels_from_annot(subject, parc=parc, subjects_dir=subjects_dir)
117+
118+
# Average the source estimates within each label of the cortical parcellation
119+
# and each sub-structure contained in the source space.
120+
# When mode = 'mean_flip', this option is used only for the cortical labels.
121+
src = inverse_operator["src"]
122+
label_ts = mne.extract_label_time_course(
123+
stcs, labels_parc, src, mode="mean_flip", allow_empty=True, return_generator=True
124+
)
125+
126+
# We compute the connectivity in the alpha band and plot it using a circular
127+
# graph layout
128+
fmin = 8.0
129+
fmax = 13.0
130+
sfreq = epochs.info["sfreq"] # the sampling frequency
131+
con = spectral_connectivity_epochs(
132+
label_ts,
133+
method="pli",
134+
mode="multitaper",
135+
sfreq=sfreq,
136+
fmin=fmin,
137+
fmax=fmax,
138+
faverage=True,
139+
mt_adaptive=True,
140+
n_jobs=1,
141+
)
142+
143+
# We create a list of Label containing also the sub structures
144+
labels_aseg = mne.get_volume_labels_from_src(src, subject, subjects_dir)
145+
labels = labels_parc + labels_aseg
146+
147+
# read colors
148+
node_colors = [label.color for label in labels]
149+
150+
# We reorder the labels based on their location in the left hemi
151+
label_names = [label.name for label in labels]
152+
lh_labels = [name for name in label_names if name.endswith("lh")]
153+
rh_labels = [name for name in label_names if name.endswith("rh")]
154+
155+
# Get the y-location of the label
156+
label_ypos_lh = list()
157+
for name in lh_labels:
158+
idx = label_names.index(name)
159+
ypos = np.mean(labels[idx].pos[:, 1])
160+
label_ypos_lh.append(ypos)
161+
try:
162+
idx = label_names.index("Brain-Stem")
163+
except ValueError:
164+
pass
165+
else:
166+
ypos = np.mean(labels[idx].pos[:, 1])
167+
lh_labels.append("Brain-Stem")
168+
label_ypos_lh.append(ypos)
169+
170+
171+
# Reorder the labels based on their location
172+
lh_labels = [label for (yp, label) in sorted(zip(label_ypos_lh, lh_labels))]
173+
174+
# For the right hemi
175+
rh_labels = [
176+
label[:-2] + "rh"
177+
for label in lh_labels
178+
if label != "Brain-Stem" and label[:-2] + "rh" in rh_labels
179+
]
180+
181+
# Save the plot order
182+
node_order = lh_labels[::-1] + rh_labels
183+
184+
node_angles = circular_layout(
185+
label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) // 2]
186+
)
187+
188+
189+
# Plot the graph using node colors from the FreeSurfer parcellation. We only
190+
# show the 300 strongest connections.
191+
conmat = con.get_data(output="dense")[:, :, 0]
192+
fig, ax = plt.subplots(figsize=(8, 8), facecolor="black", subplot_kw=dict(polar=True))
193+
plot_connectivity_circle(
194+
conmat,
195+
label_names,
196+
n_lines=300,
197+
node_angles=node_angles,
198+
node_colors=node_colors,
199+
title="All-to-All Connectivity left-Auditory " "Condition (PLI)",
200+
ax=ax,
201+
)
202+
fig.tight_layout()
203+
204+
###############################################################################
205+
# Save the figure (optional)
206+
# --------------------------
207+
#
208+
# By default matplotlib does not save using the facecolor, even though this was
209+
# set when the figure was generated. If not set via savefig, the labels, title,
210+
# and legend will be cut off from the output png file.
211+
#
212+
# .. code-block:: python
213+
#
214+
# fname_fig = op.join(data_path, 'MEG', 'sample', 'plot_mixed_connect.png')
215+
# fig.savefig(fname_fig, facecolor=fig.get_facecolor())
38.6 KB
Binary file not shown.
Binary file not shown.
Binary file not shown.
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"\n# Compute seed-based time-frequency connectivity in sensor space\n\nComputes the connectivity between a seed-gradiometer close to the visual cortex\nand all other gradiometers. The connectivity is computed in the time-frequency\ndomain using Morlet wavelets and the debiased squared weighted phase lag index\n:footcite:`VinckEtAl2011` is used as connectivity metric.\n"
8+
]
9+
},
10+
{
11+
"cell_type": "code",
12+
"execution_count": null,
13+
"metadata": {
14+
"collapsed": false
15+
},
16+
"outputs": [],
17+
"source": [
18+
"# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\n\nimport mne\nimport numpy as np\nfrom mne import io\nfrom mne.datasets import sample\nfrom mne.time_frequency import AverageTFRArray\n\nfrom mne_connectivity import seed_target_indices, spectral_connectivity_epochs\n\nprint(__doc__)"
19+
]
20+
},
21+
{
22+
"cell_type": "markdown",
23+
"metadata": {},
24+
"source": [
25+
"Set parameters\n\n"
26+
]
27+
},
28+
{
29+
"cell_type": "code",
30+
"execution_count": null,
31+
"metadata": {
32+
"collapsed": false
33+
},
34+
"outputs": [],
35+
"source": [
36+
"data_path = sample.data_path()\nraw_fname = op.join(data_path, \"MEG\", \"sample\", \"sample_audvis_filt-0-40_raw.fif\")\nevent_fname = op.join(data_path, \"MEG\", \"sample\", \"sample_audvis_filt-0-40_raw-eve.fif\")\n\n# Setup for reading the raw data\nraw = io.read_raw_fif(raw_fname)\nevents = mne.read_events(event_fname)\n\n# Add a bad channel\nraw.info[\"bads\"] += [\"MEG 2443\"]\n\n# Pick MEG gradiometers\npicks = mne.pick_types(\n raw.info, meg=\"grad\", eeg=False, stim=False, eog=True, exclude=\"bads\"\n)\n\n# Create epochs for left-visual condition\nevent_id, tmin, tmax = 3, -0.2, 0.5\nepochs = mne.Epochs(\n raw,\n events,\n event_id,\n tmin,\n tmax,\n picks=picks,\n baseline=(None, 0),\n reject=dict(grad=4000e-13, eog=150e-6),\n preload=True,\n)\n\n# Use 'MEG 2343' as seed\nseed_ch = \"MEG 2343\"\npicks_ch_names = [raw.ch_names[i] for i in picks]\n\n# Create seed-target indices for connectivity computation\nseed = picks_ch_names.index(seed_ch)\ntargets = np.arange(len(picks))\nindices = seed_target_indices(seed, targets)\n\n# Define wavelet frequencies and number of cycles\ncwt_freqs = np.arange(7, 30, 2)\ncwt_n_cycles = cwt_freqs / 7.0\n\n# Run the connectivity analysis using 2 parallel jobs\nsfreq = raw.info[\"sfreq\"] # the sampling frequency\ncon = spectral_connectivity_epochs(\n epochs,\n indices=indices,\n method=\"wpli2_debiased\",\n mode=\"cwt_morlet\",\n sfreq=sfreq,\n cwt_freqs=cwt_freqs,\n cwt_n_cycles=cwt_n_cycles,\n n_jobs=1,\n)\ntimes = con.times\nfreqs = con.freqs\n\n# Mark the seed channel with a value of 1.0, so we can see it in the plot\ncon.get_data()[np.where(indices[1] == seed)] = 1.0\n\n# Show topography of connectivity from seed\ntitle = \"WPLI2 - Visual - Seed %s\" % seed_ch\n\nlayout = mne.find_layout(epochs.info, \"meg\") # use full layout\n\n# Note that users of mne < 1.7 should use the `AverageTFR` class\ntfr = AverageTFRArray(epochs.info, con.get_data(), times, freqs, nave=len(epochs))\ntfr.plot_topo(fig_facecolor=\"w\", font_color=\"k\", border=\"k\")"
37+
]
38+
},
39+
{
40+
"cell_type": "markdown",
41+
"metadata": {},
42+
"source": [
43+
"## References\n.. footbibliography::\n\n"
44+
]
45+
}
46+
],
47+
"metadata": {
48+
"kernelspec": {
49+
"display_name": "Python 3",
50+
"language": "python",
51+
"name": "python3"
52+
},
53+
"language_info": {
54+
"codemirror_mode": {
55+
"name": "ipython",
56+
"version": 3
57+
},
58+
"file_extension": ".py",
59+
"mimetype": "text/x-python",
60+
"name": "python",
61+
"nbconvert_exporter": "python",
62+
"pygments_lexer": "ipython3",
63+
"version": "3.10.12"
64+
}
65+
},
66+
"nbformat": 4,
67+
"nbformat_minor": 0
68+
}

0 commit comments

Comments
 (0)