I am working on the file "0.24/_downloads/87ced9add160fc358769ef662f31e446/45_projectors_background.ipynb".
The first task is:
To remove projectors, there is a corresponding method
:meth:~mne.io.Raw.del_proj that will remove projectors based on their index
within the raw.info['projs'] list. For the special case of replacing the
existing projectors with new ones, use
raw.add_proj(ecg_projs, remove_existing=True).
To see how the ECG projectors affect the measured signal, we can once again
plot the data with and without the projectors applied (though remember that
the :meth:~mne.io.Raw.plot method only temporarily applies the projectors
for visualization, and does not permanently change the underlying data).
We'll compare the mags variable we created above, which had only the
empty room SSP projectors, to the data with both empty room and ECG
projectors:
Can you write Python code for it?

mags_ecg = raw.copy().crop(tmax=2).pick_types(meg='mag')
for data, title in zip([mags, mags_ecg], ['Without', 'With']):
    fig = data.plot(butterfly=True, proj=True)
    fig.subplots_adjust(top=0.9)
    fig.suptitle('{} ECG projector'.format(title), size='xx-large',
                 weight='bold')


I am working on the file "0.24/_downloads/87ced9add160fc358769ef662f31e446/45_projectors_background.ipynb".
The first task is:
What is a projection?
In the most basic terms, a projection is an operation that converts one set
of points into another set of points, where repeating the projection
operation on the resulting points has no effect. To give a simple geometric
example, imagine the point $(3, 2, 5)$ in 3-dimensional space. A
projection of that point onto the $x, y$ plane looks a lot like a
shadow cast by that point if the sun were directly above it:
Can you write Python code for it?

ax = setup_3d_axes()

# plot the vector (3, 2, 5)
origin = np.zeros((3, 1))
point = np.array([[3, 2, 5]]).T
vector = np.hstack([origin, point])
ax.plot(*vector, color='k')
ax.plot(*point, color='k', marker='o')

# project the vector onto the x,y plane and plot it
xy_projection_matrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]])
projected_point = xy_projection_matrix @ point
projected_vector = xy_projection_matrix @ vector
ax.plot(*projected_vector, color='C0')
ax.plot(*projected_point, color='C0', marker='o')

# add dashed arrow showing projection
arrow_coords = np.concatenate([point, projected_point - point]).flatten()
ax.quiver3D(*arrow_coords, length=0.96, arrow_length_ratio=0.1, color='C1',
            linewidth=1, linestyle='dashed')


I am working on the file "0.24/_downloads/87ced9add160fc358769ef662f31e446/45_projectors_background.ipynb".
The first task is:
raw.info['projs'] is an ordinary Python :class:list of
:class:~mne.Projection objects, so you can access individual projectors by
indexing into it. The :class:~mne.Projection object itself is similar to a
Python :class:dict, so you can use its .keys() method to see what
fields it contains (normally you don't need to access its properties
directly, but you can if necessary):
Can you write Python code for it?

first_projector = raw.info['projs'][0]
print(first_projector)
print(first_projector.keys())


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:

Note

If your annotations fall outside the range of data times in the
    `~mne.io.Raw` object, the annotations outside the data range will
    not be added to ``raw.annotations``, and a warning will be issued.

Now that your annotations have been added to a ~mne.io.Raw object,
you can see them when you visualize the ~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
Annotating continuous data
This tutorial describes adding annotations to a ~mne.io.Raw object,
and how annotations are used in later stages of data processing.
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and (since we won't actually analyze the
raw data in this tutorial) cropping the ~mne.io.Raw object to just 60
seconds before loading it into RAM to save memory:
Can you write Python code for it?

import os
from datetime import timedelta
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.crop(tmax=60).load_data()


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
Notice that it is possible to create overlapping annotations, even when they
share the same description. This is not possible when annotating
interactively; click-and-dragging to create a new annotation that overlaps
with an existing annotation with the same description will cause the old and
new annotations to be merged.
Individual annotations can be accessed by indexing an
~mne.Annotations object, and subsets of the annotations can be
achieved by either slicing or indexing with a list, tuple, or array of
indices:
Can you write Python code for it?

print(raw.annotations[0])       # just the first annotation
print(raw.annotations[:2])      # the first two annotations
print(raw.annotations[(3, 2)])  # the fourth and third annotations


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
Reading and writing Annotations to/from a file
~mne.Annotations objects have a :meth:~mne.Annotations.save method
which can write :file:.fif, :file:.csv, and :file:.txt formats (the
format to write is inferred from the file extension in the filename you
provide). There is a corresponding :func:~mne.read_annotations function to
load them from disk:
Can you write Python code for it?

raw.annotations.save('saved-annotations.csv', overwrite=True)
annot_from_file = mne.read_annotations('saved-annotations.csv')
print(annot_from_file)


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
Since the example data comes from a Neuromag system that starts counting
sample numbers before the recording begins, adding my_annot to the
~mne.io.Raw object also involved another automatic change: an offset
equalling the time of the first recorded sample (raw.first_samp /
raw.info['sfreq']) was added to the onset values of each annotation
(see time-as-index for more info on raw.first_samp):
Can you write Python code for it?

time_of_first_sample = raw.first_samp / raw.info['sfreq']
print(my_annot.onset + time_of_first_sample)
print(raw.annotations.onset)


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
The colored rings are clickable, and determine which existing label will be
created by the next click-and-drag operation in the main plot window. New
annotation descriptions can be added by typing the new description,
clicking the :guilabel:Add label button; the new description will be added
to the list of descriptions and automatically selected.
During interactive annotation it is also possible to adjust the start and end
times of existing annotations, by clicking-and-dragging on the left or right
edges of the highlighting rectangle corresponding to that annotation.

Warning

Calling :meth:`~mne.io.Raw.set_annotations` **replaces** any annotations
    currently stored in the `~mne.io.Raw` object, so be careful when
    working with annotations that were created interactively (you could lose
    a lot of work if you accidentally overwrite your interactive
    annotations). A good safeguard is to run
    ``interactive_annot = raw.annotations`` after you finish an interactive
    annotation session, so that the annotations are stored in a separate
    variable outside the `~mne.io.Raw` object.

How annotations affect preprocessing and analysis
You may have noticed that the description for new labels in the annotation
controls window defaults to BAD_. The reason for this is that annotation
is often used to mark bad temporal spans of data (such as movement artifacts
or environmental interference that cannot be removed in other ways such as
projection <tut-projectors-background> or filtering). Several
MNE-Python operations
are "annotation aware" and will avoid using data that is annotated with a
description that begins with "bad" or "BAD"; such operations typically have a
boolean reject_by_annotation parameter. Examples of such operations are
independent components analysis (mne.preprocessing.ICA), functions
for finding heartbeat and blink artifacts
(:func:~mne.preprocessing.find_ecg_events,
:func:~mne.preprocessing.find_eog_events), and creation of epoched...
Can you write Python code for it?

new_annot = mne.Annotations(onset=3.75, duration=0.75, description='AAA')
raw.set_annotations(my_annot + new_annot)
raw.plot(start=2, duration=6)


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
The three annotations appear as differently colored rectangles because they
have different description values (which are printed along the top
edge of the plot area). Notice also that colored spans appear in the small
scroll bar at the bottom of the plot window, making it easy to quickly view
where in a ~mne.io.Raw object the annotations are so you can easily
browse through the data to find and examine them.
Annotating Raw objects interactively
Annotations can also be added to a ~mne.io.Raw object interactively
by clicking-and-dragging the mouse in the plot window. To do this, you must
first enter "annotation mode" by pressing :kbd:a while the plot window is
focused; this will bring up the annotation controls window:
Can you write Python code for it?


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
You can also iterate over the annotations within an ~mne.Annotations
object:
Can you write Python code for it?

for ann in raw.annotations:
    descr = ann['description']
    start = ann['onset']
    end = ann['onset'] + ann['duration']
    print("'{}' goes from {} to {}".format(descr, start, end))


I am working on the file "0.24/_downloads/88563c785f9a977b7ce2000e660aeacf/30_annotate_raw.ipynb".
The first task is:
~mne.Annotations in MNE-Python are a way of storing short strings of
information about temporal spans of a ~mne.io.Raw object. Below the
surface, ~mne.Annotations are list-like <list> objects,
where each element comprises three pieces of information: an onset time
(in seconds), a duration (also in seconds), and a description (a text
string). Additionally, the ~mne.Annotations object itself also keeps
track of orig_time, which is a POSIX timestamp_ denoting a real-world
time relative to which the annotation onsets should be interpreted.
Creating annotations programmatically
If you know in advance what spans of the ~mne.io.Raw object you want
to annotate, ~mne.Annotations can be created programmatically, and
you can even pass lists or arrays to the ~mne.Annotations
constructor to annotate multiple spans at once:
Can you write Python code for it?

my_annot = mne.Annotations(onset=[3, 5, 7],  # in seconds
                           duration=[1, 0.5, 0.25],  # in seconds, too
                           description=['AAA', 'BBB', 'CCC'])
print(my_annot)


I am working on the file "0.24/_downloads/89667e881398db43faecc03a232e53a5/40_whitened.ipynb".
The first task is:
Epochs with whitening
Can you write Python code for it?


I am working on the file "0.24/_downloads/89667e881398db43faecc03a232e53a5/40_whitened.ipynb".
The first task is:
Evoked data with scaled whitening
The :meth:mne.Evoked.plot_white function takes an additional step of
scaling the whitened plots to show how well the assumption of Gaussian
noise is satisfied by the data:
Can you write Python code for it?


I am working on the file "0.24/_downloads/89667e881398db43faecc03a232e53a5/40_whitened.ipynb".
The first task is:
Evoked data with whitening
Can you write Python code for it?

evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.plot(noise_cov=noise_cov, time_unit='s')


I am working on the file "0.24/_downloads/89667e881398db43faecc03a232e53a5/40_whitened.ipynb".
The first task is:
Topographic plot with whitening
Can you write Python code for it?

evoked.comment = 'All trials'
evoked.plot_topo(title='Evoked data')
evoked.plot_topo(noise_cov=noise_cov, title='Whitened evoked data')


I am working on the file "0.24/_downloads/8b7a85d4b98927c93b7d9ca1da8d2ab2/compute_mne_inverse_volume.ipynb".
The first task is:
Plot with nilearn:
Can you write Python code for it?

plot_stat_map(index_img(img, 61), t1_fname, threshold=8.,
              title='%s (t=%.1f s.)' % (method, stc.times[61]))


I am working on the file "0.24/_downloads/8de61cd59c9d83353f96a413e8484686/compute_mne_inverse_raw_in_label.ipynb".
The first task is:
Compute sLORETA inverse solution on raw data
Compute sLORETA inverse solution on raw dataset restricted
to a brain label and stores the solution in stc files for
visualisation.
Can you write Python code for it?

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause

import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse_raw, read_inverse_operator

print(__doc__)

data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name

snr = 1.0  # use smaller SNR for raw data
lambda2 = 1.0 / snr ** 2
method = "sLORETA"  # use sLORETA method (could also be MNE or dSPM)

# Load data
raw = mne.io.read_raw_fif(fname_raw)
inverse_operator = read_inverse_operator(fname_inv)
label = mne.read_label(fname_label)

raw.set_eeg_reference('average', projection=True)  # set average reference.
start, stop = raw.time_as_index([0, 15])  # read the first 15s of data

# Compute inverse solution
stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label,
                        start, stop, pick_ori=None)

# Save result in stc files
stc.save('mne_%s_raw_inverse_%s' % (method, label_name))


I am working on the file "0.24/_downloads/8ea2bfc401dbdff70c284d271d62fa8c/label_from_stc.ipynb".
The first task is:
Generate a functional label from source estimates
Threshold source estimates and produce a functional label. The label
is typically the region of interest that contains high values.
Here we compare the average time course in the anatomical label obtained
by FreeSurfer segmentation and the average time course from the
functional label. As expected the time course in the functional
label yields higher values.
Can you write Python code for it?

# Author: Luke Bloy <luke.bloy@gmail.com>
#         Alex Gramfort <alexandre.gramfort@inria.fr>
# License: BSD-3-Clause

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.minimum_norm import read_inverse_operator, apply_inverse
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'
subject = 'sample'

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Compute a label/ROI based on the peak power between 80 and 120 ms.
# The label bankssts-lh is used for the comparison.
aparc_label_name = 'bankssts-lh'
tmin, tmax = 0.080, 0.120

# Load data
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']  # get the source space

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method,
                    pick_ori='normal')

# Make an STC in the time interval of interest and take the mean
stc_mean = stc.copy().crop(tmin, tmax).mean()

# use the stc_mean to generate a functional label
# region growing is halted at 60% of the peak value within the
# anatomical label / ROI specified by aparc_label_name
label = mne.read_labels_from_annot(subject, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=aparc_label_name)[0]
stc_mean_label = stc_mean.in_label(label)
data = np.abs(stc_mean_label.data)
stc_mean_label.data[data < 0.6 * np.max(data)] = 0.

# 8.5% of original source space vertices were omitted during forward
# calculation, suppress the warning here with verbose='error'
func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True,
                                  subjects_dir=subjects_dir, connected=True,
                                 ...


I am working on the file "0.24/_downloads/8ea2bfc401dbdff70c284d271d62fa8c/label_from_stc.ipynb".
The first task is:
plot the time courses....
Can you write Python code for it?

plt.figure()
plt.plot(1e3 * stc_anat_label.times, pca_anat, 'k',
         label='Anatomical %s' % aparc_label_name)
plt.plot(1e3 * stc_func_label.times, pca_func, 'b',
         label='Functional %s' % aparc_label_name)
plt.legend()
plt.show()


I am working on the file "0.24/_downloads/8fc13fc21872d78f6b3678c81e192a76/decoding_xdawn_eeg.ipynb".
The first task is:
The patterns_ attribute of a fitted Xdawn instance (here from the last
cross-validation fold) can be used for visualization.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=len(event_id), ncols=n_filter,
                         figsize=(n_filter, len(event_id) * 2))
fitted_xdawn = clf.steps[0][1]
info = create_info(epochs.ch_names, 1, epochs.get_channel_types())
info.set_montage(epochs.get_montage())
for ii, cur_class in enumerate(sorted(event_id)):
    cur_patterns = fitted_xdawn.patterns_[cur_class]
    pattern_evoked = EvokedArray(cur_patterns[:n_filter].T, info, tmin=0)
    pattern_evoked.plot_topomap(
        times=np.arange(n_filter),
        time_format='Component %d' if ii == 0 else '', colorbar=False,
        show_names=False, axes=axes[ii], show=False)
    axes[ii, 0].set(ylabel=cur_class)
fig.tight_layout(h_pad=1.0, w_pad=1.0, pad=0.1)


I am working on the file "0.24/_downloads/8fc13fc21872d78f6b3678c81e192a76/decoding_xdawn_eeg.ipynb".
The first task is:
XDAWN Decoding From EEG data
ERP decoding with Xdawn :footcite:RivetEtAl2009,RivetEtAl2011. For each event
type, a set of spatial Xdawn filters are trained and applied on the signal.
Channels are concatenated and rescaled to create features vectors that will be
fed into a logistic regression.
Can you write Python code for it?

# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD-3-Clause

import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import MinMaxScaler

from mne import io, pick_types, read_events, Epochs, EvokedArray, create_info
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.decoding import Vectorizer

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.24/_downloads/8fdd7a9ad9a4bab4331f7c5da5e3bb1a/define_target_events.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'

#   Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.read_events(event_fname)

#   Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
include = []  # or stim channels ['STI 014']
raw.info['bads'] += ['EEG 053']  # bads

# pick MEG channels
picks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=True,
                       include=include, exclude='bads')


I am working on the file "0.24/_downloads/8fdd7a9ad9a4bab4331f7c5da5e3bb1a/define_target_events.ipynb".
The first task is:
View evoked response
Can you write Python code for it?

times = 1e3 * epochs.times  # time in milliseconds
title = 'Evoked response followed by %s button press'

fig, axes = plt.subplots(2, 1)
early.plot(axes=axes[0], time_unit='s')
axes[0].set(title=title % 'late', ylabel='Evoked field (fT)')
late.plot(axes=axes[1], time_unit='s')
axes[1].set(title=title % 'early', ylabel='Evoked field (fT)')
plt.show()


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:

Warning

Be careful when concatenating :class:`~mne.io.Raw` objects from different
    recordings, especially when saving: :meth:`~mne.io.Raw.append` only
    preserves the ``info`` attribute of the initial :class:`~mne.io.Raw`
    object (the one outside the :meth:`~mne.io.Raw.append` method call).

Extracting data from Raw objects
So far we've been looking at ways to modify a :class:~mne.io.Raw object.
This section shows how to extract the data from a :class:~mne.io.Raw object
into a :class:NumPy array <numpy.ndarray>, for analysis or plotting using
functions outside of MNE-Python. To select portions of the data,
:class:~mne.io.Raw objects can be indexed using square brackets. However,
indexing :class:~mne.io.Raw works differently than indexing a :class:NumPy
array <numpy.ndarray> in two ways:

Along with the requested sample value(s) MNE-Python also returns an array
   of times (in seconds) corresponding to the requested samples. The data
   array and the times array are returned together as elements of a tuple.

The data array will always be 2-dimensional even if you request only a
   single time sample or a single channel.

Extracting data by index
To illustrate the above two points, let's select a couple seconds of data
from the first channel:
Can you write Python code for it?

sampling_freq = raw.info['sfreq']
start_stop_seconds = np.array([11, 13])
start_sample, stop_sample = (start_stop_seconds * sampling_freq).astype(int)
channel_index = 0
raw_selection = raw[channel_index, start_sample:stop_sample]
print(raw_selection)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:

Note

Most of the fields of ``raw.info`` reflect metadata recorded at
    acquisition time, and should not be changed by the user. There are a few
    exceptions (such as ``raw.info['bads']`` and ``raw.info['projs']``), but
    in most cases there are dedicated MNE-Python functions or methods to
    update the :class:`~mne.Info` object safely (such as
    :meth:`~mne.io.Raw.add_proj` to update ``raw.info['projs']``).

Time, sample number, and sample index
.. sidebar:: Sample numbering in VectorView data
For data from VectorView systems, it is important to distinguish *sample
number* from *sample index*. See :term:`first_samp` for more information.

One method of :class:~mne.io.Raw objects that is frequently useful is
:meth:~mne.io.Raw.time_as_index, which converts a time (in seconds) into
the integer index of the sample occurring closest to that time. The method
can also take a list or array of times, and will return an array of indices.
It is important to remember that there may not be a data sample at exactly
the time requested, so the number of samples between time = 1 second and
time = 2 seconds may be different than the number of samples between
time = 2 and time = 3:
Can you write Python code for it?

print(raw.time_as_index(20))
print(raw.time_as_index([20, 30, 40]), '\n')

print(np.diff(raw.time_as_index([1, 2, 3])))


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
As you can see above, :func:~mne.io.read_raw_fif automatically displays
some information about the file it's loading. For example, here it tells us
that there are three "projection items" in the file along with the recorded
data; those are :term:SSP projectors <projector> calculated to remove
environmental noise from the MEG signals, and are discussed in a the tutorial
tut-projectors-background.
In addition to the information displayed during loading, you can
get a glimpse of the basic details of a :class:~mne.io.Raw object by
printing it:
Can you write Python code for it?


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Changing channel name and type
.. sidebar:: Long channel names
Due to limitations in the :file:`.fif` file format (which MNE-Python uses
to save :class:`~mne.io.Raw` objects), channel names are limited to a
maximum of 15 characters.

You may have noticed that the EEG channel names in the sample data are
numbered rather than labelled according to a standard nomenclature such as
the 10-20 <ten_twenty_> or 10-05 <ten_oh_five_> systems, or perhaps it
bothers you that the channel names contain spaces. It is possible to rename
channels using the :meth:~mne.io.Raw.rename_channels method, which takes a
Python dictionary to map old names to new names. You need not rename all
channels at once; provide only the dictionary entries for the channels you
want to rename. Here's a frivolous example:
Can you write Python code for it?

raw.rename_channels({'EOG 061': 'blink detector'})


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Extracting channels by name
The :class:~mne.io.Raw object can also be indexed with the names of
channels instead of their index numbers. You can pass a single string to get
just one channel, or a list of strings to select multiple channels. As with
integer indexing, this will return a tuple of (data_array, times_array)
that can be easily plotted. Since we're plotting 2 channels this time, we'll
add a vertical offset to one channel so it's not plotted right on top
of the other one:
Can you write Python code for it?

channel_names = ['MEG_0712', 'MEG_1022']
two_meg_chans = raw[channel_names, start_sample:stop_sample]
y_offset = np.array([5e-11, 0])  # just enough to separate the channel traces
x = two_meg_chans[1]
y = two_meg_chans[0].T + y_offset
lines = plt.plot(x, y)
plt.legend(lines, channel_names)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Extracting channels by type
There are several ways to select all channels of a given type from a
:class:~mne.io.Raw object. The safest method is to use
:func:mne.pick_types to obtain the integer indices of the channels you
want, then use those indices with the square-bracket indexing method shown
above. The :func:~mne.pick_types function uses the :class:~mne.Info
attribute of the :class:~mne.io.Raw object to determine channel types, and
takes boolean or string parameters to indicate which type(s) to retain. The
meg parameter defaults to True, and all others default to False,
so to get just the EEG channels, we pass eeg=True and meg=False:
Can you write Python code for it?

eeg_channel_indices = mne.pick_types(raw.info, meg=False, eeg=True)
eeg_data, times = raw[eeg_channel_indices]
print(eeg_data.shape)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
If for some reason the channel types in your :class:~mne.io.Raw object are
inaccurate, you can change the type of any channel with the
:meth:~mne.io.Raw.set_channel_types method. The method takes a
:class:dictionary <dict> mapping channel names to types; allowed types are
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, dbs, stim, syst, ecog,
hbo, hbr. A common use case for changing channel type is when using frontal
EEG electrodes as makeshift EOG channels:
Can you write Python code for it?

raw.set_channel_types({'EEG_001': 'eog'})
print(raw.copy().pick_types(meg=False, eog=True).ch_names)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
If you want the array of times, :meth:~mne.io.Raw.get_data has an optional
return_times parameter:
Can you write Python code for it?

data, times = raw.get_data(return_times=True)
print(data.shape)
print(times.shape)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
It is also possible to export the data to a :class:Pandas DataFrame
<pandas.DataFrame> object, and use the saving methods that :mod:Pandas
<pandas> affords. The :class:~mne.io.Raw object's
:meth:~mne.io.Raw.to_data_frame method is similar to
:meth:~mne.io.Raw.get_data in that it has a picks parameter for
restricting which channels are exported, and start and stop
parameters for restricting the time domain. Note that, by default, times will
be converted to milliseconds, rounded to the nearest millisecond, and used as
the DataFrame index; see the scaling_time parameter in the documentation
of :meth:~mne.io.Raw.to_data_frame for more details.
Can you write Python code for it?

sampling_freq = raw.info['sfreq']
start_end_secs = np.array([10, 13])
start_sample, stop_sample = (start_end_secs * sampling_freq).astype(int)
df = raw.to_data_frame(picks=['eeg'], start=start_sample, stop=stop_sample)
# then save using df.to_csv(...), df.to_hdf(...), etc
print(df.head())


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Loading continuous data
.. sidebar:: Datasets in MNE-Python
There are ``data_path`` functions for several example datasets in
MNE-Python (e.g., :func:`mne.datasets.kiloword.data_path`,
:func:`mne.datasets.spm_face.data_path`, etc). All of them will check the
default download location first to see if the dataset is already on your
computer, and only download it if necessary.  The default download
location is also configurable; see the documentation of any of the
``data_path`` functions for more information.

As mentioned in the introductory tutorial <tut-overview>,
MNE-Python data structures are based around
the :file:.fif file format from Neuromag. This tutorial uses an
example dataset <sample-dataset> in :file:.fif format, so here we'll
use the function :func:mne.io.read_raw_fif to load the raw data; there are
reader functions for a wide variety of other data formats
<data-formats> as well.
There are also several other example datasets
<datasets> that can be downloaded with just a few lines
of code. Functions for downloading example datasets are in the
:mod:mne.datasets submodule; here we'll use
:func:mne.datasets.sample.data_path to download the "sample-dataset"
dataset, which contains EEG, MEG, and structural MRI data from one subject
performing an audiovisual experiment. When it's done downloading,
:func:~mne.datasets.sample.data_path will return the folder location where
it put the files; you can navigate there with your file browser if you want
to examine the files yourself. Once we have the file path, we can load the
data with :func:~mne.io.read_raw_fif. This will return a
:class:~mne.io.Raw object, which we'll store in a variable called raw.
Can you write Python code for it?

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Modifying Raw objects
.. sidebar:: len(raw)
Although the :class:`~mne.io.Raw` object underlyingly stores data samples
in a :class:`NumPy array <numpy.ndarray>` of shape (n_channels,
n_timepoints), the :class:`~mne.io.Raw` object behaves differently from
:class:`NumPy arrays <numpy.ndarray>` with respect to the :func:`len`
function. ``len(raw)`` will return the number of timepoints (length along
data axis 1), not the number of channels (length along data axis 0).
Hence in this section you'll see ``len(raw.ch_names)`` to get the number
of channels.

:class:~mne.io.Raw objects have a number of methods that modify the
:class:~mne.io.Raw instance in-place and return a reference to the modified
instance. This can be useful for method chaining_
(e.g., raw.crop(...).pick_channels(...).filter(...).plot())
but it also poses a problem during interactive analysis: if you modify your
:class:~mne.io.Raw object for an exploratory plot or analysis (say, by
dropping some channels), you will then need to re-load the data (and repeat
any earlier processing steps) to undo the channel-dropping and try something
else. For that reason, the examples in this section frequently use the
:meth:~mne.io.Raw.copy method before the other methods being demonstrated,
so that the original :class:~mne.io.Raw object is still available in the
variable raw for use in later examples.
Selecting, dropping, and reordering channels
Altering the channels of a :class:~mne.io.Raw object can be done in several
ways. As a first example, we'll use the :meth:~mne.io.Raw.pick_types method
to restrict the :class:~mne.io.Raw object to just the EEG and EOG channels:
Can you write Python code for it?

eeg_and_eog = raw.copy().pick_types(meg=False, eeg=True, eog=True)
print(len(raw.ch_names), '→', len(eeg_and_eog.ch_names))


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Remember that sample times don't always align exactly with requested tmin
or tmax values (due to sampling), which is why the max values of the
cropped files don't exactly match the requested tmax (see
time-as-index for further details).
If you need to select discontinuous spans of a :class:~mne.io.Raw object —
or combine two or more separate :class:~mne.io.Raw objects — you can use
the :meth:~mne.io.Raw.append method:
Can you write Python code for it?

raw_selection1 = raw.copy().crop(tmin=30, tmax=30.1)     # 0.1 seconds
raw_selection2 = raw.copy().crop(tmin=40, tmax=41.1)     # 1.1 seconds
raw_selection3 = raw.copy().crop(tmin=50, tmax=51.3)     # 1.3 seconds
raw_selection1.append([raw_selection2, raw_selection3])  # 2.5 seconds total
print(raw_selection1.times.min(), raw_selection1.times.max())


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Similar to the :meth:~mne.io.Raw.pick_types method, there is also the
:meth:~mne.io.Raw.pick_channels method to pick channels by name, and a
corresponding :meth:~mne.io.Raw.drop_channels method to remove channels by
name:
Can you write Python code for it?

raw_temp = raw.copy()
print('Number of channels in raw_temp:')
print(len(raw_temp.ch_names), end=' → drop two → ')
raw_temp.drop_channels(['EEG 037', 'EEG 059'])
print(len(raw_temp.ch_names), end=' → pick three → ')
raw_temp.pick_channels(['MEG 1811', 'EEG 017', 'EOG 061'])
print(len(raw_temp.ch_names))


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
Some of the parameters of :func:mne.pick_types accept string arguments as
well as booleans. For example, the meg parameter can take values
'mag', 'grad', 'planar1', or 'planar2' to select only
magnetometers, all gradiometers, or a specific type of gradiometer. See the
docstring of :meth:mne.pick_types for full details.
The Raw.get_data() method
If you only want the data (not the corresponding array of times),
:class:~mne.io.Raw objects have a :meth:~mne.io.Raw.get_data method. Used
with no parameters specified, it will extract all data from all channels, in
a (n_channels, n_timepoints) :class:NumPy array <numpy.ndarray>:
Can you write Python code for it?


data = raw.get_data()
np.save(file='my_data.npy', arr=data)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
The :meth:~mne.io.Raw.get_data method can also be used to extract specific
channel(s) and sample ranges, via its picks, start, and stop
parameters. The picks parameter accepts integer channel indices, channel
names, or channel types, and preserves the requested channel order given as
its picks parameter.
Can you write Python code for it?

first_channel_data = raw.get_data(picks=0)
eeg_and_eog_data = raw.get_data(picks=['eeg', 'eog'])
two_meg_chans_data = raw.get_data(picks=['MEG_0712', 'MEG_1022'],
                                  start=1000, stop=2000)

print(first_channel_data.shape)
print(eeg_and_eog_data.shape)
print(two_meg_chans_data.shape)


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
The Raw data structure: continuous data
This tutorial covers the basics of working with raw EEG/MEG data in Python. It
introduces the :class:~mne.io.Raw data structure in detail, including how to
load, query, subselect, export, and plot data from a :class:~mne.io.Raw
object. For more info on visualization of :class:~mne.io.Raw objects, see
tut-visualize-raw. For info on creating a :class:~mne.io.Raw object
from simulated data in a :class:NumPy array <numpy.ndarray>, see
tut-creating-data-structures.
As usual we'll start by importing the modules we need:
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
import mne


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
This next example replaces spaces in the channel names with underscores,
using a Python dict comprehension_:
Can you write Python code for it?

print(raw.ch_names[-3:])
channel_renaming_dict = {name: name.replace(' ', '_') for name in raw.ch_names}
raw.rename_channels(channel_renaming_dict)
print(raw.ch_names[-3:])


I am working on the file "0.24/_downloads/91078106f2c04f1e09c01a2fa07e9d27/10_raw_overview.ipynb".
The first task is:
You can see that it contains 2 arrays. This combination of data and times
makes it easy to plot selections of raw data (although note that we're
transposing the data array so that each channel is a column instead of a row,
to match what matplotlib expects when plotting 2-dimensional y against
1-dimensional x):
Can you write Python code for it?

x = raw_selection[1]
y = raw_selection[0].T
plt.plot(x, y)


I am working on the file "0.24/_downloads/9363cd44fa61e7532287bca17b028ef6/time_frequency_global_field_power.ipynb".
The first task is:
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
:footcite:HariSalmelin1997 and use it on the somato dataset.
The idea is to track the band-limited temporal evolution
of spatial patterns by using the :term: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 :term:GFP is computed as described in
:footcite:EngemannGramfort2015, using the sum of the
squares but without normalization by the rank.
Baselining is subsequently applied to make the :term:GFP comparable
between frequencies.
The procedure is then repeated for each frequency band of interest and
all :term:GFPs<GFP> are visualized. To estimate uncertainty, non-parametric
confidence intervals are computed as described in :footcite:EfronHastie2016
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: somato-dataset
References
.. footbibliography::
Can you write Python code for it?

# 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


I am working on the file "0.24/_downloads/9363cd44fa61e7532287bca17b028ef6/time_frequency_global_field_power.ipynb".
The first task is:
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.
Can you write Python code for it?

# 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]')


I am working on the file "0.24/_downloads/9363cd44fa61e7532287bca17b028ef6/time_frequency_global_field_power.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

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)
]


I am working on the file "0.24/_downloads/93b9388c9b54989a6ee795fd5dedd153/otp.ipynb".
The first task is:
Plot the phantom data, lowpassed to get rid of high-frequency artifacts.
We also crop to a single 10-second segment for speed.
Notice that there are two large flux jumps on channel 1522 that could
spread to other channels when performing subsequent spatial operations
(e.g., Maxwell filtering, SSP, or ICA).
Can you write Python code for it?

dipole_number = 1
data_path = bst_phantom_elekta.data_path()
raw = read_raw_fif(
    op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif'))
raw.crop(40., 50.).load_data()
order = list(range(160, 170))
raw.copy().filter(0., 40.).plot(order=order, n_channels=10)


I am working on the file "0.24/_downloads/93b9388c9b54989a6ee795fd5dedd153/otp.ipynb".
The first task is:
We can also look at the effect on single-trial phantom localization.
See the tut-brainstorm-elekta-phantom
for more information. Here we use a version that does single-trial
localization across the 17 trials are in our 10-second window:
Can you write Python code for it?

def compute_bias(raw):
    events = find_events(raw, 'STI201', verbose=False)
    events = events[1:]  # first one has an artifact
    tmin, tmax = -0.2, 0.1
    epochs = mne.Epochs(raw, events, dipole_number, tmin, tmax,
                        baseline=(None, -0.01), preload=True, verbose=False)
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=None,
                                   verbose=False)
    cov = mne.compute_covariance(epochs, tmax=0, method='oas',
                                 rank=None, verbose=False)
    idx = epochs.time_as_index(0.036)[0]
    data = epochs.get_data()[:, :, idx].T
    evoked = mne.EvokedArray(data, epochs.info, tmin=0.)
    dip = fit_dipole(evoked, cov, sphere, n_jobs=1, verbose=False)[0]
    actual_pos = mne.dipole.get_phantom_dipoles()[0][dipole_number - 1]
    misses = 1000 * np.linalg.norm(dip.pos - actual_pos, axis=-1)
    return misses

bias = compute_bias(raw)
print('Raw bias: %0.1fmm (worst: %0.1fmm)'
      % (np.mean(bias), np.max(bias)))
bias_clean = compute_bias(raw_clean)
print('OTP bias: %0.1fmm (worst: %0.1fmm)'
      % (np.mean(bias_clean), np.max(bias_clean),))


I am working on the file "0.24/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
Indeed and as the mindful reader already suspected, the same can be said
about vertices. stc.lh_vertno thereby maps to the left and
stc.rh_vertno to the right inflated surface representation of
FreeSurfer.
Relationship to SourceSpaces (src)
As mentioned above, :class:src <mne.SourceSpaces> carries the mapping from
stc to the surface. The surface is built up from a
triangulated mesh <https://en.wikipedia.org/wiki/Surface_triangulation>_
for each hemisphere. Each triangle building up a face consists of 3 vertices.
Since src is a list of two source spaces (left and right hemisphere), we can
access the respective data by selecting the source space first. Faces
building up the left hemisphere can be accessed via src[0]['tris'], where
the index $0$ stands for the left and $1$ for the right
hemisphere.
The values in src[0]['tris'] refer to row indices in src[0]['rr'].
Here we find the actual coordinates of the surface mesh. Hence every index
value for vertices will select a coordinate from here. Furthermore
src[0]['vertno'] stores the same data as stc.lh_vertno,
except when working with sparse solvers such as
:func:mne.inverse_sparse.mixed_norm, as then only a fraction of
vertices actually have non-zero activations.
In other words stc.lh_vertno equals src[0]['vertno'], whereas
stc.rh_vertno equals src[1]['vertno']. Thus the Nth time series in
stc.lh_data corresponds to the Nth value in stc.lh_vertno and
src[0]['vertno'] respectively, which in turn map the time series to a
specific location on the surface, represented as the set of cartesian
coordinates stc.lh_vertno[N] in src[0]['rr'].
Let's obtain the peak amplitude of the data as vertex and time point index
Can you write Python code for it?

peak_vertex, peak_time = stc.get_peak(hemi='lh', vert_as_index=True,
                                      time_as_index=True)


I am working on the file "0.24/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
Load and inspect example data
This data set contains source estimation data from an audio visual task. It
has been mapped onto the inflated cortical surface representation obtained
from FreeSurfer <tut-freesurfer-mne>
using the dSPM method. It highlights a noticeable peak in the auditory
cortices.
Let's see how it looks like.
Can you write Python code for it?

stc = read_source_estimate(fname_stc, subject='sample')

# Define plotting parameters
surfer_kwargs = dict(
    hemi='lh', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
    initial_time=0.09, time_unit='s', size=(800, 800),
    smoothing_steps=5)

# Plot surface
brain = stc.plot(**surfer_kwargs)

# Add title
brain.add_text(0.1, 0.9, 'SourceEstimate', 'title', font_size=16)


I am working on the file "0.24/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
Since we did not change the time representation, only the selected subset of
vertices and hence only the row size of the matrix changed. We can check if
the rows of stc.lh_data and stc.rh_data sum up to the value we had
before.
Can you write Python code for it?

is_equal = stc.lh_data.shape[0] + stc.rh_data.shape[0] == stc.data.shape[0]

print('The number of vertices in stc.lh_data and stc.rh_data do ' +
      ('not ' if not is_equal else '') +
      'sum up to the number of rows in stc.data')


I am working on the file "0.24/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
SourceEstimate (stc)
A source estimate contains the time series of a activations
at spatial locations defined by the source space.
In the context of a FreeSurfer surfaces - which consist of 3D triangulations
- we could call each data point on the inflated brain
representation a vertex . If every vertex represents the spatial location
of a time series, the time series and spatial location can be written into a
matrix, where to each vertex (rows) at multiple time points (columns) a value
can be assigned. This value is the strength of our signal at a given point in
space and time. Exactly this matrix is stored in stc.data.
Let's have a look at the shape
Can you write Python code for it?

shape = stc.data.shape

print('The data has %s vertex locations with %s sample points each.' % shape)


I am working on the file "0.24/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
The :class:SourceEstimate <mne.SourceEstimate> data structure
Source estimates, commonly referred to as STC (Source Time Courses),
are obtained from source localization methods.
Source localization method solve the so-called 'inverse problem'.
MNE provides different methods for solving it:
dSPM, sLORETA, LCMV, MxNE etc.
Source localization consists in projecting the EEG/MEG sensor data into
a 3-dimensional 'source space' positioned in the individual subject's brain
anatomy. Hence the data is transformed such that the recorded time series at
each sensor location maps to time series at each spatial location of the
'source space' where is defined our source estimates.
An STC object contains the amplitudes of the sources over time.
It only stores the amplitudes of activations but
not the locations of the sources. To get access to the locations
you need to have the :class:source space <mne.SourceSpaces>
(often abbreviated src) used to compute the
:class:forward operator <mne.Forward> (often abbreviated fwd).
See tut-forward for more details on forward modeling, and
tut-inverse-methods
for an example of source localization with dSPM, sLORETA or eLORETA.
Source estimates come in different forms:
- :class:`mne.SourceEstimate`: For cortically constrained source spaces.

- :class:`mne.VolSourceEstimate`: For volumetric source spaces

- :class:`mne.VectorSourceEstimate`: For cortically constrained source
  spaces with vector-valued source activations (strength and orientation)

- :class:`mne.MixedSourceEstimate`: For source spaces formed of a
  combination of cortically constrained and volumetric sources.

Note

:class:`(Vector) <mne.VectorSourceEstimate>`
    :class:`SourceEstimate <mne.SourceEstimate>` are surface representations
    mostly used together with `FreeSurfer <tut-freesurfer-mne>`
    surface representations.

Let's get ourselves an idea of what a :class:mne.SourceEstimate really
is. We first set up the environment and load some data:
Can you write Python code for it?

import os

from mne import read_source_estimate
from mne.datasets import sample

print(__doc__)

# Paths to example data
sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')

fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')


I am working on the file "0.24/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
We see that stc carries 7498 time series of 25 samples length. Those time
series belong to 7498 vertices, which in turn represent locations
on the cortical surface. So where do those vertex values come from?
FreeSurfer separates both hemispheres and creates surfaces
representation for left and right hemisphere. Indices to surface locations
are stored in stc.vertices. This is a list with two arrays of integers,
that index a particular vertex of the FreeSurfer mesh. A value of 42 would
hence map to the x,y,z coordinates of the mesh with index 42.
See next section on how to get access to the positions in a
:class:mne.SourceSpaces object.
Since both hemispheres are always represented separately, both attributes
introduced above, can also be obtained by selecting the respective
hemisphere. This is done by adding the correct prefix (lh or rh).
Can you write Python code for it?

shape_lh = stc.lh_data.shape

print('The left hemisphere has %s vertex locations with %s sample points each.'
      % shape_lh)


I am working on the file "0.24/_downloads/98d9662291626be9c938eee7a8fcc9bd/sensor_noise_level.ipynb".
The first task is:
Show noise levels from empty room data
This shows how to use :meth:mne.io.Raw.plot_psd to examine noise levels
of systems. See :footcite:KhanCohen2013 for an example.
Can you write Python code for it?

# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause

import os.path as op
import mne

data_path = mne.datasets.sample.data_path()

raw_erm = mne.io.read_raw_fif(op.join(data_path, 'MEG', 'sample',
                                      'ernoise_raw.fif'), preload=True)


I am working on the file "0.24/_downloads/98d9662291626be9c938eee7a8fcc9bd/sensor_noise_level.ipynb".
The first task is:
We can plot the absolute noise levels:
Can you write Python code for it?

raw_erm.plot_psd(tmax=10., average=True, spatial_colors=False,
                 dB=False, xscale='log')


I am working on the file "0.24/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
Compute a cross-spectral density (CSD) matrix
A cross-spectral density (CSD) matrix is similar to a covariance matrix, but in
the time-frequency domain. It is the first step towards computing
sensor-to-sensor coherence or a DICS beamformer.
This script demonstrates the three methods that MNE-Python provides to compute
the CSD:

Using short-term Fourier transform: :func:mne.time_frequency.csd_fourier
Using a multitaper approach: :func:mne.time_frequency.csd_multitaper
Using Morlet wavelets: :func:mne.time_frequency.csd_morlet
Can you write Python code for it?

# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
# License: BSD-3-Clause

from matplotlib import pyplot as plt

import mne
from mne.datasets import sample
from mne.time_frequency import csd_fourier, csd_multitaper, csd_morlet

print(__doc__)


I am working on the file "0.24/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
Computing CSD matrices using short-term Fourier transform and (adaptive)
multitapers is straightforward:
Can you write Python code for it?

csd_fft = csd_fourier(epochs, fmin=15, fmax=20, n_jobs=n_jobs)
csd_mt = csd_multitaper(epochs, fmin=15, fmax=20, adaptive=True, n_jobs=n_jobs)


I am working on the file "0.24/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
Loading the sample dataset.
Can you write Python code for it?

data_path = sample.data_path()
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)


I am working on the file "0.24/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
The resulting :class:mne.time_frequency.CrossSpectralDensity objects have a
plotting function we can use to compare the results of the different methods.
We're plotting the mean CSD across frequencies.
Can you write Python code for it?

csd_fft.mean().plot()
plt.suptitle('short-term Fourier transform')

csd_mt.mean().plot()
plt.suptitle('adaptive multitapers')

csd_wav.mean().plot()
plt.suptitle('Morlet wavelet transform')


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
:func:~mne.pick_channels_regexp can be especially useful for channels named
according to the 10-20 <ten-twenty_>_ system (e.g., to select all channels
ending in "z" to get the midline, or all channels beginning with "O" to get
the occipital channels). Note that :func:~mne.pick_channels_regexp uses the
Python standard module :mod:re to perform regular expression matching; see
the documentation of the :mod:re module for implementation details.

Warning

Both :func:`~mne.pick_channels` and :func:`~mne.pick_channels_regexp`
   operate on lists of channel names, so they are unaware of which channels
   (if any) have been marked as "bad" in ``info['bads']``. Use caution to
   avoid accidentally selecting bad channels.

Obtaining channel type information
Sometimes it can be useful to know channel type based on its index in the
data array. For this case, use :func:mne.channel_type, which takes
an :class:~mne.Info object and a single integer channel index:
Can you write Python code for it?


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
:func:~mne.pick_types works differently, since channel type cannot always
be reliably determined from channel name alone. Consequently,
:func:~mne.pick_types needs an :class:~mne.Info object instead of just a
list of channel names, and has boolean keyword arguments for each channel
type. Default behavior is to pick only MEG channels (and MEG reference
channels if present) and exclude any channels already marked as "bad" in the
bads field of the :class:~mne.Info object. Therefore, to get all and
only the EEG channel indices (including the "bad" EEG channels) we must
pass meg=False and exclude=[]:
Can you write Python code for it?

print(mne.pick_types(info, meg=False, eeg=True, exclude=[]))


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Alternatively, you can get the indices of all channels of all channel types
present in the data, using :func:~mne.channel_indices_by_type,
which returns a :class:dict with channel types as keys, and lists of
channel indices as values:
Can you write Python code for it?

ch_idx_by_type = mne.channel_indices_by_type(info)
print(ch_idx_by_type.keys())
print(ch_idx_by_type['eog'])


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
As seen in the introductory tutorial <tut-overview>, when a
:class:~mne.io.Raw object is loaded, an :class:~mne.Info object is
created automatically, and stored in the raw.info attribute:
Can you write Python code for it?


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
As you can see, the :class:~mne.Info object keeps track of a lot of
information about:

the recording system (gantry angle, HPI details, sensor digitizations,
  channel names, ...)
the experiment (project name and ID, subject information, recording date,
  experimenter name or ID, ...)
the data (sampling frequency, applied filter frequencies, bad channels,
  projectors, ...)

The complete list of fields is given in :class:the API documentation
<mne.Info>.
Querying the Info object
The fields in a :class:~mne.Info object act like Python :class:dictionary
<dict> keys, using square brackets and strings to access the contents of a
field:
Can you write Python code for it?

print(info.keys())
print()  # insert a blank line
print(info['ch_names'])


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Dropping channels from an Info object
If you want to modify an :class:~mne.Info object by eliminating some of the
channels in it, you can use the :func:mne.pick_info function to pick the
channels you want to keep and omit the rest:
Can you write Python code for it?

print(info['nchan'])
eeg_indices = mne.pick_types(info, meg=False, eeg=True)
print(mne.pick_info(info, eeg_indices)['nchan'])


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Most of the fields contain :class:int, :class:float, or :class:list
data, but the chs field bears special mention: it contains a list of
dictionaries (one :class:dict per channel) containing everything there is
to know about a channel other than the data it recorded. Normally it is not
necessary to dig into the details of the chs field — various MNE-Python
functions can extract the information more cleanly than iterating over the
list of dicts yourself — but it can be helpful to know what is in there. Here
we show the keys for the first channel's :class:dict:
Can you write Python code for it?


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
To obtain several channel types at once, you could embed
:func:~mne.channel_type in a :term:list comprehension, or use the
:meth:~mne.io.Raw.get_channel_types method of a :class:~mne.io.Raw,
:class:~mne.Epochs, or :class:~mne.Evoked instance:
Can you write Python code for it?

picks = (25, 76, 77, 319)
print([mne.channel_type(info, x) for x in picks])
print(raw.get_channel_types(picks=picks))


I am working on the file "0.24/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
We can also get a nice HTML representation in IPython like:
Can you write Python code for it?


I am working on the file "0.24/_downloads/9d142d98d094666b7fd2d94155f8b3ec/decoding_unsupervised_spatial_filter.ipynb".
The first task is:
Analysis of evoked response using ICA and PCA reduction techniques
This example computes PCA and ICA of evoked or epochs data. Then the
PCA / ICA components, a.k.a. spatial filters, are used to transform
the channel data to new sources / virtual channels. The output is
visualized on the average of all the epochs.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Asish Panda <asishrocks95@gmail.com>
#
# License: BSD-3-Clause

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.decoding import UnsupervisedSpatialFilter

from sklearn.decomposition import PCA, FastICA

print(__doc__)

# Preprocess data
data_path = sample.data_path()

# Load and filter data, set up epochs
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.3
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 20, fir_design='firwin')
events = mne.read_events(event_fname)

picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False,
                       exclude='bads')

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=False,
                    picks=picks, baseline=None, preload=True,
                    verbose=False)

X = epochs.get_data()


I am working on the file "0.24/_downloads/9d142d98d094666b7fd2d94155f8b3ec/decoding_unsupervised_spatial_filter.ipynb".
The first task is:
Transform data with PCA computed on the average ie evoked response
Can you write Python code for it?

pca = UnsupervisedSpatialFilter(PCA(30), average=False)
pca_data = pca.fit_transform(X)
ev = mne.EvokedArray(np.mean(pca_data, axis=0),
                     mne.create_info(30, epochs.info['sfreq'],
                                     ch_types='eeg'), tmin=tmin)
ev.plot(show=False, window_title="PCA", time_unit='s')


I am working on the file "0.24/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Compute MNE inverse solution on evoked data with a mixed source space
Create a mixed source space and compute an MNE inverse solution on an evoked
dataset.
Can you write Python code for it?

# Author: Annalisa Pascarella <a.pascarella@iac.cnr.it>
#
# License: BSD-3-Clause

import os.path as op
import matplotlib.pyplot as plt

from nilearn import plotting

import mne
from mne.minimum_norm import make_inverse_operator, apply_inverse

# Set dir
data_path = mne.datasets.sample.data_path()
subject = 'sample'
data_dir = op.join(data_path, 'MEG', subject)
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, subject, 'bem')

# Set file names
fname_mixed_src = op.join(bem_dir, '%s-oct-6-mixed-src.fif' % subject)
fname_aseg = op.join(subjects_dir, subject, 'mri', 'aseg.mgz')

fname_model = op.join(bem_dir, '%s-5120-bem.fif' % subject)
fname_bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % subject)

fname_evoked = data_dir + '/sample_audvis-ave.fif'
fname_trans = data_dir + '/sample_audvis_raw-trans.fif'
fname_fwd = data_dir + '/sample_audvis-meg-oct-6-mixed-fwd.fif'
fname_cov = data_dir + '/sample_audvis-shrunk-cov.fif'


I am working on the file "0.24/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Compute the fwd matrix
Can you write Python code for it?

fwd = mne.make_forward_solution(
    fname_evoked, fname_trans, src, fname_bem,
    mindist=5.0,  # ignore sources<=5mm from innerskull
    meg=True, eeg=False, n_jobs=1)
del src  # save memory

leadfield = fwd['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)
print(f"The fwd source space contains {len(fwd['src'])} spaces and "
      f"{sum(s['nuse'] for s in fwd['src'])} vertices")

# Load data
condition = 'Left Auditory'
evoked = mne.read_evokeds(fname_evoked, condition=condition,
                          baseline=(None, 0))
noise_cov = mne.read_cov(fname_cov)


I am working on the file "0.24/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Get a surface-based source space, here with few source points for speed
in this demonstration, in general you should use oct6 spacing!
Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct5',
                             add_dist=False, subjects_dir=subjects_dir)


I am working on the file "0.24/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Plot the mixed source estimate
Can you write Python code for it?

initial_time = 0.1
stc_vec = apply_inverse(evoked, inverse_operator, lambda2, inv_method,
                        pick_ori='vector')
brain = stc_vec.plot(
    hemi='both', src=inverse_operator['src'], views='coronal',
    initial_time=initial_time, subjects_dir=subjects_dir,
    brain_kwargs=dict(silhouette=True), smoothing_steps=7)


I am working on the file "0.24/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Plot the volume
Can you write Python code for it?

fig = stc.volume().plot(initial_time=initial_time, src=src,
                        subjects_dir=subjects_dir)


I am working on the file "0.24/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Process labels
Average the source estimates within each label of the cortical parcellation
and each sub structure contained in the src space
Can you write Python code for it?

# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels_parc = mne.read_labels_from_annot(
    subject, parc=parc, subjects_dir=subjects_dir)

label_ts = mne.extract_label_time_course(
    [stc], labels_parc, src, mode='mean', allow_empty=True)

# plot the times series of 2 labels
fig, axes = plt.subplots(1)
axes.plot(1e3 * stc.times, label_ts[0][0, :], 'k', label='bankssts-lh')
axes.plot(1e3 * stc.times, label_ts[0][-1, :].T, 'r', label='Brain-stem')
axes.set(xlabel='Time (ms)', ylabel='MNE current (nAm)')
axes.legend()
mne.viz.tight_layout()


I am working on the file "0.24/_downloads/a179627fc73cce931ace004638e9685c/read_inverse.ipynb".
The first task is:
Reading an inverse operator
The inverse operator's source space is shown in 3D.
Can you write Python code for it?

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause

import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator
from mne.viz import set_3d_view

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'

fname_trans = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

inv_fname = data_path
inv_fname += '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

inv = read_inverse_operator(inv_fname)

print("Method: %s" % inv['methods'])
print("fMRI prior: %s" % inv['fmri_prior'])
print("Number of sources: %s" % inv['nsource'])
print("Number of channels: %s" % inv['nchan'])

src = inv['src']  # get the source space

# Get access to the triangulation of the cortex

print("Number of vertices on the left hemisphere: %d" % len(src[0]['rr']))
print("Number of triangles on left hemisphere: %d" % len(src[0]['use_tris']))
print("Number of vertices on the right hemisphere: %d" % len(src[1]['rr']))
print("Number of triangles on right hemisphere: %d" % len(src[1]['use_tris']))


I am working on the file "0.24/_downloads/a3f6a5e6550d5cc477c48007e697532b/ems_filtering.ipynb".
The first task is:
Note that a similar transformation can be applied with compute_ems
However, this function replicates Schurger et al's original paper, and thus
applies the normalization outside a leave-one-out cross-validation, which we
recommend not to do.
Can you write Python code for it?

epochs.equalize_event_counts(event_ids)
X_transform, filters, classes = compute_ems(epochs)


I am working on the file "0.24/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Cleaned data:
Can you write Python code for it?


I am working on the file "0.24/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Cleaned raw data PSD:
Can you write Python code for it?


I am working on the file "0.24/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Cleaned raw data traces:
Can you write Python code for it?


I am working on the file "0.24/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Note that even though standard noise removal has already
been applied to these data, much of the noise in the reference channels
(bottom of the plot) can still be seen in the standard channels.
Can you write Python code for it?

select_picks = np.concatenate(
    (mne.pick_types(raw.info, meg=True)[-32:],
     mne.pick_types(raw.info, meg=False, ref_meg=True)))
plot_kwargs = dict(
    duration=100, order=select_picks, n_channels=len(select_picks),
    scalings={"mag": 8e-13, "ref_meg": 2e-11})
raw.plot(**plot_kwargs)


I am working on the file "0.24/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Read raw data, cropping to 5 minutes to save memory
Can you write Python code for it?

raw_fname = data_path + '/sample_reference_MEG_noise-raw.fif'
raw = io.read_raw_fif(raw_fname).crop(300, 600).load_data()


I am working on the file "0.24/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
The PSD of these data show the noise as clear peaks.
Can you write Python code for it?


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Apply the subset, and check the result
Now we simply need to apply our selection and yield a result. Therefore,
we typically report grand average SNR over the subselection.
In this tutorial we don't verify the presence of a neural response.
This is commonly done in the ASSR literature where SNR is
often lower. An F-test or Hotelling T² would be
appropriate for this purpose.
Can you write Python code for it?

snrs_target = snrs[i_trial_12hz, :, i_bin_12hz][:, picks_roi_vis]
print("sub 2, 12 Hz trials, SNR at 12 Hz")
print(f'average SNR (occipital ROI): {snrs_target.mean()}')


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
As you can easily see there are striking differences between the trials.
Let's verify this using a series of two-tailed paired T-Tests.
Can you write Python code for it?

# Compare 12 Hz and 15 Hz SNR in trials after averaging over channels

tstat_12hz_trial_stim = \
    ttest_rel(res['stim_12hz_snrs_12hz'], res['stim_12hz_snrs_15hz'])
print("12 Hz Trials: 12 Hz SNR is significantly higher than 15 Hz SNR"
      ": t = %.3f, p = %f" % tstat_12hz_trial_stim)

tstat_12hz_trial_1st_harmonic = \
    ttest_rel(res['stim_12hz_snrs_24hz'], res['stim_12hz_snrs_30hz'])
print("12 Hz Trials: 24 Hz SNR is significantly higher than 30 Hz SNR"
      ": t = %.3f, p = %f" % tstat_12hz_trial_1st_harmonic)

tstat_12hz_trial_2nd_harmonic = \
    ttest_rel(res['stim_12hz_snrs_36hz'], res['stim_12hz_snrs_45hz'])
print("12 Hz Trials: 36 Hz SNR is significantly higher than 45 Hz SNR"
      ": t = %.3f, p = %f" % tstat_12hz_trial_2nd_harmonic)

print()
tstat_15hz_trial_stim = \
    ttest_rel(res['stim_15hz_snrs_12hz'], res['stim_15hz_snrs_15hz'])
print("15 Hz trials: 12 Hz SNR is significantly lower than 15 Hz SNR"
      ": t = %.3f, p = %f" % tstat_15hz_trial_stim)

tstat_15hz_trial_1st_harmonic = \
    ttest_rel(res['stim_15hz_snrs_24hz'], res['stim_15hz_snrs_30hz'])
print("15 Hz trials: 24 Hz SNR is significantly lower than 30 Hz SNR"
      ": t = %.3f, p = %f" % tstat_15hz_trial_1st_harmonic)

tstat_15hz_trial_2nd_harmonic = \
    ttest_rel(res['stim_15hz_snrs_36hz'], res['stim_15hz_snrs_45hz'])
print("15 Hz trials: 36 Hz SNR is significantly lower than 45 Hz SNR"
      ": t = %.3f, p = %f" % tstat_15hz_trial_2nd_harmonic)


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Data preprocessing
Due to a generally high SNR in SSVEP/vSSR, typical preprocessing steps
are considered optional. This doesn't mean, that a proper cleaning would not
increase your signal quality!

Raw data have FCz reference, so we will apply common-average rereferencing.

We  will apply a 0.1 highpass filter.

Lastly, we will cut the data in 20 s epochs corresponding to the trials.
Can you write Python code for it?

# Load raw data
data_path = mne.datasets.ssvep.data_path()
bids_fname = data_path + '/sub-02/ses-01/eeg/sub-02_ses-01_task-ssvep_eeg.vhdr'

raw = mne.io.read_raw_brainvision(bids_fname, preload=True, verbose=False)
raw.info['line_freq'] = 50.

# Set montage
montage = mne.channels.make_standard_montage('easycap-M1')
raw.set_montage(montage, verbose=False)

# Set common average reference
raw.set_eeg_reference('average', projection=False, verbose=False)

# Apply bandpass filter
raw.filter(l_freq=0.1, h_freq=None, fir_design='firwin', verbose=False)

# Construct epochs
event_id = {
    '12hz': 255,
    '15hz': 155
}
events, _ = mne.events_from_annotations(raw, verbose=False)
tmin, tmax = -1., 20.  # in s
baseline = None
epochs = mne.Epochs(
    raw, events=events,
    event_id=[event_id['12hz'], event_id['15hz']], tmin=tmin,
    tmax=tmax, baseline=baseline, verbose=False)


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Debriefing
So that's it, we hope you enjoyed our little tour through this example
dataset.
As you could see, frequency-tagging is a very powerful tool that can yield
very high signal to noise ratios and effect sizes that enable you to detect
brain responses even within a single participant and single trials of only
a few seconds duration.
Bonus exercises
For the overly motivated amongst you, let's see what else we can show with
these data.
Using the PSD function as implemented in MNE makes it very easy to change
the amount of data that is actually used in the spectrum
estimation.
Here we employ this to show you some features of frequency
tagging data that you might or might not have already intuitively expected:
Effect of trial duration on SNR
First we will simulate shorter trials by taking only the first x s of our 20s
trials (2, 4, 6, 8, ..., 20 s), and compute the SNR using a FFT window
that covers the entire epoch:
Can you write Python code for it?

stim_bandwidth = .5

# shorten data and welch window
window_lengths = [i for i in range(2, 21, 2)]
window_snrs = [[]] * len(window_lengths)
for i_win, win in enumerate(window_lengths):
    # compute spectrogram
    windowed_psd, windowed_freqs = mne.time_frequency.psd_welch(
        epochs[str(event_id['12hz'])],
        n_fft=int(sfreq * win),
        n_overlap=0, n_per_seg=None,
        tmin=0, tmax=win,
        window='boxcar',
        fmin=fmin, fmax=fmax, verbose=False)
    # define a bandwidth of 1 Hz around stimfreq for SNR computation
    bin_width = windowed_freqs[1] - windowed_freqs[0]
    skip_neighbor_freqs = \
        round((stim_bandwidth / 2) / bin_width - bin_width / 2. - .5) if (
            bin_width < stim_bandwidth) else 0
    n_neighbor_freqs = \
        int((sum((windowed_freqs <= 13) & (windowed_freqs >= 11)
                 ) - 1 - 2 * skip_neighbor_freqs) / 2)
    # compute snr
    windowed_snrs = \
        snr_spectrum(
            windowed_psd,
            noise_n_neighbor_freqs=n_neighbor_freqs if (
                n_neighbor_freqs > 0
            ) else 1,
            noise_skip_neighbor_freqs=skip_neighbor_freqs)
    window_snrs[i_win] = \
        windowed_snrs[
        :, picks_roi_vis,
        np.argmin(
            abs(windowed_freqs - 12.))].mean(axis=1)

fig, ax = plt.subplots(1)
ax.boxplot(window_snrs, labels=window_lengths, vert=True)
ax.set(title='Effect of trial duration on 12 Hz SNR',
       ylabel='Average SNR', xlabel='Trial duration [s]')
ax.axhline(1, ls='--', c='r')
fig.show()


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Frequency analysis
Now we compute the frequency spectrum of the EEG data.
You will already see the peaks at the stimulation frequencies and some of
their harmonics, without any further processing.
The 'classical' PSD plot will be compared to a plot of the SNR spectrum.
SNR will be computed as a ratio of the power in a given frequency bin
to the average power in its neighboring bins.
This procedure has two advantages over using the raw PSD:

it normalizes the spectrum and accounts for 1/f power decay.

power modulations which are not very narrow band will disappear.

Calculate power spectral density (PSD)
The frequency spectrum will be computed using Fast Fourier transform (FFT).
This seems to be common practice in the steady-state literature and is
based on the exact knowledge of the stimulus and the assumed response -
especially in terms of it's stability over time.
For a discussion see e.g.
Bach & Meigen (1999) <https://doi.org/10.1023/A:1002648202420>_
We will exclude the first second of each trial from the analysis:

steady-state response often take a while to stabilize, and the
  transient phase in the beginning can distort the signal estimate.

this section of data is expected to be dominated by responses related to
  the stimulus onset, and we are not interested in this.

In MNE we call plain FFT as a special case of Welch's method, with only a
single Welch window spanning the entire trial and no specific windowing
function (i.e. applying a boxcar window).
Can you write Python code for it?

tmin = 1.
tmax = 20.
fmin = 1.
fmax = 90.
sfreq = epochs.info['sfreq']

psds, freqs = mne.time_frequency.psd_welch(
    epochs,
    n_fft=int(sfreq * (tmax - tmin)),
    n_overlap=0, n_per_seg=None,
    tmin=tmin, tmax=tmax,
    fmin=fmin, fmax=fmax,
    window='boxcar',
    verbose=False)


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
In this tutorial we compute the frequency spectrum and quantify signal-to-noise
ratio (SNR) at a target frequency in EEG data recorded during fast periodic
visual stimulation (FPVS) at 12 Hz and 15 Hz in different trials.
Extracting SNR at stimulation frequency is a simple way to quantify frequency
tagged responses in MEEG (a.k.a. steady state visually evoked potentials,
SSVEP, or visual steady-state responses, vSSR in the visual domain,
or auditory steady-state responses, ASSR in the auditory domain).
For a general introduction to the method see
Norcia et al. (2015) <https://doi.org/10.1167/15.6.4> for the visual domain,
and Picton et al. (2003) <https://doi.org/10.3109/14992020309101316> for
the auditory domain.
Data and outline:
We use a simple example dataset with frequency tagged visual stimulation:
N=2 participants observed checkerboard patterns inverting with a constant
frequency of either 12.0 Hz of 15.0 Hz.
32 channels wet EEG was recorded.
(see ssvep-dataset for more information).
We will visualize both the power-spectral density (PSD) and the SNR
spectrum of the epoched data,
extract SNR at stimulation frequency,
plot the topography of the response,
and statistically separate 12 Hz and 15 Hz responses in the different trials.
Since the evoked response is mainly generated in early visual areas of the
brain the statistical analysis will be carried out on an occipital
ROI.
   :depth: 2
Can you write Python code for it?

# Authors: Dominik Welke <dominik.welke@web.de>
#          Evgenii Kalenkovich <e.kalenkovich@gmail.com>
#
# License: BSD-3-Clause

import matplotlib.pyplot as plt
import mne
import numpy as np
from scipy.stats import ttest_rel


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Get index for the stimulation frequency (12 Hz)
Ideally, there would be a bin with the stimulation frequency exactly in its
center. However, depending on your Spectral decomposition this is not
always the case. We will find the bin closest to it - this one should contain
our frequency tagged response.
Can you write Python code for it?

# find index of frequency bin closest to stimulation frequency
i_bin_12hz = np.argmin(abs(freqs - stim_freq))
# could be updated to support multiple frequencies

# for later, we will already find the 15 Hz bin and the 1st and 2nd harmonic
# for both.
i_bin_24hz = np.argmin(abs(freqs - 24))
i_bin_36hz = np.argmin(abs(freqs - 36))
i_bin_15hz = np.argmin(abs(freqs - 15))
i_bin_30hz = np.argmin(abs(freqs - 30))
i_bin_45hz = np.argmin(abs(freqs - 45))


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Get indices for the different trial types
Can you write Python code for it?

i_trial_12hz = np.where(epochs.events[:, 2] == event_id['12hz'])[0]
i_trial_15hz = np.where(epochs.events[:, 2] == event_id['15hz'])[0]


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Get indices of EEG channels forming the ROI
Can you write Python code for it?

# Define different ROIs
roi_vis = ['POz', 'Oz', 'O1', 'O2', 'PO3', 'PO4', 'PO7',
           'PO8', 'PO9', 'PO10', 'O9', 'O10']  # visual roi

# Find corresponding indices using mne.pick_types()
picks_roi_vis = mne.pick_types(epochs.info, eeg=True, stim=False,
                               exclude='bads', selection=roi_vis)


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Now we call the function to compute our SNR spectrum.
As described above, we have to define two parameters.

how many noise bins do we want?

do we want to skip the n bins directly next to the target bin?

Tweaking these parameters can drastically impact the resulting spectrum,
but mainly if you choose extremes.
E.g. if you'd skip very many neighboring bins, broad band power modulations
(such as the alpha peak) should reappear in the SNR spectrum.
On the other hand, if you skip none you might miss or smear peaks if the
induced power is distributed over two or more frequency bins (e.g. if the
stimulation frequency isn't perfectly constant, or you have very narrow
bins).
Here, we want to compare power at each bin with average power of the
three neighboring bins (on each side) and skip one bin directly next
to it.
Can you write Python code for it?

snrs = snr_spectrum(psds, noise_n_neighbor_freqs=3,
                    noise_skip_neighbor_freqs=1)


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Plot PSD and SNR spectra
Now we will plot grand average PSD (in blue) and SNR (in red) ± sd
for every frequency bin.
PSD is plotted on a log scale.
Can you write Python code for it?

fig, axes = plt.subplots(2, 1, sharex='all', sharey='none', figsize=(8, 5))
freq_range = range(np.where(np.floor(freqs) == 1.)[0][0],
                   np.where(np.ceil(freqs) == fmax - 1)[0][0])

psds_plot = 10 * np.log10(psds)
psds_mean = psds_plot.mean(axis=(0, 1))[freq_range]
psds_std = psds_plot.std(axis=(0, 1))[freq_range]
axes[0].plot(freqs[freq_range], psds_mean, color='b')
axes[0].fill_between(
    freqs[freq_range], psds_mean - psds_std, psds_mean + psds_std,
    color='b', alpha=.2)
axes[0].set(title="PSD spectrum", ylabel='Power Spectral Density [dB]')

# SNR spectrum
snr_mean = snrs.mean(axis=(0, 1))[freq_range]
snr_std = snrs.std(axis=(0, 1))[freq_range]

axes[1].plot(freqs[freq_range], snr_mean, color='r')
axes[1].fill_between(
    freqs[freq_range], snr_mean - snr_std, snr_mean + snr_std,
    color='r', alpha=.2)
axes[1].set(
    title="SNR spectrum", xlabel='Frequency [Hz]',
    ylabel='SNR', ylim=[-2, 30], xlim=[fmin, fmax])
fig.show()


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Topography of the vSSR
But wait...
As described in the intro, we have decided a priori to work with average
SNR over a subset of occipital channels - a visual region of interest (ROI)
- because we expect SNR to be higher on these channels than in other
channels.
Let's check out, whether this was a good decision!
Here we will plot average SNR for each channel location as a topoplot.
Then we will do a simple paired T-test to check, whether average SNRs over
the two sets of channels are significantly different.
Can you write Python code for it?

# get average SNR at 12 Hz for ALL channels
snrs_12hz = snrs[i_trial_12hz, :, i_bin_12hz]
snrs_12hz_chaverage = snrs_12hz.mean(axis=0)

# plot SNR topography
fig, ax = plt.subplots(1)
mne.viz.plot_topomap(snrs_12hz_chaverage, epochs.info, vmin=1., axes=ax)

print("sub 2, 12 Hz trials, SNR at 12 Hz")
print("average SNR (all channels): %f" % snrs_12hz_chaverage.mean())
print("average SNR (occipital ROI): %f" % snrs_target.mean())

tstat_roi_vs_scalp = \
    ttest_rel(snrs_target.mean(axis=1), snrs_12hz.mean(axis=1))
print("12 Hz SNR in occipital ROI is significantly larger than 12 Hz SNR over "
      "all channels: t = %.3f, p = %f" % tstat_roi_vs_scalp)


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
We can see, that 1) this participant indeed exhibits a cluster of channels
with high SNR in the occipital region and 2) that the average SNR over all
channels is smaller than the average of the visual ROI computed above.
The difference is statistically significant. Great!
Such a topography plot can be a nice tool to explore and play with your data
- e.g. you could try how changing the reference will affect the spatial
distribution of SNR values.
However, we also wanted to show this plot to point at a potential
problem with frequency-tagged (or any other brain imaging) data:
there are many channels and somewhere you will likely find some
statistically significant effect.
It is very easy - even unintended - to end up double-dipping or p-hacking.
So if you want to work with an ROI or individual channels, ideally select
them a priori - before collecting or looking at the data - and preregister
this decision so people will believe you.
If you end up selecting an ROI or individual channel for reporting because
this channel or ROI shows an effect, e.g. in an explorative analysis, this
is also fine but make it transparently and correct for multiple comparison.
Statistical separation of 12 Hz and 15 Hz vSSR
After this little detour into open science, let's move on and
do the analyses we actually wanted to do:
We will show that we can easily detect and discriminate the brains responses
in the trials with different stimulation frequencies.
In the frequency and SNR spectrum plot above, we had all trials mixed up.
Now we will extract 12 and 15 Hz SNR in both types of trials individually,
and compare the values with a simple t-test.
We will also extract SNR of the 1st and 2nd harmonic for both stimulation
frequencies. These are often reported as well and can show interesting
interactions.
Can you write Python code for it?

snrs_roi = snrs[:, picks_roi_vis, :].mean(axis=1)

freq_plot = [12, 15, 24, 30, 36, 45]
color_plot = [
    'darkblue', 'darkgreen', 'mediumblue', 'green', 'blue', 'seagreen'
]
xpos_plot = [-5. / 12, -3. / 12, -1. / 12, 1. / 12, 3. / 12, 5. / 12]
fig, ax = plt.subplots()
labels = ['12 Hz trials', '15 Hz trials']
x = np.arange(len(labels))  # the label locations
width = 0.6  # the width of the bars
res = dict()

# loop to plot SNRs at stimulation frequencies and harmonics
for i, f in enumerate(freq_plot):
    # extract snrs
    stim_12hz_tmp = \
        snrs_roi[i_trial_12hz, np.argmin(abs(freqs - f))]
    stim_15hz_tmp = \
        snrs_roi[i_trial_15hz, np.argmin(abs(freqs - f))]
    SNR_tmp = [stim_12hz_tmp.mean(), stim_15hz_tmp.mean()]
    # plot (with std)
    ax.bar(
        x + width * xpos_plot[i], SNR_tmp, width / len(freq_plot),
        yerr=np.std(SNR_tmp),
        label='%i Hz SNR' % f, color=color_plot[i])
    # store results for statistical comparison
    res['stim_12hz_snrs_%ihz' % f] = stim_12hz_tmp
    res['stim_15hz_snrs_%ihz' % f] = stim_15hz_tmp

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('SNR')
ax.set_title('Average SNR at target frequencies')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend(['%i Hz' % f for f in freq_plot], title='SNR at:')
ax.set_ylim([0, 70])
ax.axhline(1, ls='--', c='r')
fig.show()


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
You can see that the peaks at the stimulation frequencies (12 Hz, 15 Hz)
and their harmonics are visible in both plots (just as the line noise at
50 Hz).
Yet, the SNR spectrum shows them more prominently as peaks from a
noisy but more or less constant baseline of SNR = 1.
You can further see that the SNR processing removes any broad-band power
differences (such as the increased power in alpha band around 10 Hz),
and also removes the 1/f decay in the PSD.
Note, that while the SNR plot implies the possibility of values below 0
(mean minus sd) such values do not make sense.
Each SNR value is a ratio of positive PSD values, and the lowest possible PSD
value is 0 (negative Y-axis values in the upper panel only result from
plotting PSD on a log scale).
Hence SNR values must be positive and can minimally go towards 0.
Extract SNR values at the stimulation frequency
Our processing yielded a large array of many SNR values for each trial x
channel x frequency-bin of the PSD array.
For statistical analysis we obviously need to define specific subsets of this
array. First of all, we are only interested in SNR at the stimulation
frequency, but we also want to restrict the analysis to a spatial ROI.
Lastly, answering your interesting research questions will probably rely on
comparing SNR in different trials.
Therefore we will have to find the indices of trials, channels, etc.
Alternatively, one could subselect the trials already at the epoching step,
using MNE's event information, and process different epoch structures
separately.
Let's only have a look at the trials with 12 Hz stimulation, for now.
Can you write Python code for it?

# define stimulation frequency
stim_freq = 12.


I am working on the file "0.24/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
You can see that the signal estimate / our SNR measure increases with the
trial duration.
This should be easy to understand: in longer recordings there is simply
more signal (one second of additional stimulation adds, in our case, 12
cycles of signal) while the noise is (hopefully) stochastic and not locked
to the stimulation frequency.
In other words: with more data the signal term grows faster than the noise
term.
We can further see that the very short trials with FFT windows < 2-3s are not
great - here we've either hit the noise floor and/or the transient response
at the trial onset covers too much of the trial.
Again, this tutorial doesn't statistically test for the presence of a neural
response, but an F-test or Hotelling T² would be appropriate for this
purpose.
Time resolved SNR
..and finally we can trick MNE's PSD implementation to make it a
sliding window analysis and come up with a time resolved SNR measure.
This will reveal whether a participant blinked or scratched their head..
Each of the ten trials is coded with a different color in the plot below.
Can you write Python code for it?

# 3s sliding window
window_length = 4
window_starts = [i for i in range(20 - window_length)]
window_snrs = [[]] * len(window_starts)

for i_win, win in enumerate(window_starts):
    # compute spectrogram
    windowed_psd, windowed_freqs = mne.time_frequency.psd_welch(
        epochs[str(event_id['12hz'])],
        n_fft=int(sfreq * window_length) - 1,
        n_overlap=0, n_per_seg=None,
        window='boxcar',
        tmin=win, tmax=win + window_length,
        fmin=fmin, fmax=fmax,
        verbose=False)
    # define a bandwidth of 1 Hz around stimfreq for SNR computation
    bin_width = windowed_freqs[1] - windowed_freqs[0]
    skip_neighbor_freqs = \
        round((stim_bandwidth / 2) / bin_width - bin_width / 2. - .5) if (
            bin_width < stim_bandwidth) else 0
    n_neighbor_freqs = \
        int((sum((windowed_freqs <= 13) & (windowed_freqs >= 11)
                 ) - 1 - 2 * skip_neighbor_freqs) / 2)
    # compute snr
    windowed_snrs = snr_spectrum(
        windowed_psd,
        noise_n_neighbor_freqs=n_neighbor_freqs if (
            n_neighbor_freqs > 0) else 1,
        noise_skip_neighbor_freqs=skip_neighbor_freqs)
    window_snrs[i_win] = \
        windowed_snrs[:, picks_roi_vis, np.argmin(
            abs(windowed_freqs - 12.))].mean(axis=1)

fig, ax = plt.subplots(1)
colors = plt.get_cmap('Greys')(np.linspace(0, 1, 10))
for i in range(10):
    ax.plot(window_starts, np.array(window_snrs)[:, i], color=colors[i])
ax.set(title='Time resolved 12 Hz SNR - %is sliding window' % window_length,
       ylabel='Average SNR', xlabel='t0 of analysis window [s]')
ax.axhline(1, ls='--', c='r')
ax.legend(['individual trials in greyscale'])
fig.show()


I am working on the file "0.24/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Let's check to make sure everything is aligned.

Note

The most rostral electrode in the temporal lobe is outside the
   fsaverage template brain. This is not ideal but it is the best that
   the linear Talairach transform can accomplish. A more complex
   transform is necessary for more accurate warping, see
   `tut-ieeg-localize`.

Can you write Python code for it?

# compute the transform to head for plotting
trans = mne.channels.compute_native_head_t(montage)
# note that this is the same as:
# ``mne.transforms.invert_transform(
#      mne.transforms.combine_transforms(head_mri_t, mri_mni_t))``

fig = mne.viz.plot_alignment(epochs.info, trans, 'fsaverage',
                             subjects_dir=subjects_dir, show_axes=True,
                             surfaces=['pial', 'head'], coord_frame='mri')


I am working on the file "0.24/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Let's load some sEEG data with channel locations and make epochs.
Can you write Python code for it?

raw = mne.io.read_raw(op.join(misc_path, 'seeg', 'sample_seeg_ieeg.fif'))

events, event_id = mne.events_from_annotations(raw)
epochs = mne.Epochs(raw, events, event_id, detrend=1, baseline=None)
epochs = epochs['Response'][0]  # just process one epoch of data for speed


I am working on the file "0.24/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Next, we'll get the epoch data and plot its amplitude over time.
Can you write Python code for it?


I am working on the file "0.24/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Plot 3D source (brain region) visualization:
By default, stc.plot_3d() <mne.VolSourceEstimate.plot_3d> will show a time
course of the source with the largest absolute value across any time point.
In this example, it is simply the source with the largest raw signal value.
Its location is marked on the brain by a small blue sphere.
Can you write Python code for it?

brain = stc.plot_3d(
    src=vol_src, subjects_dir=subjects_dir,
    view_layout='horizontal', views=['axial', 'coronal', 'sagittal'],
    size=(800, 300), show_traces=0.4, clim=clim,
    add_data_kwargs=dict(colorbar_kwargs=dict(label_font_size=8)))

# You can save a movie like the one on our documentation website with:
# brain.save_movie(time_dilation=3, interpolation='linear', framerate=5,
#                  time_viewer=True, filename='./mne-test-seeg.m4')


I am working on the file "0.24/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Working with sEEG data
MNE-Python supports working with more than just MEG and EEG data. Here we show
some of the functions that can be used to facilitate working with
stereoelectroencephalography (sEEG) data.
This example shows how to use:

sEEG data
channel locations in MNI space
projection into a volume

Note that our sample sEEG electrodes are already assumed to be in MNI
space. If you want to map positions from your subject MRI space to MNI
fsaverage space, you must apply the FreeSurfer's talairach.xfm transform
for your dataset. You can take a look at tut-freesurfer-mne for
more information.
For an example that involves ECoG data, channel locations in a
subject-specific MRI, or projection into a surface, see
tut-working-with-ecog. In the ECoG example, we show
how to visualize surface grid channels on the brain.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Adam Li <adam2392@gmail.com>
#          Alex Rockhill <aprockhill@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 fetch_fsaverage

# paths to mne datasets - sample sEEG and FreeSurfer's fsaverage subject
# which is in MNI space
misc_path = mne.datasets.misc.data_path()
sample_path = mne.datasets.sample.data_path()
subjects_dir = op.join(sample_path, 'subjects')

# use mne-python's fsaverage data
fetch_fsaverage(subjects_dir=subjects_dir, verbose=True)  # downloads if needed