I am working on the file "0.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Querying the Raw object
.. sidebar:: Attributes vs. Methods
**Attributes** are usually static properties of Python objects — things
that are pre-computed and stored as part of the object's representation
in memory. Attributes are accessed with the ``.`` operator and do not
require parentheses after the attribute name (example: ``raw.ch_names``).

**Methods** are like specialized functions attached to an object.
Usually they require additional user input and/or need some computation
to yield a result. Methods always have parentheses at the end; additional
arguments (if any) go inside those parentheses (examples:
``raw.estimate_rank()``, ``raw.drop_channels(['EEG 030', 'MEG 2242'])``).

We saw above that printing the :class:~mne.io.Raw object displays some
basic information like the total number of channels, the number of time
points at which the data were sampled, total duration, and the approximate
size in memory. Much more information is available through the various
attributes and methods of the :class:~mne.io.Raw class. Some useful
attributes of :class:~mne.io.Raw objects include a list of the channel
names (:attr:~mne.io.Raw.ch_names), an array of the sample times in seconds
(:attr:~mne.io.Raw.times), and the total number of samples
(:attr:~mne.io.Raw.n_times); a list of all attributes and methods is given
in the documentation of the :class:~mne.io.Raw class.
The Raw.info attribute
There is also quite a lot of information stored in the raw.info
attribute, which stores an :class:~mne.Info object that is similar to a
:class:Python dictionary <dict> (in that it has fields accessed via named
keys). Like Python dictionaries, raw.info has a .keys() method that
shows all the available field names; unlike Python dictionaries, printing
raw.info will print a nicely-formatted glimpse of each field's data. See
tut-info-class for more on what is stored in :class:~mne.Info
objects, and how to interact with them.
Can you write Python code for it?

n_time_samps = raw.n_times
time_secs = raw.times
ch_names = raw.ch_names
n_chan = len(ch_names)  # note: there is no raw.n_channels attribute
print('the (cropped) sample data object has {} time samples and {} channels.'
      ''.format(n_time_samps, n_chan))
print('The last time sample is at {} seconds.'.format(time_secs[-1]))
print('The first few channel names are {}.'.format(', '.join(ch_names[:3])))
print()  # insert a blank line in the output

# some examples of raw.info:
print('bad channels:', raw.info['bads'])  # chs marked "bad" during acquisition
print(raw.info['sfreq'], 'Hz')            # sampling frequency
print(raw.info['description'], '\n')      # miscellaneous acquisition info

print(raw.info)


I am working on the file "0.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Selection in the time domain
If you want to limit the time domain of a :class:~mne.io.Raw object, you
can use the :meth:~mne.io.Raw.crop method, which modifies the
:class:~mne.io.Raw object in place (we've seen this already at the start of
this tutorial, when we cropped the :class:~mne.io.Raw object to 60 seconds
to reduce memory demands). :meth:~mne.io.Raw.crop takes parameters tmin
and tmax, both in seconds (here we'll again use :meth:~mne.io.Raw.copy
first to avoid changing the original :class:~mne.io.Raw object):
Can you write Python code for it?

raw_selection = raw.copy().crop(tmin=10, tmax=12.5)
print(raw_selection)


I am working on the file "0.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.
   :depth: 2
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.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.22/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_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.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Additional examples of plotting scalp topographies can be found in
ex-evoked-topomap.
Arrow maps
Scalp topographies at a given time point can be augmented with arrows to show
the estimated magnitude and direction of the magnetic field, using the
function mne.viz.plot_arrowmap:
Can you write Python code for it?

mags = evks['aud/left'].copy().pick_types(meg='mag')
mne.viz.plot_arrowmap(mags.data[:, 175], mags.info, extrapolate='local')


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
By default, MEG sensors will be used to estimate the field on the helmet
surface, while EEG sensors will be used to estimate the field on the scalp.
Once the maps are computed, you can plot them with evoked.plot_field()
<mne.Evoked.plot_field>:
Can you write Python code for it?

maps = mne.make_field_map(evks['aud/left'], trans=sample_data_trans_file,
                          subject='sample', subjects_dir=subjects_dir)
evks['aud/left'].plot_field(maps, time=0.1)


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
For larger numbers of sensors, the method evoked.plot_topo()
<mne.Evoked.plot_topo> and the function mne.viz.plot_evoked_topo
can both be used. The ~mne.Evoked.plot_topo method will plot only a
single condition, while the ~mne.viz.plot_evoked_topo function can
plot one or more conditions on the same axes, if passed a list of
~mne.Evoked objects. The legend entries will be automatically drawn
from the ~mne.Evoked objects' comment attribute:
Can you write Python code for it?


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Instead of creating the ~mne.Evoked object from an ~mne.Epochs object,
we'll load an existing ~mne.Evoked object from disk. Remember, the
:file:.fif format can store multiple ~mne.Evoked objects, so we'll end up
with a list of ~mne.Evoked objects after loading. Recall also from the
tut-section-load-evk section of the introductory Evoked tutorial
<tut-evoked-class> that the sample ~mne.Evoked objects have not been
baseline-corrected and have unapplied projectors, so we'll take care of that
when loading:
Can you write Python code for it?

sample_data_folder = mne.datasets.sample.data_path()
sample_data_evk_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis-ave.fif')
evokeds_list = mne.read_evokeds(sample_data_evk_file, baseline=(None, 0),
                                proj=True, verbose=False)
# show the condition names
for e in evokeds_list:
    print(e.comment)


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Joint plots
Joint plots combine butterfly plots with scalp topographies, and provide an
excellent first-look at evoked data; by default, topographies will be
automatically placed based on peak finding. Here we plot the
right-visual-field condition; if no picks are specified we get a separate
figure for each channel type:
Can you write Python code for it?


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Like ~mne.Evoked.plot_topomap you can specify the times at which
you want the scalp topographies calculated, and you can customize the plot in
various other ways as well. See mne.Evoked.plot_joint for details.
Comparing Evoked objects
To compare ~mne.Evoked objects from different experimental
conditions, the function mne.viz.plot_compare_evokeds can take a
:class:list or :class:dict of ~mne.Evoked objects and plot them
all on the same axes. Like most MNE-Python visualization functions, it has a
picks parameter for selecting channels, but by default will generate one
figure for each channel type, and combine information across channels of the
same type by calculating the :term:global field power <GFP>. Information
may be combined across channels in other ways too; support for combining via
mean, median, or standard deviation are built-in, and custom callable
functions may also be used, as shown here:
Can you write Python code for it?

def custom_func(x):
    return x.max(axis=1)

for combine in ('mean', 'median', 'gfp', custom_func):
    mne.viz.plot_compare_evokeds(evks, picks='eeg', combine=combine)


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
The legends generated by ~mne.viz.plot_compare_evokeds above used the
dictionary keys provided by the evks variable. If instead you pass a
:class:list or :class:tuple of ~mne.Evoked objects, the legend keys
will be generated automatically from the comment attribute of the
~mne.Evoked objects (or, as sequential integers if the comment attribute is
empty or ambiguous). To illustrate this, we'll make a list of 5 ~mne.Evoked
objects: 2 with identical comments, 2 with empty comments (either an empty
string or None), and 1 with a unique non-empty comment:
Can you write Python code for it?

temp_list = list()
for idx, _comment in enumerate(('foo', 'foo', '', None, 'bar'), start=1):
    _evk = evokeds_list[0].copy()
    _evk.comment = _comment
    _evk.data *= idx  # so we can tell the traces apart
    temp_list.append(_evk)

mne.viz.plot_compare_evokeds(temp_list, picks='mag')


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
To make our life easier, let's convert that list of ~mne.Evoked
objects into a :class:dictionary <dict>. We'll use /-separated
dictionary keys to encode the conditions (like is often done when epoching)
because some of the plotting methods can take advantage of that style of
coding.
Can you write Python code for it?

conds = ('aud/left', 'aud/right', 'vis/left', 'vis/right')
evks = dict(zip(conds, evokeds_list))
#      ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ this is equivalent to:
# {'aud/left': evokeds_list[0], 'aud/right': evokeds_list[1],
#  'vis/left': evokeds_list[2], 'vis/right': evokeds_list[3]}


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Topographical subplots
For sensor-level analyses it can be useful to plot the response at each
sensor in a topographical layout. The ~mne.viz.plot_compare_evokeds
function can do this if you pass axes='topo', but it can be quite slow
if the number of sensors is too large, so here we'll plot only the EEG
channels:
Can you write Python code for it?

mne.viz.plot_compare_evokeds(evks, picks='eeg', colors=dict(aud=0, vis=1),
                             linestyles=dict(left='solid', right='dashed'),
                             axes='topo', styles=dict(aud=dict(linewidth=1),
                                                      vis=dict(linewidth=1)))


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Visualizing Evoked data
This tutorial shows the different visualization methods for
~mne.Evoked objects.
   :depth: 2
As usual we'll start by importing the modules we need:
Can you write Python code for it?


I am working on the file "0.22/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
You can also use MEG sensors to estimate the scalp field by passing
meg_surf='head'. By selecting each sensor type in turn, you can compare
the scalp field estimates from each.
Can you write Python code for it?

for ch_type in ('mag', 'grad', 'eeg'):
    evk = evks['aud/right'].copy().pick(ch_type)
    _map = mne.make_field_map(evk, trans=sample_data_trans_file,
                              subject='sample', subjects_dir=subjects_dir,
                              meg_surf='head')
    fig = evk.plot_field(_map, time=0.1)
    mne.viz.set_3d_title(fig, ch_type, size=20)


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:

Note

The ``@`` symbol indicates matrix multiplication on NumPy arrays, and was
    introduced in Python 3.5 / NumPy 1.10. The notation ``plot(*point)`` uses
    Python `argument expansion`_ to "unpack" the elements of ``point`` into
    separate positional arguments to the function. In other words,
    ``plot(*point)`` expands to ``plot(3, 2, 5)``.

Notice that we used matrix multiplication to compute the projection of our
point $(3, 2, 5)$onto the $x, y$ plane:
\begin{align}\left[
      \begin{matrix} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 0 \end{matrix}
    \right]
    \left[ \begin{matrix} 3 \ 2 \ 5 \end{matrix} \right] =
    \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right]\end{align}
...and that applying the projection again to the result just gives back the
result again:
\begin{align}\left[
      \begin{matrix} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 0 \end{matrix}
    \right]
    \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right] =
    \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right]\end{align}
From an information perspective, this projection has taken the point
$x, y, z$ and removed the information about how far in the $z$
direction our point was located; all we know now is its position in the
$x, y$ plane. Moreover, applying our projection matrix to any point
in $x, y, z$ space will reduce it to a corresponding point on the
$x, y$ plane. The term for this is a subspace: the projection matrix
projects points in the original space into a subspace of lower dimension
than the original. The reason our subspace is the $x,y$ plane (instead
of, say, the $y,z$ plane) is a direct result of the particular values
in our projection matrix.
Example: projection as noise reduction
Another way to describe this "loss of information" or "projection into a
subspace" is to say that projection reduces the rank (or "degrees of
freedom") of the measurement — here, from 3 dimensions down to 2. On the
other hand, if you know that measurement component in the $z$ direction
is just...
Can you write Python code for it?

trigger_effect = np.array([[3, -1, 1]]).T


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Additional ways of visualizing projectors are covered in the tutorial
tut-artifact-ssp.
Loading and saving projectors
SSP can be used for other types of signal cleaning besides just reduction of
environmental noise. You probably noticed two large deflections in the
magnetometer signals in the previous plot that were not removed by the
empty-room projectors — those are artifacts of the subject's heartbeat. SSP
can be used to remove those artifacts as well. The sample data includes
projectors for heartbeat noise reduction that were saved in a separate file
from the raw data, which can be loaded with the :func:mne.read_proj
function:
Can you write Python code for it?

ecg_proj_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                             'sample_audvis_ecg-proj.fif')
ecg_projs = mne.read_proj(ecg_proj_file)
print(ecg_projs)


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Background on projectors and projections
This tutorial provides background information on projectors and Signal Space
Projection (SSP), and covers loading and saving projectors, adding and removing
projectors from Raw objects, the difference between "applied" and "unapplied"
projectors, and at what stages MNE-Python applies projectors automatically.
   :depth: 2
We'll start by importing the Python modules we need; we'll also define a short
function to make it easier to make several plots that look similar:
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # noqa
from scipy.linalg import svd
import mne

def setup_3d_axes():
    ax = plt.axes(projection='3d')
    ax.view_init(azim=-105, elev=20)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.set_xlim(-1, 5)
    ax.set_ylim(-1, 5)
    ax.set_zlim(0, 5)
    return ax


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Computing projectors
In MNE-Python, SSP vectors can be computed using general purpose functions
:func:mne.compute_proj_raw, :func:mne.compute_proj_epochs, and
:func:mne.compute_proj_evoked. The general assumption these functions make
is that the data passed contains raw data, epochs or averages of the artifact
you want to repair via projection. In practice this typically involves
continuous raw data of empty room recordings or averaged ECG or EOG
artifacts. A second set of high-level convenience functions is provided to
compute projection vectors for typical use cases. This includes
:func:mne.preprocessing.compute_proj_ecg and
:func:mne.preprocessing.compute_proj_eog for computing the ECG and EOG
related artifact components, respectively; see tut-artifact-ssp for
examples of these uses. For computing the EEG reference signal as a
projector, the function :func:mne.set_eeg_reference can be used; see
tut-set-eeg-ref for more information.

Warning

It is best to compute projectors only on channels that will be
             used (e.g., excluding bad channels). This ensures that
             projection vectors will remain ortho-normalized and that they
             properly capture the activity of interest.

Visualizing the effect of projectors
You can see the effect the projectors are having on the measured signal by
comparing plots with and without the projectors applied. By default,
raw.plot() will apply the projectors in the background before plotting
(without modifying the :class:~mne.io.Raw object); you can control this
with the boolean proj parameter as shown below, or you can turn them on
and off interactively with the projectors interface, accessed via the
:kbd:Proj button in the lower right corner of the plot window. Here we'll
look at just the magnetometers, and a 2-second sample from the beginning of
the file.
Can you write Python code for it?

mags = raw.copy().crop(tmax=2).pick_types(meg='mag')
for proj in (False, True):
    fig = mags.plot(butterfly=True, proj=proj)
    fig.subplots_adjust(top=0.9)
    fig.suptitle('proj={}'.format(proj), size='xx-large', weight='bold')


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Computing the projection matrix from the trigger_effect vector is done
using singular value decomposition <svd_>_ (SVD); interested readers may
consult the internet or a linear algebra textbook for details on this method.
With the projection matrix in place, we can project our original vector
$(3, 2, 5)$ to remove the effect of the trigger, and then plot it:
Can you write Python code for it?

# compute the projection matrix
U, S, V = svd(trigger_effect, full_matrices=False)
trigger_projection_matrix = np.eye(3) - U @ U.T

# project the vector onto the orthogonal plane
projected_point = trigger_projection_matrix @ point
projected_vector = trigger_projection_matrix @ vector

# plot the trigger effect and its orthogonal plane
ax = setup_3d_axes()
ax.plot_trisurf(x, y, z, color='C2', shade=False, alpha=0.25)
ax.quiver3D(*np.concatenate([origin, trigger_effect]).flatten(),
            arrow_length_ratio=0.1, color='C2', alpha=0.5)

# plot the original vector
ax.plot(*vector, color='k')
ax.plot(*point, color='k', marker='o')
offset = np.full((3, 1), 0.1)
ax.text(*(point + offset).flat, '({}, {}, {})'.format(*point.flat), color='k')

# plot the projected vector
ax.plot(*projected_vector, color='C0')
ax.plot(*projected_point, color='C0', marker='o')
offset = np.full((3, 1), -0.2)
ax.text(*(projected_point + offset).flat,
        '({}, {}, {})'.format(*np.round(projected_point.flat, 2)),
        color='C0', horizontalalignment='right')

# 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.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
In MNE-Python, the environmental noise vectors are computed using principal
component analysis <pca_>, usually abbreviated "PCA", which is why the SSP
projectors usually have names like "PCA-v1". (Incidentally, since the process
of performing PCA uses singular value decomposition <svd_> under the hood,
it is also common to see phrases like "projectors were computed using SVD" in
published papers.) The projectors are stored in the projs field of
raw.info:
Can you write Python code for it?


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Just as before, the projection matrix will map any point in $x, y, z$
space onto that plane, and once a point has been projected onto that plane,
applying the projection again will have no effect. For that reason, it should
be clear that although the projected points vary in all three $x$,
$y$, and $z$ directions, the set of projected points have only
two effective dimensions (i.e., they are constrained to a plane).
.. sidebar:: Terminology
In MNE-Python, the matrix used to project a raw signal into a subspace is
usually called a :term:`projector <projector>` or a *projection
operator* — these terms are interchangeable with the term *projection
matrix* used above.

Projections of EEG or MEG signals work in very much the same way: the point
$x, y, z$ corresponds to the value of each sensor at a single time
point, and the projection matrix varies depending on what aspects of the
signal (i.e., what kind of noise) you are trying to project out. The only
real difference is that instead of a single 3-dimensional point $(x, y,
z)$ you're dealing with a time series of $N$-dimensional "points" (one
at each sampling time), where $N$ is usually in the tens or hundreds
(depending on how many sensors your EEG/MEG system has). Fortunately, because
projection is a matrix operation, it can be done very quickly even on signals
with hundreds of dimensions and tens of thousands of time points.
Signal-space projection (SSP)
We mentioned above that the projection matrix will vary depending on what
kind of noise you are trying to project away. Signal-space projection (SSP)
:footcite:UusitaloIlmoniemi1997 is a way of estimating what that projection
matrix should be, by
comparing measurements with and without the signal of interest. For example,
you can take additional "empty room" measurements that record activity at the
sensors when no subject is present. By looking at the spatial pattern of
activity across MEG sensors in an empty room measurement, you can create one
or more $N$-dimensional vector(s) giving the...
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)
raw.crop(tmax=60).load_data()


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
The :class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked
objects all have a boolean :attr:~mne.io.Raw.proj attribute that indicates
whether there are any unapplied / inactive projectors stored in the object.
In other words, the :attr:~mne.io.Raw.proj attribute is True if at
least one :term:projector is present and all of them are active. In
addition, each individual projector also has a boolean active field:
Can you write Python code for it?


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
There is a corresponding :func:mne.write_proj function that can be used to
save projectors to disk in .fif format:
.. code-block:: python3
mne.write_proj('heartbeat-proj.fif', ecg_projs)

Note

By convention, MNE-Python expects projectors to be saved with a filename
    ending in ``-proj.fif`` (or ``-proj.fif.gz``), and will issue a warning
    if you forgo this recommendation.

Adding and removing projectors
Above, when we printed the ecg_projs list that we loaded from a file, it
showed two projectors for gradiometers (the first two, marked "planar"), two
for magnetometers (the middle two, marked "axial"), and two for EEG sensors
(the last two, marked "eeg"). We can add them to the :class:~mne.io.Raw
object using the :meth:~mne.io.Raw.add_proj method:
Can you write Python code for it?


I am working on the file "0.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_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.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_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.22/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_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.22/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Analysing continuous features with binning and regression in sensor space
Predict single trial activity from a continuous variable.
A single-trial regression is performed in each sensor and timepoint
individually, resulting in an :class:mne.Evoked object which contains the
regression coefficient (beta value) for each combination of sensor and
timepoint. This example shows the regression coefficient; the t and p values
are also calculated automatically.
Here, we repeat a few of the analyses from [1]_. This can be easily performed
by accessing the metadata object, which contains word-level information about
various psycholinguistically relevant features of the words for which we have
EEG activity.
For the general methodology, see e.g. [2]_.
References
.. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand
   words are worth a picture: Snapshots of printed-word processing in an
   event-related potential megastudy. Psychological Science, 2015
.. [2] Hauk et al. The time course of visual word recognition as revealed by
   linear regression analysis of ERP data. Neuroimage, 2006
Can you write Python code for it?

# Authors: Tal Linzen <linzen@nyu.edu>
#          Denis A. Engemann <denis.engemann@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)

import pandas as pd
import mne
from mne.stats import linear_regression, fdr_correction
from mne.viz import plot_compare_evokeds
from mne.datasets import kiloword

# Load the data
path = kiloword.data_path() + '/kword_metadata-epo.fif'
epochs = mne.read_epochs(path)
print(epochs.metadata.head())


I am working on the file "0.22/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Because the :func:~mne.stats.linear_regression function also estimates
p values, we can --
after applying FDR correction for multiple comparisons -- also visualise the
statistical significance of the regression of word concreteness.
The :func:mne.viz.plot_evoked_image function takes a mask parameter.
If we supply it with a boolean mask of the positions where we can reject
the null hypothesis, points that are not significant will be shown
transparently, and if desired, in a different colour palette and surrounded
by dark contour lines.
Can you write Python code for it?

reject_H0, fdr_pvals = fdr_correction(res["Concreteness"].p_val.data)
evoked = res["Concreteness"].beta
evoked.plot_image(mask=reject_H0, time_unit='s')


I am working on the file "0.22/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Psycholinguistically relevant word characteristics are continuous. I.e.,
concreteness or imaginability is a graded property. In the metadata,
we have concreteness ratings on a 5-point scale. We can show the dependence
of the EEG on concreteness by dividing the data into bins and plotting the
mean activity per bin, color coded.
Can you write Python code for it?

name = "Concreteness"
df = epochs.metadata
df[name] = pd.cut(df[name], 11, labels=False) / 10
colors = {str(val): val for val in df[name].unique()}
epochs.metadata = df.assign(Intercept=1)  # Add an intercept for later
evokeds = {val: epochs[name + " == " + val].average() for val in colors}
plot_compare_evokeds(evokeds, colors=colors, split_legend=True,
                     cmap=(name + " Percentile", "viridis"))


I am working on the file "0.22/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
We observe that there appears to be a monotonic dependence of EEG on
concreteness. We can also conduct a continuous analysis: single-trial level
regression with concreteness as a continuous (although here, binned)
feature. We can plot the resulting regression coefficient just like an
Event-related Potential.
Can you write Python code for it?

names = ["Intercept", name]
res = linear_regression(epochs, epochs.metadata[names], names=names)
for cond in names:
    res[cond].beta.plot_joint(title=cond, ts_args=dict(time_unit='s'),
                              topomap_args=dict(time_unit='s'))


I am working on the file "0.22/_downloads/542dc1082b4eb8bba1ec06e757cdf52d/plot_interpolate_bad_channels.ipynb".
The first task is:
Compute interpolation (also works with Raw and Epochs objects)
Can you write Python code for it?

evoked_interp = evoked.copy().interpolate_bads(reset_bads=False)
evoked_interp.plot(exclude=[], picks=('grad', 'eeg'))


I am working on the file "0.22/_downloads/542dc1082b4eb8bba1ec06e757cdf52d/plot_interpolate_bad_channels.ipynb".
The first task is:
Interpolate bad channels for MEG/EEG channels
This example shows how to interpolate bad MEG/EEG channels

Using spherical splines from :footcite:PerrinEtAl1989 for EEG data.
Using field interpolation for MEG and EEG data.

In this example, the bad channels will still be marked as bad.
Only the data in those channels is replaced.
Can you write Python code for it?

# Authors: Denis A. Engemann <denis.engemann@gmail.com>
#          Mainak Jas <mainak.jas@telecom-paristech.fr>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname, condition='Left Auditory',
                          baseline=(None, 0))

# plot with bads
evoked.plot(exclude=[], picks=('grad', 'eeg'))


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Above, when we created an :class:~mne.Evoked object by averaging epochs,
baseline correction was applied by default when we extracted epochs from the
~mne.io.Raw object (the default baseline period is (None, 0),
which assured zero mean for times before the stimulus event). In contrast, if
we plot the first :class:~mne.Evoked object in the list that was loaded
from disk, we'll see that the data have not been baseline-corrected:
Can you write Python code for it?


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Basic visualization of Evoked objects
We can visualize the average evoked response for left-auditory stimuli using
the :meth:~mne.Evoked.plot method, which yields a butterfly plot of each
channel type:
Can you write Python code for it?


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Creating Evoked objects from Epochs
:class:~mne.Evoked objects typically store an EEG or MEG signal that has
been averaged over multiple :term:epochs, which is a common technique for
estimating stimulus-evoked activity. The data in an :class:~mne.Evoked
object are stored in an :class:array <numpy.ndarray> of shape
(n_channels, n_times) (in contrast to an :class:~mne.Epochs object,
which stores data of shape (n_epochs, n_channels, n_times)). Thus to
create an :class:~mne.Evoked object, we'll start by epoching some raw data,
and then averaging together all the epochs from one condition:
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, verbose=False)
events = mne.find_events(raw, stim_channel='STI 014')
# we'll skip the "face" and "buttonpress" conditions, to save memory:
event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4}
epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7, event_id=event_dict,
                    preload=True)
evoked = epochs['auditory/left'].average()

del raw  # reduce memory usage


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
If you want to load only some of the conditions present in a .fif file,
:func:~mne.read_evokeds has a condition parameter, which takes either a
string (matched against the comment attribute of the evoked objects on disk),
or an integer selecting the :class:~mne.Evoked object based on the order
it's stored in the file. Passing lists of integers or strings is also
possible. If only one object is selected, the :class:~mne.Evoked object
will be returned directly (rather than a length-one list containing it):
Can you write Python code for it?

right_vis = mne.read_evokeds(sample_data_evk_file, condition='Right visual')
print(right_vis)
print(type(right_vis))


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Like the plot() methods for :meth:Raw <mne.io.Raw.plot> and
:meth:Epochs <mne.Epochs.plot> objects,
:meth:evoked.plot() <mne.Evoked.plot> has many parameters for customizing
the plot output, such as color-coding channel traces by scalp location, or
plotting the :term:global field power <GFP> alongside the channel traces.
See tut-visualize-evoked for more information about visualizing
:class:~mne.Evoked objects.
Subselecting Evoked data
.. sidebar:: Evokeds are not memory-mapped
:class:~mne.Evoked objects use a :attr:~mne.Evoked.data attribute
  rather than a :meth:~mne.Epochs.get_data method; this reflects the fact
  that the data in :class:~mne.Evoked objects are always loaded into
  memory, never memory-mapped_ from their location on disk (because they
  are typically much smaller than :class:~mne.io.Raw or
  :class:~mne.Epochs objects).
Unlike :class:~mne.io.Raw and :class:~mne.Epochs objects,
:class:~mne.Evoked objects do not support selection by square-bracket
indexing. Instead, data can be subselected by indexing the
:attr:~mne.Evoked.data attribute:
Can you write Python code for it?

print(evoked.data[:2, :3])  # first 2 channels, first 3 timepoints


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Note that the nave attribute of the resulting ~mne.Evoked object will
reflect the effective number of averages, and depends on both the nave
attributes of the contributing ~mne.Evoked objects and the weights at
which they are combined. Keeping track of effective nave is important for
inverse imaging, because nave is used to scale the noise covariance
estimate (which in turn affects the magnitude of estimated source activity).
See minimum_norm_estimates for more information (especially the
whitening_and_scaling section). Note that mne.grand_average does
not adjust nave to reflect effective number of averaged epochs; rather
it simply sets nave to the number of evokeds that were averaged
together. For this reason, it is best to use mne.combine_evoked rather than
mne.grand_average if you intend to perform inverse imaging on the resulting
:class:~mne.Evoked object.
Other uses of Evoked objects
Although the most common use of :class:~mne.Evoked objects is to store
averages of epoched data, there are a couple other uses worth noting here.
First, the method :meth:epochs.standard_error() <mne.Epochs.standard_error>
will create an :class:~mne.Evoked object (just like
:meth:epochs.average() <mne.Epochs.average> does), but the data in the
:class:~mne.Evoked object will be the standard error across epochs instead
of the average. To indicate this difference, :class:~mne.Evoked objects
have a :attr:~mne.Evoked.kind attribute that takes values 'average' or
'standard error' as appropriate.
Another use of :class:~mne.Evoked objects is to represent a single trial
or epoch of data, usually when looping through epochs. This can be easily
accomplished with the :meth:epochs.iter_evoked() <mne.Epochs.iter_evoked>
method, and can be useful for applications where you want to do something
that is only possible for :class:~mne.Evoked objects. For example, here
we use the :meth:~mne.Evoked.get_peak method (which isn't available for
:class:~mne.Epochs objects) to get the peak response in each trial:
Can you write Python code for it?

for ix, trial in enumerate(epochs[:3].iter_evoked()):
    channel, latency, value = trial.get_peak(ch_type='eeg',
                                             return_amplitude=True)
    latency = int(round(latency * 1e3))  # convert to milliseconds
    value = int(round(value * 1e6))      # convert to µV
    print('Trial {}: peak of {} µV at {} ms in channel {}'
          .format(ix, value, latency, channel))


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Notice that :func:mne.read_evokeds returned a :class:list of
:class:~mne.Evoked objects, and each one has an evoked.comment
attribute describing the experimental condition that was averaged to
generate the estimate:
Can you write Python code for it?

for evok in evokeds_list:
    print(evok.comment)


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Notice that :meth:~mne.Evoked.apply_baseline operated in-place. Similarly,
:class:~mne.Evoked objects may have been saved to disk with or without
:term:projectors <projector> applied; you can pass proj=True to the
:func:~mne.read_evokeds function, or use the :meth:~mne.Evoked.apply_proj
method after loading.
Combining Evoked objects
One way to pool data across multiple conditions when estimating evoked
responses is to do so prior to averaging (recall that MNE-Python can select
based on partial matching of /-separated epoch labels; see
tut-section-subselect-epochs for more info):
Can you write Python code for it?

left_right_aud = epochs['auditory'].average()
print(left_right_aud)


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Similarities among the core data structures
:class:~mne.Evoked objects have many similarities with :class:~mne.io.Raw
and :class:~mne.Epochs objects, including:

They can be loaded from and saved to disk in .fif format, and their
  data can be exported to a :class:NumPy array <numpy.ndarray> (but through
  the :attr:~mne.Evoked.data attribute, not through a get_data()
  method). :class:Pandas DataFrame <pandas.DataFrame> export is also
  available through the :meth:~mne.Evoked.to_data_frame method.

You can change the name or type of a channel using
  :meth:evoked.rename_channels() <mne.Evoked.rename_channels> or
  :meth:evoked.set_channel_types() <mne.Evoked.set_channel_types>.
  Both methods take :class:dictionaries <dict> where the keys are existing
  channel names, and the values are the new name (or type) for that channel.
  Existing channels that are not in the dictionary will be unchanged.

:term:SSP projector <projector> manipulation is possible through
  :meth:~mne.Evoked.add_proj, :meth:~mne.Evoked.del_proj, and
  :meth:~mne.Evoked.plot_projs_topomap methods, and the
  :attr:~mne.Evoked.proj attribute. See tut-artifact-ssp for more
  information on SSP.

Like :class:~mne.io.Raw and :class:~mne.Epochs objects,
  :class:~mne.Evoked objects have :meth:~mne.Evoked.copy,
  :meth:~mne.Evoked.crop, :meth:~mne.Evoked.time_as_index,
  :meth:~mne.Evoked.filter, and :meth:~mne.Evoked.resample methods.

Like :class:~mne.io.Raw and :class:~mne.Epochs objects,
  :class:~mne.Evoked objects have evoked.times,
  :attr:evoked.ch_names <mne.Evoked.ch_names>, and :class:info <mne.Info>
  attributes.

Loading and saving Evoked data
Single :class:~mne.Evoked objects can be saved to disk with the
:meth:evoked.save() <mne.Evoked.save> method. One difference between
:class:~mne.Evoked objects and the other data structures is that multiple
:class:~mne.Evoked objects can be saved into a single .fif file, using
:func:mne.write_evokeds. The example data...
Can you write Python code for it?

sample_data_evk_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis-ave.fif')
evokeds_list = mne.read_evokeds(sample_data_evk_file, verbose=False)
print(evokeds_list)
print(type(evokeds_list))


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
The Evoked data structure: evoked/averaged data
This tutorial covers the basics of creating and working with :term:evoked
data. It introduces the :class:~mne.Evoked data structure in detail,
including how to load, query, subselect, export, and plot data from an
:class:~mne.Evoked object. For info on creating an :class:~mne.Evoked
object from (possibly simulated) data in a :class:NumPy array
<numpy.ndarray>, see tut_creating_data_structures.
   :depth: 2
As usual we'll start by importing the modules we need:
Can you write Python code for it?


I am working on the file "0.22/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
This can be remedied by either passing a baseline parameter to
:func:mne.read_evokeds, or by applying baseline correction after loading,
as shown here:
Can you write Python code for it?


I am working on the file "0.22/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Compute statistic
To use an algorithm optimized for spatio-temporal clustering, we
just pass the spatial adjacency matrix (instead of spatio-temporal)
Can you write Python code for it?

print('Computing adjacency.')
adjacency = mne.spatial_src_adjacency(src)

#    Note that X needs to be a multi-dimensional array of shape
#    samples (subjects) x time x space, so we permute dimensions
X = np.transpose(X, [2, 1, 0])

#    Now let's actually do the clustering. This can take a long time...
#    Here we set the threshold quite high to reduce computation.
p_threshold = 0.001
t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)
print('Clustering.')
T_obs, clusters, cluster_p_values, H0 = clu = \
    spatio_temporal_cluster_1samp_test(X, adjacency=adjacency, n_jobs=1,
                                       threshold=t_threshold, buffer_size=None,
                                       verbose=True)
#    Now select the clusters that are sig. at p < 0.05 (note that this value
#    is multiple-comparisons corrected).
good_cluster_inds = np.where(cluster_p_values < 0.05)[0]


I am working on the file "0.22/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Finally, we want to compare the overall activity levels in each condition,
the diff is taken along the last axis (condition). The negative sign makes
it so condition1 > condition2 shows up as "red blobs" (instead of blue).
Can you write Python code for it?

X = np.abs(X)  # only magnitude
X = X[:, :, :, 0] - X[:, :, :, 1]  # make paired contrast


I am working on the file "0.22/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = sample.data_path()
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'
subjects_dir = data_path + '/subjects'
src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'

tmin = -0.2
tmax = 0.3  # Use a lower tmax to reduce multiple comparisons

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


I am working on the file "0.22/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to common cortical space
Normally you would read in estimates across several subjects and morph
them to the same cortical space (e.g. fsaverage). For example purposes,
we will simulate this by just having each "subject" have the same
response (just noisy in source space) here.

Note

Note that for 7 subjects with a two-sided statistical test, the minimum
    significance under a permutation test is only p = 1/(2 ** 6) = 0.015,
    which is large.

Can you write Python code for it?

n_vertices_sample, n_times = condition1.data.shape
n_subjects = 7
print('Simulating data for %d subjects.' % n_subjects)

#    Let's make sure our results replicate, so set the seed.
np.random.seed(0)
X = randn(n_vertices_sample, n_times, n_subjects, 2) * 10
X[:, :, :, 0] += condition1.data[:, :, np.newaxis]
X[:, :, :, 1] += condition2.data[:, :, np.newaxis]


I am working on the file "0.22/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to source space
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE, sLORETA, or eLORETA)
inverse_operator = read_inverse_operator(fname_inv)
sample_vertices = [s['vertno'] for s in inverse_operator['src']]

#    Let's average and compute inverse, resampling to speed things up
evoked1 = epochs1.average()
evoked1.resample(50, npad='auto')
condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method)
evoked2 = epochs2.average()
evoked2.resample(50, npad='auto')
condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method)

#    Let's only deal with t > 0, cropping to reduce multiple comparisons
condition1.crop(0, None)
condition2.crop(0, None)
tmin = condition1.tmin
tstep = condition1.tstep * 1000  # convert to milliseconds


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
.. sidebar:: Computing sensor locations
If you are interested in how standard ("idealized") EEG sensor positions
are computed on a spherical head model, the `eeg_positions`_ repository
provides code and documentation to this end.

These built-in EEG montages can be loaded via
:func:mne.channels.make_standard_montage. Note that when loading via
:func:~mne.channels.make_standard_montage, provide the filename without
its file extension:
Can you write Python code for it?

ten_twenty_montage = mne.channels.make_standard_montage('standard_1020')
print(ten_twenty_montage)


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
:func:~mne.viz.plot_alignment requires an :class:~mne.Info object, and
can also render MRI surfaces of the scalp, skull, and brain (by passing
keywords like 'head', 'outer_skull', or 'brain' to the
surfaces parameter) making it useful for assessing coordinate frame
transformations <plot_source_alignment>. For examples of various uses of
:func:~mne.viz.plot_alignment, see plot_montage,
:doc:../../auto_examples/visualization/plot_eeg_on_scalp, and
:doc:../../auto_examples/visualization/plot_meg_sensors.
Working with layout files
As with montages, many layout files are included during MNE-Python
installation, and are stored in the :file:mne/channels/data/layouts folder:
Can you write Python code for it?

layout_dir = os.path.join(os.path.dirname(mne.__file__),
                          'channels', 'data', 'layouts')
print('\nBUILT-IN LAYOUT FILES')
print('=====================')
print(sorted(os.listdir(layout_dir)))


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
About montages and layouts
:class:Montages <mne.channels.DigMontage> contain sensor
positions in 3D (x, y, z, in meters), and can be used to set
the physical positions of sensors. By specifying the location of sensors
relative to the brain, :class:Montages <mne.channels.DigMontage> play an
important role in computing the forward solution and computing inverse
estimates.
In contrast, :class:Layouts <mne.channels.Layout> are idealized 2-D
representations of sensor positions, and are primarily used for arranging
individual sensor subplots in a topoplot, or for showing the approximate
relative arrangement of sensors as seen from above.
Working with built-in montages
The 3D coordinates of MEG sensors are included in the raw recordings from MEG
systems, and are automatically stored in the info attribute of the
:class:~mne.io.Raw file upon loading. EEG electrode locations are much more
variable because of differences in head shape. Idealized montages for many
EEG systems are included during MNE-Python installation; these files are
stored in your mne-python directory, in the
:file:mne/channels/data/montages folder:
Can you write Python code for it?

montage_dir = os.path.join(os.path.dirname(mne.__file__),
                           'channels', 'data', 'montages')
print('\nBUILT-IN MONTAGE FILES')
print('======================')
print(sorted(os.listdir(montage_dir)))


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Controlling channel projection (MNE vs EEGLAB)
Channel positions in 2d space are obtained by projecting their actual 3d
positions using a sphere as a reference. Because 'standard_1020' montage
contains realistic, not spherical, channel positions, we will use a different
montage to demonstrate controlling how channels are projected to 2d space.
Can you write Python code for it?

biosemi_montage = mne.channels.make_standard_montage('biosemi64')
biosemi_montage.plot(show_names=False)


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
In mne-python the head center and therefore the sphere center are calculated
using fiducial points. Because of this the head circle represents head
circumference at the nasion and ear level, and not where it is commonly
measured in 10-20 EEG system: above nasion at T4/T8, T3/T7, Oz, Fz level.
Notice below that by default T7 and Oz channels are placed within the head
circle, not on the head outline:
Can you write Python code for it?


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Instead of approximating the EEGLAB-esque sphere location as above, you can
calculate the sphere origin from position of Oz, Fpz, T3/T7 or T4/T8
channels. This is easier once the montage has been applied to the data and
channel positions are in the head space - see
this example <ex-topomap-eeglab-style>.
Reading sensor digitization files
In the sample data, setting the digitized EEG montage was done prior to
saving the :class:~mne.io.Raw object to disk, so the sensor positions are
already incorporated into the info attribute of the :class:~mne.io.Raw
object (see the documentation of the reading functions and
:meth:~mne.io.Raw.set_montage for details on how that works). Because of
that, we can plot sensor locations directly from the :class:~mne.io.Raw
object using the :meth:~mne.io.Raw.plot_sensors method, which provides
similar functionality to
:meth:montage.plot() <mne.channels.DigMontage.plot>.
:meth:~mne.io.Raw.plot_sensors also allows channel selection by type, can
color-code channels in various ways (by default, channels listed in
raw.info['bads'] will be plotted in red), and allows drawing into an
existing matplotlib axes object (so the channel positions can easily be
made as a subplot in a multi-panel figure):
Can you write Python code for it?

fig = plt.figure()
ax2d = fig.add_subplot(121)
ax3d = fig.add_subplot(122, projection='3d')
raw.plot_sensors(ch_type='eeg', axes=ax2d)
raw.plot_sensors(ch_type='eeg', axes=ax3d, kind='3d')
ax3d.view_init(azim=70, elev=15)


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
It's probably evident from the 2D topomap above that there is some
irregularity in the EEG sensor positions in the sample dataset
<sample-dataset> — this is because the sensor positions in that dataset are
digitizations of the sensor positions on an actual subject's head, rather
than idealized sensor positions based on a spherical head model. Depending on
what system was used to digitize the electrode positions (e.g., a Polhemus
Fastrak digitizer), you must use different montage reading functions (see
dig-formats). The resulting :class:montage <mne.channels.DigMontage>
can then be added to :class:~mne.io.Raw objects by passing it to the
:meth:~mne.io.Raw.set_montage method (just as we did above with the name of
the idealized montage 'standard_1020'). Once loaded, locations can be
plotted with :meth:~mne.channels.DigMontage.plot and saved with
:meth:~mne.channels.DigMontage.save, like when working with a standard
montage.

Note

When setting a montage with :meth:`~mne.io.Raw.set_montage`
    the measurement info is updated in two places (the ``chs``
    and ``dig`` entries are updated). See `tut-info-class`.
    ``dig`` may contain HPI, fiducial, or head shape points in
    addition to electrode locations.

Rendering sensor position with mayavi
It is also possible to render an image of a MEG sensor helmet in 3D, using
mayavi instead of matplotlib, by calling :func:mne.viz.plot_alignment
Can you write Python code for it?

fig = mne.viz.plot_alignment(raw.info, trans=None, dig=False, eeg=False,
                             surfaces=[], meg=['helmet', 'sensors'],
                             coord_frame='meg')
mne.viz.set_3d_view(fig, azimuth=50, elevation=90, distance=0.5)


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Once loaded, a montage can be applied to data via one of the instance methods
such as :meth:raw.set_montage <mne.io.Raw.set_montage>. It is also possible
to skip the loading step by passing the filename string directly to the
:meth:~mne.io.Raw.set_montage method. This won't work with our sample
data, because it's channel names don't match the channel names in the
standard 10-20 montage, so these commands are not run here:
Can you write Python code for it?

# these will be equivalent:
# raw_1020 = raw.copy().set_montage(ten_twenty_montage)
# raw_1020 = raw.copy().set_montage('standard_1020')


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Similar to the picks argument for selecting channels from
:class:~mne.io.Raw objects, the :meth:~mne.channels.Layout.plot method of
:class:~mne.channels.Layout objects also has a picks argument. However,
because layouts only contain information about sensor name and location (not
sensor type), the :meth:~mne.channels.Layout.plot method only allows
picking channels by index (not by name or by type). Here we find the indices
we want using :func:numpy.where; selection by name or type is possible via
:func:mne.pick_channels or :func:mne.pick_types.
Can you write Python code for it?

midline = np.where([name.endswith('z') for name in biosemi_layout.names])[0]
biosemi_layout.plot(picks=midline)


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Working with sensor locations
This tutorial describes how to read and plot sensor locations, and how
the physical location of sensors is handled in MNE-Python.
   :depth: 2
As usual we'll start by importing the modules we need and loading some
example data <sample-dataset>:
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # noqa
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, preload=True, verbose=False)


I am working on the file "0.22/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
You may have noticed that the file formats and filename extensions of the
built-in layout and montage files vary considerably. This reflects different
manufacturers' conventions; to make loading easier the montage and layout
loading functions in MNE-Python take the filename without its extension so
you don't have to keep track of which file format is used by which
manufacturer.
To load a layout file, use the :func:mne.channels.read_layout function, and
provide the filename without its file extension. You can then visualize the
layout using its :meth:~mne.channels.Layout.plot method, or (equivalently)
by passing it to :func:mne.viz.plot_layout:
Can you write Python code for it?

biosemi_layout = mne.channels.read_layout('biosemi')
biosemi_layout.plot()  # same result as: mne.viz.plot_layout(biosemi_layout)


I am working on the file "0.22/_downloads/5a3a8c2664be35abac537a97ac994e3e/plot_modifying_data_inplace.ipynb".
The first task is:
Finally, it is possible to apply arbitrary functions to your data to do
what you want. Here we will use this to take the amplitude and phase of
the hilbert transformed data.

Note

You can also use ``envelope=True`` in the call to
          :meth:`mne.io.Raw.apply_hilbert` to do this automatically.

Can you write Python code for it?

# Take the amplitude and phase
raw_amp = raw_hilb.copy()
raw_amp.apply_function(np.abs, hilb_picks)
raw_phase = raw_hilb.copy()
raw_phase.apply_function(np.angle, hilb_picks)

_, (a1, a2) = plt.subplots(2, 1, figsize=(15, 10))
a1.plot(raw_band[hilb_picks[0]][0][0].real)
a1.plot(raw_amp[hilb_picks[0]][0][0].real)
a2.plot(raw_phase[hilb_picks[0]][0][0].real)
a1.set_title('Amplitude of frequency band')
a2.set_title('Phase of frequency band')


I am working on the file "0.22/_downloads/5a3a8c2664be35abac537a97ac994e3e/plot_modifying_data_inplace.ipynb".
The first task is:
In addition, there are functions for applying the Hilbert transform, which is
useful to calculate phase / amplitude of your signal.
Can you write Python code for it?

# Filter signal with a fairly steep filter, then take hilbert transform

raw_band = raw.copy()
raw_band.filter(12, 18, l_trans_bandwidth=2., h_trans_bandwidth=2.,
                fir_design='firwin')
raw_hilb = raw_band.copy()
hilb_picks = mne.pick_types(raw_band.info, meg=False, eeg=True)
raw_hilb.apply_hilbert(hilb_picks)
print(raw_hilb[0][0].dtype)


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Event dictionaries like this one are used when extracting epochs from
continuous data, and the resulting :class:~mne.Epochs object allows pooling
by requesting partial trial descriptors. For example, if we wanted to pool
all auditory trials, instead of merging Event IDs 1 and 2 using the
:func:~mne.merge_events function, we can make use of the fact that the keys
of event_dict contain multiple trial descriptors separated by /
characters: requesting 'auditory' trials will select all epochs with
Event IDs 1 and 2; requesting 'left' trials will select all epochs with
Event IDs 1 and 3. An example of this is shown in a later tutorial.
.. TODO replace above sentence when the relevant tut is ready:
   An example of this is shown later, in the epoch-pooling section of
   the epochs-intro-tutorial tutorial.
Plotting events
Another use of event dictionaries is when plotting events, which can serve as
a useful check that your event signals were properly sent to the STIM
channel(s) and that MNE-Python has successfully found them. The function
:func:mne.viz.plot_events will plot each event versus its sample number
(or, if you provide the sampling frequency, it will plot them versus time in
seconds). It can also account for the offset between sample number and sample
index in Neuromag systems, with the first_samp parameter. If an event
dictionary is provided, it will be used to generate a legend:
Can you write Python code for it?

fig = mne.viz.plot_events(events, sfreq=raw.info['sfreq'],
                          first_samp=raw.first_samp, event_id=event_dict)
fig.subplots_adjust(right=0.7)  # make room for legend


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Making equally-spaced Events arrays
For some experiments (such as those intending to analyze resting-state
activity) there may not be any experimental events included in the raw
recording. In such cases, an Events array of equally-spaced events can be
generated using :func:mne.make_fixed_length_events:
Can you write Python code for it?

new_events = mne.make_fixed_length_events(raw, start=5, stop=50, duration=2.)


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Note, however, that merging events is not necessary if you simply want to
pool trial types for analysis; the next section describes how MNE-Python uses
event dictionaries to map integer Event IDs to more descriptive label
strings.
Mapping Event IDs to trial descriptors
So far in this tutorial we've only been dealing with integer Event IDs, which
were assigned based on DC voltage pulse magnitude (which is ultimately
determined by the experimenter's choices about what signals to send to the
STIM channels). Keeping track of which Event ID corresponds to which
experimental condition can be cumbersome, and it is often desirable to pool
experimental conditions during analysis. You may recall that the mapping of
integer Event IDs to meaningful descriptions for the sample dataset
<sample-dataset> is given in this table
<sample-data-event-dict-table> in the introductory tutorial
<tut-overview>. Here we simply reproduce that mapping as an
event dictionary:
Can you write Python code for it?

event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'smiley': 5, 'buttonpress': 32}


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Plotting events and raw data together
Events can also be plotted alongside the :class:~mne.io.Raw object they
were extracted from, by passing the Event array as the events parameter
of :meth:raw.plot <mne.io.Raw.plot>:
Can you write Python code for it?

raw.plot(events=events, start=5, duration=10, color='gray',
         event_color={1: 'r', 2: 'g', 3: 'b', 4: 'm', 5: 'y', 32: 'k'})


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Reading and writing events from/to a file
Event arrays are :class:NumPy array <numpy.ndarray> objects, so they could
be saved to disk as binary :file:.npy files using :func:numpy.save.
However, MNE-Python provides convenience functions :func:mne.read_events
and :func:mne.write_events for reading and writing event arrays as either
text files (common file extensions are :file:.eve, :file:.lst, and
:file:.txt) or binary :file:.fif files. The example dataset includes the
results of mne.find_events(raw) in a :file:.fif file. Since we've
truncated our :class:~mne.io.Raw object, it will have fewer events than the
events file loaded from disk (which contains events for the entire
recording), but the events should match for the first 60 seconds anyway:
Can you write Python code for it?

sample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                       'sample_audvis_raw-eve.fif')
events_from_file = mne.read_events(sample_data_events_file)
assert np.array_equal(events, events_from_file[:len(events)])


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
The tutorial tut-events-vs-annotations describes in detail the
different ways of obtaining an :term:Events array <events> from a
:class:~mne.io.Raw object (see the section
overview-tut-events-section for details). Since the sample
dataset <sample-dataset> includes experimental events recorded on
:term:stim channel STI 014, we'll start this tutorial by parsing the
events from that channel using :func:mne.find_events:
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
When writing event arrays to disk, the format will be inferred from the file
extension you provide. By convention, MNE-Python expects events files to
either have an :file:.eve extension or to have a file basename ending in
-eve or _eve (e.g., :file:{my_experiment}_eve.fif), and will issue
a warning if this convention is not respected.
Subselecting and combining events
The output of :func:~mne.find_events above (repeated here) told us the
number of events that were found, and the unique integer event IDs present:
Can you write Python code for it?


I am working on the file "0.22/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Working with events
This tutorial describes event representation and how event arrays are used to
subselect data.
   :depth: 2
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping the :class:~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
import numpy as np
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.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Custom reference: Use the mean of channels EEG 001 and EEG 002 as
a reference
Can you write Python code for it?

raw_custom, _ = mne.set_eeg_reference(raw, ['EEG 001', 'EEG 002'])
evoked_custom = mne.Epochs(raw_custom, **epochs_params).average()
del raw_custom  # save memory

title = 'EEG Custom reference'
evoked_custom.plot(titles=dict(eeg=title), time_unit='s')
evoked_custom.plot_topomap(times=[0.1], size=3., title=title, time_unit='s')


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Evoked arithmetic (e.g. differences)
Trial subsets from Epochs can be selected using 'tags' separated by '/'.
Evoked objects support basic arithmetic.
First, we create an Epochs object containing 4 conditions.
Can you write Python code for it?

event_id = {'left/auditory': 1, 'right/auditory': 2,
            'left/visual': 3, 'right/visual': 4}
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     reject=reject)
epochs = mne.Epochs(raw, **epochs_params)

print(epochs)


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Evoked response averaged across channels by ROI
It is possible to average channels by region of interest (for example left
and right) when studying the response to this left auditory stimulus. Here we
use our Raw object on which the average reference projection has been added
back.
Can you write Python code for it?

evoked = mne.Epochs(raw, **epochs_params).average()

left_idx = mne.pick_channels(evoked.info['ch_names'],
                             ['EEG 017', 'EEG 018', 'EEG 025', 'EEG 026'])
right_idx = mne.pick_channels(evoked.info['ch_names'],
                              ['EEG 023', 'EEG 024', 'EEG 034', 'EEG 035'])
roi_dict = dict(Left=left_idx, Right=right_idx)
evoked_combined = combine_channels(evoked, roi_dict, method='mean')

title = 'Evoked response averaged by side'
evoked_combined.plot(titles=dict(eeg=title), time_unit='s')


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
In practice it's quite common to have some EEG channels that are actually
EOG channels. To change a channel type you can use the
:func:mne.io.Raw.set_channel_types method. For example
to treat an EOG channel as EEG you can change its type using
Can you write Python code for it?

raw.set_channel_types(mapping={'EOG 061': 'eeg'})
print(raw.info)


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Let's restrict the data to the EEG channels
Can you write Python code for it?

raw.pick_types(meg=False, eeg=True, eog=True).load_data()

# This particular dataset already has an average reference projection added
# that we now want to remove it for the sake of this example.
raw.set_eeg_reference([])


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Next, we create averages of stimulation-left vs stimulation-right trials.
We can use negative weights in mne.combine_evoked to construct difference
ERPs.
Can you write Python code for it?

left, right = epochs["left"].average(), epochs["right"].average()

# create and plot difference ERP
joint_kwargs = dict(ts_args=dict(time_unit='s'),
                    topomap_args=dict(time_unit='s'))
mne.combine_evoked([left, right], weights=[1, -1]).plot_joint(**joint_kwargs)


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Setup for reading the raw data
Can you write Python code for it?

data_path = sample.data_path()
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'
raw = mne.io.read_raw_fif(raw_fname)


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
The EEG channels in the sample dataset already have locations.
These locations are available in the 'loc' of each channel description.
For the first channel we get
Can you write Python code for it?


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
This can be simplified with a Python list comprehension:
Can you write Python code for it?

all_evokeds = [epochs[cond].average() for cond in sorted(event_id.keys())]
print(all_evokeds)

# Then, we can construct and plot an unweighted average of left vs. right
# trials this way, too:
mne.combine_evoked(
    all_evokeds, weights=[0.5, 0.5, -0.5, -0.5]).plot_joint(**joint_kwargs)


I am working on the file "0.22/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
To plot the GFP by itself you can pass gfp='only' (this makes it easier
to read off the GFP data values, because the scale is aligned):
Can you write Python code for it?


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Alpha
Can you write Python code for it?

fig_alpha, brain_alpha = plot_band('vv', 'alpha')


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
And for OPM:
Can you write Python code for it?

with mne.use_coil_def(opm_coil_def_fname):
    fig = mne.viz.plot_alignment(
        raws['opm'].info, trans=opm_trans_fname, subject=subject,
        subjects_dir=subjects_dir, dig=False, coord_frame='mri',
        surfaces=('head', 'white'))
    mne.viz.set_3d_view(figure=fig, **kwargs)
    fwd['opm'] = mne.make_forward_solution(
        raws['opm'].info, opm_trans_fname, src, bem, eeg=False, verbose=True)

del src, bem


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Do some minimal artifact rejection just for VectorView data
Can you write Python code for it?

titles = dict(vv='VectorView', opm='OPM')
ssp_ecg, _ = mne.preprocessing.compute_proj_ecg(
    raws['vv'], tmin=-0.1, tmax=0.1, n_grad=1, n_mag=1)
raws['vv'].add_proj(ssp_ecg, remove_existing=True)
# due to how compute_proj_eog works, it keeps the old projectors, so
# the output contains both projector types (and also the original empty-room
# projectors)
ssp_ecg_eog, _ = mne.preprocessing.compute_proj_eog(
    raws['vv'], n_grad=1, n_mag=1, ch_name='MEG0112')
raws['vv'].add_proj(ssp_ecg_eog, remove_existing=True)
raw_erms['vv'].add_proj(ssp_ecg_eog)
fig = mne.viz.plot_projs_topomap(raws['vv'].info['projs'][-4:],
                                 info=raws['vv'].info)
fig.suptitle(titles['vv'])
fig.subplots_adjust(0.05, 0.05, 0.95, 0.85)


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Explore data
Can you write Python code for it?

kinds = ('vv', 'opm')
n_fft = next_fast_len(int(round(4 * new_sfreq)))
print('Using n_fft=%d (%0.1f sec)' % (n_fft, n_fft / raws['vv'].info['sfreq']))
for kind in kinds:
    fig = raws[kind].plot_psd(n_fft=n_fft, proj=True)
    fig.suptitle(titles[kind])
    fig.subplots_adjust(0.1, 0.1, 0.95, 0.85)


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Gamma
Can you write Python code for it?

fig_gamma, brain_gamma = plot_band('vv', 'gamma')


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Load data, resample. We will store the raw objects in dicts with entries
"vv" and "opm" to simplify housekeeping and simplify looping later.
Can you write Python code for it?

raws = dict()
raw_erms = dict()
new_sfreq = 90.  # Nyquist frequency (45 Hz) < line noise freq (50 Hz)
raws['vv'] = mne.io.read_raw_fif(vv_fname, verbose='error')  # ignore naming
raws['vv'].load_data().resample(new_sfreq)
raws['vv'].info['bads'] = ['MEG2233', 'MEG1842']
raw_erms['vv'] = mne.io.read_raw_fif(vv_erm_fname, verbose='error')
raw_erms['vv'].load_data().resample(new_sfreq)
raw_erms['vv'].info['bads'] = ['MEG2233', 'MEG1842']

raws['opm'] = mne.io.read_raw_fif(opm_fname)
raws['opm'].load_data().resample(new_sfreq)
raw_erms['opm'] = mne.io.read_raw_fif(opm_erm_fname)
raw_erms['opm'].load_data().resample(new_sfreq)
# Make sure our assumptions later hold
assert raws['opm'].info['sfreq'] == raws['vv'].info['sfreq']


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Now we can make some plots of each frequency band. Note that the OPM head
coverage is only over right motor cortex, so only localization
of beta is likely to be worthwhile.
Theta
Can you write Python code for it?

def plot_band(kind, band):
    """Plot activity within a frequency band on the subject's brain."""
    title = "%s %s\n(%d-%d Hz)" % ((titles[kind], band,) + freq_bands[band])
    topos[kind][band].plot_topomap(
        times=0., scalings=1., cbar_fmt='%0.1f', vmin=0, cmap='inferno',
        time_format=title)
    brain = stcs[kind][band].plot(
        subject=subject, subjects_dir=subjects_dir, views='cau', hemi='both',
        time_label=title, title=title, colormap='inferno',
        time_viewer=False, show_traces=False,
        clim=dict(kind='percent', lims=(70, 85, 99)), smoothing_steps=10)
    brain.show_view(dict(azimuth=0, elevation=0), roll=0)
    return fig, brain

fig_theta, brain_theta = plot_band('vv', 'theta')


I am working on the file "0.22/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Then OPM:
Can you write Python code for it?

fig_beta_opm, brain_beta_opm = plot_band('opm', 'beta')


I am working on the file "0.22/_downloads/638c39682b0791ce4e430e4d2fcc4c45/plot_tf_dics.ipynb".
The first task is:
Time-frequency beamforming using DICS
Compute DICS source power :footcite:DalalEtAl2008 in a grid of time-frequency
windows.
Can you write Python code for it?

# Author: Roman Goj <roman.goj@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.event import make_fixed_length_events
from mne.datasets import sample
from mne.time_frequency import csd_fourier
from mne.beamformer import tf_dics
from mne.viz import plot_source_spectrogram

print(__doc__)

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
noise_fname = data_path + '/MEG/sample/ernoise_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
subjects_dir = data_path + '/subjects'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name


I am working on the file "0.22/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
.. sidebar:: The middle column of the Events array
MNE-Python events are actually *three* values: in between the sample
number and the integer event code is a value indicating what the event
code was on the immediately preceding sample. In practice, that value is
almost always ``0``, but it can be used to detect the *endpoint* of an
event whose duration is longer than one sample. See the documentation of
:func:`mne.find_events` for more details.

If you don't provide the name of a STIM channel, :func:~mne.find_events
will first look for MNE-Python config variables <tut-configure-mne>
for variables MNE_STIM_CHANNEL, MNE_STIM_CHANNEL_1, etc. If those are
not found, channels STI 014 and STI101 are tried, followed by the
first channel with type "STIM" present in raw.ch_names. If you regularly
work with data from several different MEG systems with different STIM channel
names, setting the MNE_STIM_CHANNEL config variable may not be very
useful, but for researchers whose data is all from a single system it can be
a time-saver to configure that variable once and then forget about it.
:func:~mne.find_events has several options, including options for aligning
events to the onset or offset of the STIM channel pulses, setting the minimum
pulse duration, and handling of consecutive pulses (with no return to zero
between them). For example, you can effectively encode event duration by
passing output='step' to :func:mne.find_events; see the documentation
of :func:~mne.find_events for details. More information on working with
events arrays (including how to plot, combine, load, and save event arrays)
can be found in the tutorial tut-event-arrays.
Reading embedded events as Annotations
Some EEG/MEG systems generate files where events are stored in a separate
data array rather than as pulses on one or more STIM channels. For example,
the EEGLAB format stores events as a collection of arrays in the :file:.set
file. When reading those files, MNE-Python will automatically convert the
stored events into an...
Can you write Python code for it?

testing_data_folder = mne.datasets.testing.data_path()
eeglab_raw_file = os.path.join(testing_data_folder, 'EEGLAB', 'test_raw.set')
eeglab_raw = mne.io.read_raw_eeglab(eeglab_raw_file)
print(eeglab_raw.annotations)


I am working on the file "0.22/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
Making multiple events per annotation
As mentioned above, you can generate equally-spaced events from an
:class:~mne.Annotations object using the chunk_duration parameter of
:func:~mne.events_from_annotations. For example, suppose we have an
annotation in our :class:~mne.io.Raw object indicating when the subject was
in REM sleep, and we want to perform a resting-state analysis on those spans
of data. We can create an Events array with a series of equally-spaced events
within each "REM" span, and then use those events to generate (potentially
overlapping) epochs that we can analyze further.
Can you write Python code for it?

# create the REM annotations
rem_annot = mne.Annotations(onset=[5, 41],
                            duration=[16, 11],
                            description=['REM'] * 2)
raw.set_annotations(rem_annot)
(rem_events,
 rem_event_dict) = mne.events_from_annotations(raw, chunk_duration=1.5)


I am working on the file "0.22/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
Now we can check that our events indeed fall in the ranges 5-21 seconds and
41-52 seconds, and are ~1.5 seconds apart (modulo some jitter due to the
sampling frequency). Here are the event times rounded to the nearest
millisecond:
Can you write Python code for it?

print(np.round((rem_events[:, 0] - raw.first_samp) / raw.info['sfreq'], 3))


I am working on the file "0.22/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
Now, the annotations will appear automatically when plotting the raw data,
and will be color-coded by their label value:
Can you write Python code for it?


I am working on the file "0.22/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
To make the opposite conversion (from an Events array to an
:class:~mne.Annotations object), you can create a mapping from integer
Event ID to string descriptions, use ~mne.annotations_from_events
to construct the :class:~mne.Annotations object, and call the
:meth:~mne.io.Raw.set_annotations method to add the annotations to the
:class:~mne.io.Raw object.
Because the sample data <sample-dataset> was recorded on a Neuromag
system (where sample numbering starts when the acquisition system is
initiated, not when the recording is initiated), we also need to pass in
the orig_time parameter so that the onsets are properly aligned relative
to the start of recording:
Can you write Python code for it?

mapping = {1: 'auditory/left', 2: 'auditory/right', 3: 'visual/left',
           4: 'visual/right', 5: 'smiley', 32: 'buttonpress'}
annot_from_events = mne.annotations_from_events(
    events=events, event_desc=mapping, sfreq=raw.info['sfreq'],
    orig_time=raw.info['meas_date'])
raw.set_annotations(annot_from_events)


I am working on the file "0.22/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
You can see that STI 014 (the summation channel) contains pulses of
different magnitudes whereas pulses on other channels have consistent
magnitudes. You can also see that every time there is a pulse on one of the
other STIM channels, there is a corresponding pulse on STI 014.
.. TODO: somewhere in prev. section, link out to a table of which systems
   have STIM channels vs. which have marker files or embedded event arrays
   (once such a table has been created).
Converting a STIM channel signal to an Events array
If your data has events recorded on a STIM channel, you can convert them into
an events array using :func:mne.find_events. The sample number of the onset
(or offset) of each pulse is recorded as the event time, the pulse magnitudes
are converted into integers, and these pairs of sample numbers plus integer
codes are stored in :class:NumPy arrays <numpy.ndarray> (usually called
"the events array" or just "the events"). In its simplest form, the function
requires only the :class:~mne.io.Raw object, and the name of the channel(s)
from which to read events:
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
print(events[:5])  # show the first 5


I am working on the file "0.22/_downloads/6f729e8febc223b1d7003304f207eea9/plot_40_epochs_to_data_frame.ipynb".
The first task is:
Exporting Epochs to Pandas DataFrames
This tutorial shows how to export the data in :class:~mne.Epochs objects to a
:class:Pandas DataFrame <pandas.DataFrame>, and applies a typical Pandas
:doc:split-apply-combine <pandas:user_guide/groupby> workflow to examine the
latencies of the response maxima across epochs and conditions.
   :depth: 2
We'll use the sample-dataset dataset, but load a version of the raw file
that has already been filtered and downsampled, and has an average reference
applied to its EEG channels. As usual we'll start by importing the modules we
need and loading the data:
Can you write Python code for it?

import os
import seaborn as sns
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)


I am working on the file "0.22/_downloads/6f729e8febc223b1d7003304f207eea9/plot_40_epochs_to_data_frame.ipynb".
The first task is:
Generating the :class:~pandas.DataFrame in long format can be helpful when
using other Python modules for subsequent analysis or plotting. For example,
here we'll take data from the "auditory/left" condition, pick a couple MEG
channels, and use :func:seaborn.lineplot to automatically plot the mean and
confidence band for each channel, with confidence computed across the epochs
in the chosen condition:
Can you write Python code for it?

channels = ['MEG 1332', 'MEG 1342']
data = long_df.loc['auditory/left'].query('channel in @channels')
# convert channel column (CategoryDtype → string; for a nicer-looking legend)
data['channel'] = data['channel'].astype(str)
sns.lineplot(x='time', y='value', hue='channel', data=data)


I am working on the file "0.22/_downloads/6f729e8febc223b1d7003304f207eea9/plot_40_epochs_to_data_frame.ipynb".
The first task is:
Scaling time and channel values
By default, time values are converted from seconds to milliseconds and
then rounded to the nearest integer; if you don't want this, you can pass
time_format=None to keep time as a :class:float value in seconds, or
convert it to a :class:~pandas.Timedelta value via
time_format='timedelta'.
Note also that, by default, channel measurement values are scaled so that EEG
data are converted to µV, magnetometer data are converted to fT, and
gradiometer data are converted to fT/cm. These scalings can be customized
through the scalings parameter, or suppressed by passing
scalings=dict(eeg=1, mag=1, grad=1).
Can you write Python code for it?

df = epochs.to_data_frame(time_format=None,
                          scalings=dict(eeg=1, mag=1, grad=1))
df.iloc[:5, :10]


I am working on the file "0.22/_downloads/6f729e8febc223b1d7003304f207eea9/plot_40_epochs_to_data_frame.ipynb".
The first task is:
We can also now use all the power of Pandas for grouping and transforming our
data. Here, we find the latency of peak activation of 2 gradiometers (one
near auditory cortex and one near visual cortex), and plot the distribution
of the timing of the peak in each channel as a :func:~seaborn.violinplot:
Can you write Python code for it?

df = epochs.to_data_frame(time_format=None)
peak_latency = (df.filter(regex=r'condition|epoch|MEG 1332|MEG 2123')
                .groupby(['condition', 'epoch'])
                .aggregate(lambda x: df['time'].iloc[x.idxmax()])
                .reset_index()
                .melt(id_vars=['condition', 'epoch'],
                      var_name='channel',
                      value_name='latency of peak')
                )

ax = sns.violinplot(x='channel', y='latency of peak', hue='condition',
                    data=peak_latency, palette='deep', saturation=1)


I am working on the file "0.22/_downloads/6f729e8febc223b1d7003304f207eea9/plot_40_epochs_to_data_frame.ipynb".
The first task is:
Wide- versus long-format DataFrames
Another parameter, long_format, determines whether each channel's data is
in a separate column of the :class:~pandas.DataFrame
(long_format=False), or whether the measured values are pivoted into a
single 'value' column with an extra indicator column for the channel name
(long_format=True). Passing long_format=True will also create an
extra column ch_type indicating the channel type.
Can you write Python code for it?

long_df = epochs.to_data_frame(time_format=None, index='condition',
                               long_format=True)
long_df.head()