I am working on the file "0.21/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
The source space
Let's start by examining the source space as constructed by the
:func:mne.setup_source_space function. Dipoles are placed along fixed
intervals on the cortex, determined by the spacing parameter. The source
space does not define the orientation for these dipoles.
Can you write Python code for it?

lh = fwd['src'][0]  # Visualize the left hemisphere
verts = lh['rr']  # The vertices of the source space
tris = lh['tris']  # Groups of three vertices that form triangles
dip_pos = lh['rr'][lh['vertno']]  # The position of the dipoles
dip_ori = lh['nn'][lh['vertno']]
dip_len = len(dip_pos)
dip_times = [0]
white = (1.0, 1.0, 1.0)  # RGB values for a white color

actual_amp = np.ones(dip_len)  # misc amp to create Dipole instance
actual_gof = np.ones(dip_len)  # misc GOF to create Dipole instance
dipoles = mne.Dipole(dip_times, dip_pos, actual_amp, dip_ori, actual_gof)
trans = mne.read_trans(trans_fname)

fig = mne.viz.create_3d_figure(size=(600, 400), bgcolor=white)
coord_frame = 'mri'

# Plot the cortex
fig = mne.viz.plot_alignment(subject=subject, subjects_dir=subjects_dir,
                             trans=trans, surfaces='white',
                             coord_frame=coord_frame, fig=fig)

# Mark the position of the dipoles with small red dots
fig = mne.viz.plot_dipole_locations(dipoles=dipoles, trans=trans,
                                    mode='sphere', subject=subject,
                                    subjects_dir=subjects_dir,
                                    coord_frame=coord_frame,
                                    scale=7e-4, fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.25)


I am working on the file "0.21/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
When computing the source estimate, the activity at each of the three dipoles
is collapsed into the XYZ components of a single vector, which leads to the
following source estimate for the sample data:
Can you write Python code for it?

# Make an inverse operator with loose dipole orientations
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=False,
                            loose=1.0)

# Compute the source estimate, indicate that we want a vector solution
stc = apply_inverse(left_auditory, inv, pick_ori='vector')

# Visualize it at the moment of peak activity.
_, time_max = stc.magnitude().get_peak(hemi='lh')
brain_mag = stc.plot(subjects_dir=subjects_dir, initial_time=time_max,
                     time_unit='s', size=(600, 400), overlay_alpha=0)


I am working on the file "0.21/_downloads/a2556d0f8dd65be2930ab61c812863c7/plot_read_epochs.ipynb".
The first task is:
Reading epochs from a raw FIF file
This script shows how to read the epochs from a raw file given
a list of events. For illustration, we compute the evoked responses
for both MEG and EEG data by averaging all the epochs.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.21/_downloads/a2556d0f8dd65be2930ab61c812863c7/plot_read_epochs.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

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

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))

evoked = epochs.average()  # average epochs to get the evoked response


I am working on the file "0.21/_downloads/a2556d0f8dd65be2930ab61c812863c7/plot_read_epochs.ipynb".
The first task is:
Show result
Can you write Python code for it?


I am working on the file "0.21/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb".
The first task is:
Classification with linear discrimant analysis
Can you write Python code for it?

# Define a monte-carlo cross-validation generator (reduce variance):
scores = []
epochs_data = epochs.get_data()
epochs_data_train = epochs_train.get_data()
cv = ShuffleSplit(10, test_size=0.2, random_state=42)
cv_split = cv.split(epochs_data_train)

# Assemble a classifier
lda = LinearDiscriminantAnalysis()
csp = CSP(n_components=4, reg=None, log=True, norm_trace=False)

# Use scikit-learn Pipeline with cross_val_score function
clf = Pipeline([('CSP', csp), ('LDA', lda)])
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1. - class_balance)
print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores),
                                                          class_balance))

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)

csp.plot_patterns(epochs.info, ch_type='eeg', units='Patterns (AU)', size=1.5)


I am working on the file "0.21/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb".
The first task is:
Look at performance over time
Can you write Python code for it?

sfreq = raw.info['sfreq']
w_length = int(sfreq * 0.5)   # running classifier: window length
w_step = int(sfreq * 0.1)  # running classifier: window step size
w_start = np.arange(0, epochs_data.shape[2] - w_length, w_step)

scores_windows = []

for train_idx, test_idx in cv_split:
    y_train, y_test = labels[train_idx], labels[test_idx]

    X_train = csp.fit_transform(epochs_data_train[train_idx], y_train)
    X_test = csp.transform(epochs_data_train[test_idx])

    # fit classifier
    lda.fit(X_train, y_train)

    # running classifier: test classifier on sliding window
    score_this_window = []
    for n in w_start:
        X_test = csp.transform(epochs_data[test_idx][:, :, n:(n + w_length)])
        score_this_window.append(lda.score(X_test, y_test))
    scores_windows.append(score_this_window)

# Plot scores over time
w_times = (w_start + w_length / 2.) / sfreq + epochs.tmin

plt.figure()
plt.plot(w_times, np.mean(scores_windows, 0), label='Score')
plt.axvline(0, linestyle='--', color='k', label='Onset')
plt.axhline(0.5, linestyle='-', color='k', label='Chance')
plt.xlabel('time (s)')
plt.ylabel('classification accuracy')
plt.title('Classification score over time')
plt.legend(loc='lower right')
plt.show()


I am working on the file "0.21/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb".
The first task is:
Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP)
Decoding of motor imagery applied to EEG data decomposed using CSP. A
classifier is then applied to features extracted on CSP-filtered signals.
See https://en.wikipedia.org/wiki/Common_spatial_pattern and [1]. The EEGBCI
dataset is documented in [2]. The data set is available at PhysioNet [3]_.
References
.. [1] Zoltan J. Koles. The quantitative extraction and topographic mapping
       of the abnormal components in the clinical EEG. Electroencephalography
       and Clinical Neurophysiology, 79(6):440--447, December 1991.
.. [2] Schalk, G., McFarland, D.J., Hinterberger, T., Birbaumer, N.,
       Wolpaw, J.R. (2004) BCI2000: A General-Purpose Brain-Computer Interface
       (BCI) System. IEEE TBME 51(6):1034-1043.
.. [3] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh, Mark RG,
       Mietus JE, Moody GB, Peng C-K, Stanley HE. (2000) PhysioBank,
       PhysioToolkit, and PhysioNet: Components of a New Research Resource for
       Complex Physiologic Signals. Circulation 101(23):e215-e220.
Can you write Python code for it?

# Authors: Martin Billinger <martin.billinger@tugraz.at>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import ShuffleSplit, cross_val_score

from mne import Epochs, pick_types, events_from_annotations
from mne.channels import make_standard_montage
from mne.io import concatenate_raws, read_raw_edf
from mne.datasets import eegbci
from mne.decoding import CSP

print(__doc__)

# #############################################################################
# # Set parameters and read data

# avoid classification of evoked responses by using epochs that start 1s after
# cue onset.
tmin, tmax = -1., 4.
event_id = dict(hands=2, feet=3)
subject = 1
runs = [6, 10, 14]  # motor imagery: hands vs feet

raw_fnames = eegbci.load_data(subject, runs)
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])
eegbci.standardize(raw)  # set channel names
montage = make_standard_montage('standard_1005')
raw.set_montage(montage)

# strip channel names of "." characters
raw.rename_channels(lambda x: x.strip('.'))

# Apply band-pass filter
raw.filter(7., 30., fir_design='firwin', skip_by_annotation='edge')

events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3))

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

# Read epochs (train will be done only between 1 and 2s)
# Testing will be done with a running classifier
epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,
                baseline=None, preload=True)
epochs_train = epochs.copy().crop(tmin=1., tmax=2.)
labels = epochs.events[:, -1] - 2


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Confusion matrix related to mental representations have been historically
summarized with dimensionality reduction using multi-dimensional scaling [1].
See how the face samples cluster together.
Can you write Python code for it?

fig, ax = plt.subplots(1)
mds = MDS(2, random_state=0, dissimilarity='precomputed')
chance = 0.5
summary = mds.fit_transform(chance - confusion)
cmap = plt.get_cmap('rainbow')
colors = ['r', 'b']
names = list(conds['condition'].values)
for color, name in zip(colors, set(names)):
    sel = np.where([this_name == name for this_name in names])[0]
    size = 500 if name == 'human face' else 100
    ax.scatter(summary[sel, 0], summary[sel, 1], s=size,
               facecolors=color, label=name, edgecolors='k')
ax.axis('off')
ax.legend(loc='lower right', scatterpoints=1, ncol=2)
plt.tight_layout()
plt.show()


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Epoch data
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=True)
epochs = mne.Epochs(raw, events=events, event_id=event_id, baseline=None,
                    picks=picks, tmin=-.1, tmax=.500, preload=True)


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Let's plot some conditions
Can you write Python code for it?


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Let's restrict the number of conditions to speed up computation
Can you write Python code for it?

max_trigger = 24
conds = conds[:max_trigger]  # take only the first 24 rows


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Plot
Can you write Python code for it?

labels = [''] * 5 + ['face'] + [''] * 11 + ['bodypart'] + [''] * 6
fig, ax = plt.subplots(1)
im = ax.matshow(confusion, cmap='RdBu_r', clim=[0.3, 0.7])
ax.set_yticks(range(len(classes)))
ax.set_yticklabels(labels)
ax.set_xticks(range(len(classes)))
ax.set_xticklabels(labels, rotation=40, ha='left')
ax.axhline(11.5, color='k')
ax.axvline(11.5, color='k')
plt.colorbar(im)
plt.tight_layout()
plt.show()


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Read MEG data
Can you write Python code for it?

n_runs = 4  # 4 for full data (use less to speed up computations)
fname = op.join(data_path, 'sample_subject_%i_tsss_mc.fif')
raws = [read_raw_fif(fname % block, verbose='error')
        for block in range(n_runs)]  # ignore filename warnings
raw = concatenate_raws(raws)

events = mne.find_events(raw, min_duration=.002)

events = events[events[:, 2] <= max_trigger]


I am working on the file "0.21/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Representational Similarity Analysis
Representational Similarity Analysis is used to perform summary statistics
on supervised classifications where the number of classes is relatively high.
It consists in characterizing the structure of the confusion matrix to infer
the similarity between brain responses and serves as a proxy for characterizing
the space of mental representations [1] [2] [3]_.
In this example, we perform RSA on responses to 24 object images (among
a list of 92 images). Subjects were presented with images of human, animal
and inanimate objects [4]_. Here we use the 24 unique images of faces
and body parts.

Note

this example will download a very large (~6GB) file, so we will not
          build the images below.

References
.. [1] Shepard, R. "Multidimensional scaling, tree-fitting, and clustering."
       Science 210.4468 (1980): 390-398.
.. [2] Laakso, A. & Cottrell, G.. "Content and cluster analysis:
       assessing representational similarity in neural systems." Philosophical
       psychology 13.1 (2000): 47-76.
.. [3] Kriegeskorte, N., Marieke, M., & Bandettini.  P. "Representational
       similarity analysis-connecting the branches of systems neuroscience."
       Frontiers in systems neuroscience 2 (2008): 4.
.. [4] Cichy, R. M., Pantazis, D., & Oliva, A. "Resolving human object
       recognition in space and time." Nature neuroscience (2014): 17(3),
       455-462.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import os.path as op
import numpy as np
from pandas import read_csv
import matplotlib.pyplot as plt

from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.manifold import MDS

import mne
from mne.io import read_raw_fif, concatenate_raws
from mne.datasets import visual_92_categories

print(__doc__)

data_path = visual_92_categories.data_path()

# Define stimulus - trigger mapping
fname = op.join(data_path, 'visual_stimuli.csv')
conds = read_csv(fname)
print(conds.head(5))


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
:class:~mne.Epochs objects are a data structure for representing and
analyzing equal-duration chunks of the EEG/MEG signal. :class:~mne.Epochs
are most often used to represent data that is time-locked to repeated
experimental events (such as stimulus onsets or subject button presses), but
can also be used for storing sequential or overlapping frames of a continuous
signal (e.g., for analysis of resting-state activity; see
fixed-length-events). Inside an :class:~mne.Epochs object, the data
are stored in an :class:array <numpy.ndarray> of shape (n_epochs,
n_channels, n_times).
:class:~mne.Epochs objects have many similarities with :class:~mne.io.Raw
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> through the
  :meth:~mne.Epochs.get_data method or to a :class:Pandas DataFrame
  <pandas.DataFrame> through the :meth:~mne.Epochs.to_data_frame method.

Both :class:~mne.Epochs and :class:~mne.io.Raw objects support channel
  selection by index or name, including :meth:~mne.Epochs.pick,
  :meth:~mne.Epochs.pick_channels and :meth:~mne.Epochs.pick_types
  methods.

:term:SSP projector <projector> manipulation is possible through
  :meth:~mne.Epochs.add_proj, :meth:~mne.Epochs.del_proj, and
  :meth:~mne.Epochs.plot_projs_topomap methods.

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

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

Both :class:~mne.Epochs and :class:~mne.io.Raw objects have built-in
  plotting methods :meth:~mne.Epochs.plot, :meth:~mne.Epochs.plot_psd,
  and :meth:~mne.Epochs.plot_psd_topomap.

Creating Epoched data from a Raw object
The example dataset we've been using...
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).crop(tmax=60)


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:

Note

We could also have loaded the events from file, using
    :func:`mne.read_events`::

        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)

    See `tut-section-events-io` for more details.

The :class:~mne.io.Raw object and the events array are the bare minimum
needed to create an :class:~mne.Epochs object, which we create with the
:class:mne.Epochs class constructor. However, you will almost surely want
to change some of the other default parameters. Here we'll change tmin
and tmax (the time relative to each event at which to start and end each
epoch). Note also that the :class:~mne.Epochs constructor accepts
parameters reject and flat for rejecting individual epochs based on
signal amplitude. See the tut-reject-epochs-section section for
examples.
Can you write Python code for it?

epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7)


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
As we saw in the tut-events-vs-annotations tutorial, we can extract an
events array from :class:~mne.io.Raw objects 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.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Changing channel name and type
You can change the name or type of a channel using
:meth:~mne.Epochs.rename_channels or :meth:~mne.Epochs.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.
Can you write Python code for it?

epochs.rename_channels({'EOG 061': 'BlinkChannel'})

epochs.set_channel_types({'EEG 060': 'ecg'})
print(list(zip(epochs.ch_names, epochs.get_channel_types()))[-4:])

# let's set them back to the correct values before moving on
epochs.rename_channels({'BlinkChannel': 'EOG 061'})
epochs.set_channel_types({'EEG 060': 'eeg'})


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
However, if no match is found, an error is returned:
Can you write Python code for it?

try:
    print(epochs[['top', 'bottom']])
except KeyError:
    print('Tag-based selection with no matches raises a KeyError!')


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
However, if you wanted to expand the time domain of an :class:~mne.Epochs
object, you would need to go back to the :class:~mne.io.Raw data and
recreate the :class:~mne.Epochs with different values for tmin and/or
tmax.
It is also possible to change the "zero point" that defines the time values
in an :class:~mne.Epochs object, with the :meth:~mne.Epochs.shift_time
method. :meth:~mne.Epochs.shift_time allows shifting times relative to the
current values, or specifying a fixed time to set as the new time value of
the first sample (deriving the new time values of subsequent samples based on
the :class:~mne.Epochs object's sampling frequency).
Can you write Python code for it?

# shift times so that first sample of each epoch is at time zero
later_epochs = epochs.copy().shift_time(tshift=0., relative=False)
print(later_epochs.times[:3])

# shift times by a relative amount
later_epochs.shift_time(tshift=-7, relative=True)
print(later_epochs.times[:3])

del shorter_epochs, later_epochs


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
If you want to iterate over :class:~mne.Epochs objects, you can use an
integer index as the iterator:
Can you write Python code for it?

for index in range(3):
    print(type(epochs[index]))


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
In almost all cases this will not require changing anything about your code.
However, if you need to do type checking on epochs objects, you can test
against the base class that these classes are derived from:
Can you write Python code for it?

print(all([isinstance(epochs, mne.BaseEpochs),
           isinstance(epochs_from_file, mne.BaseEpochs)]))


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Note that if your analysis requires repeatedly extracting single epochs from
an :class:~mne.Epochs object, epochs.get_data(item=2) will be much
faster than epochs[2].get_data(), because it avoids the step of
subsetting the :class:~mne.Epochs object first.
You can also export :class:~mne.Epochs data to :class:Pandas DataFrames
<pandas.DataFrame>. Here, the :class:~pandas.DataFrame index will be
constructed by converting the time of each sample into milliseconds and
rounding it to the nearest integer, and combining it with the event types and
epoch numbers to form a hierarchical :class:~pandas.MultiIndex. Each
channel will appear in a separate column. Then you can use any of Pandas'
tools for grouping and aggregating data; for example, here we select any
epochs numbered 10 or less from the auditory/left condition, and extract
times between 100 and 107 ms on channels EEG 056 through EEG 058
(note that slice indexing within Pandas' :obj:~pandas.DataFrame.loc is
inclusive of the endpoint):
Can you write Python code for it?

df = epochs.to_data_frame(index=['condition', 'epoch', 'time'])
df.sort_index(inplace=True)
print(df.loc[('auditory/left', slice(0, 10), slice(100, 107)),
             'EEG 056':'EEG 058'])

del df


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Notice that the individual epochs are sequentially numbered along the bottom
axis; the event ID associated with the epoch is marked on the top axis;
epochs are separated by vertical dashed lines; and a vertical solid green
line marks time=0 for each epoch (i.e., in this case, the stimulus onset
time for each trial). Epoch plots are interactive (similar to
:meth:raw.plot() <mne.io.Raw.plot>) and have many of the same interactive
controls as :class:~mne.io.Raw plots. Horizontal and vertical scrollbars
allow browsing through epochs or channels (respectively), and pressing
:kbd:? when the plot is focused will show a help screen with all the
available controls. See tut-visualize-epochs for more details (as well
as other ways of visualizing epoched data).
Subselecting epochs
Now that we have our :class:~mne.Epochs object with our descriptive event
labels added, we can subselect epochs easily using square brackets. For
example, we can load all the "catch trials" where the stimulus was a face:
Can you write Python code for it?


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Notice that the output now mentions "1 bad epoch dropped". In the tutorial
section tut-reject-epochs-section we saw how you can specify channel
amplitude criteria for rejecting epochs, but here we haven't specified any
such criteria. In this case, it turns out that the last event was too close
the end of the (cropped) raw file to accommodate our requested tmax of
0.7 seconds, so the final epoch was dropped because it was too short. Here
are the drop_log entries for the last 4 epochs (empty lists indicate
epochs that were not dropped):
Can you write Python code for it?


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
See the tut-epochs-dataframe tutorial for many more examples of the
:meth:~mne.Epochs.to_data_frame method.
Loading and saving Epochs objects to disk
:class:~mne.Epochs objects can be loaded and saved in the .fif format
just like :class:~mne.io.Raw objects, using the :func:mne.read_epochs
function and the :meth:~mne.Epochs.save method. Functions are also
available for loading data that was epoched outside of MNE-Python, such as
:func:mne.read_epochs_eeglab and :func:mne.read_epochs_kit.
Can you write Python code for it?

epochs.save('saved-audiovisual-epo.fif', overwrite=True)
epochs_from_file = mne.read_epochs('saved-audiovisual-epo.fif', preload=False)


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Selecting epochs by index
:class:~mne.Epochs objects can also be indexed with integers, :term:slices
<slice>, or lists of integers. This method of selection ignores event
labels, so if you want the first 10 epochs of a particular type, you can
select the type first, then use integers or slices:
Can you write Python code for it?

print(epochs[:10])    # epochs 0-9
print(epochs[1:8:2])  # epochs 1, 3, 5, 7

print(epochs['buttonpress'][:4])            # first 4 "buttonpress" epochs
print(epochs['buttonpress'][[0, 1, 2, 3]])  # same as previous line


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Selecting, dropping, and reordering channels
You can use the :meth:~mne.Epochs.pick, :meth:~mne.Epochs.pick_channels,
:meth:~mne.Epochs.pick_types, and :meth:~mne.Epochs.drop_channels methods
to modify which channels are included in an :class:~mne.Epochs object. You
can also use :meth:~mne.Epochs.reorder_channels for this purpose; any
channel names not provided to :meth:~mne.Epochs.reorder_channels will be
dropped. Note that these channel selection methods modify the object
in-place (unlike the square-bracket indexing to select epochs seen above)
so in interactive/exploratory sessions you may want to create a
:meth:~mne.Epochs.copy first.
Can you write Python code for it?

epochs_eeg = epochs.copy().pick_types(meg=False, eeg=True)
print(epochs_eeg.ch_names)

new_order = ['EEG 002', 'STI 014', 'EOG 061', 'MEG 2521']
epochs_subset = epochs.copy().reorder_channels(new_order)
print(epochs_subset.ch_names)

del epochs_eeg, epochs_subset


I am working on the file "0.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
The Epochs data structure: discontinuous data
This tutorial covers the basics of creating and working with :term:epoched
<epochs> data. It introduces the :class:~mne.Epochs data structure in
detail, including how to load, query, subselect, export, and plot data from an
:class:~mne.Epochs object. For more information about visualizing
:class:~mne.Epochs objects, see tut-visualize-epochs. For info on
creating an :class:~mne.Epochs 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.21/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
The MNE-Python naming convention for epochs files is that the file basename
(the part before the .fif or .fif.gz extension) should end with
-epo or _epo, and a warning will be issued if the filename you
provide does not adhere to that convention.
As a final note, be aware that the class of the epochs object is different
when epochs are loaded from disk rather than generated from a
:class:~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
.. sidebar:: Head coordinate frame
 The head coordinate frame in MNE is the "Neuromag" head coordinate
 frame. The origin is given by the intersection between a line connecting
 the LPA and RPA and the line orthogonal to it that runs through the
 nasion. It is also in RAS orientation, meaning that +X runs through
 the RPA, +Y goes through the nasion, and +Z is orthogonal to these
 pointing upward. See `coordinate_systems` for more information.

Notice that in "head" coordinate frame the nasion has values of 0 for the
x and z directions (which makes sense given that the nasion is used
to define the y axis in that system).
To convert from head coordinate frame to voxels, we first apply the head →
MRI (surface RAS) transform
from a :file:trans file (typically created with the MNE-Python
coregistration GUI), then convert meters → millimeters, and finally apply the
inverse of Torig to get to voxels.
Under the hood, functions like :func:mne.setup_source_space,
:func:mne.setup_volume_source_space, and :func:mne.compute_source_morph
make extensive use of these coordinate frames.
Can you write Python code for it?

trans = mne.read_trans(
    os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif'))

# first we transform from head to MRI, and *then* convert to millimeters
nasion_dig_mri = apply_trans(trans, nasion_head['r']) * 1000

# ...then we can use Torig to convert MRI to voxels:
nasion_dig_vox = np.round(
    apply_trans(np.linalg.inv(Torig), nasion_dig_mri)).astype(int)
imshow_mri(data, t1, nasion_dig_vox, dict(MRI=nasion_dig_mri),
           'Nasion transformed from digitization')


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
If you have a point (x, y, z) in scanner-native RAS space and you want
the corresponding voxel number, you can get it using the inverse of the
affine. This involves some rounding, so it's possible to end up off by one
voxel if you're not careful:
Can you write Python code for it?

ras_coords_mm = np.array([1, -17, -18])
inv_affine = np.linalg.inv(t1.affine)
i_, j_, k_ = np.round(apply_trans(inv_affine, ras_coords_mm)).astype(int)
print('Our real-world coordinates correspond to voxel ({}, {}, {})'
      .format(i_, j_, k_))


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
Let's look a bit more closely at the spherical alignment by overlaying the
two spherical meshes as wireframes and zooming way in (the purple points are
separated by about 1 mm):
Can you write Python code for it?

cyan = '#66CCEE'
purple = '#AA3377'
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 800), scene=False, **renderer_kwargs)
fnames = [os.path.join(subjects_dir, subj, 'surf', 'rh.sphere')
          for subj in ('sample', 'fsaverage')]
colors = [cyan, purple]
for name, color in zip(fnames, colors):
    this_rr, this_tri = mne.read_surface(name)
    renderer.mesh(*this_rr.T, triangles=this_tri, color=color,
                  representation='wireframe')
mne.viz.set_3d_view(figure=renderer.figure, distance=20, **view_kwargs)
renderer.show()


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
Let's write a short function to visualize where our voxel lies in an
image, and annotate it in RAS space (rounded to the nearest millimeter):
Can you write Python code for it?

def imshow_mri(data, img, vox, xyz, suptitle):
    """Show an MRI slice with a voxel annotated."""
    i, j, k = vox
    fig, ax = plt.subplots(1, figsize=(6, 6))
    codes = nibabel.orientations.aff2axcodes(img.affine)
    # Figure out the title based on the code of this axis
    ori_slice = dict(P='Coronal', A='Coronal',
                     I='Axial', S='Axial',
                     L='Sagittal', R='Saggital')
    ori_names = dict(P='posterior', A='anterior',
                     I='inferior', S='superior',
                     L='left', R='right')
    title = ori_slice[codes[0]]
    ax.imshow(data[i], vmin=10, vmax=120, cmap='gray', origin='lower')
    ax.axvline(k, color='y')
    ax.axhline(j, color='y')
    for kind, coords in xyz.items():
        annotation = ('{}: {}, {}, {} mm'
                      .format(kind, *np.round(coords).astype(int)))
        text = ax.text(k, j, annotation, va='baseline', ha='right',
                       color=(1, 1, 0.7))
        text.set_path_effects([
            path_effects.Stroke(linewidth=2, foreground='black'),
            path_effects.Normal()])
    # reorient view so that RAS is always rightward and upward
    x_order = -1 if codes[2] in 'LIP' else 1
    y_order = -1 if codes[1] in 'LIP' else 1
    ax.set(xlim=[0, data.shape[2] - 1][::x_order],
           ylim=[0, data.shape[1] - 1][::y_order],
           xlabel=f'k ({ori_names[codes[2]]}+)',
           ylabel=f'j ({ori_names[codes[1]]}+)',
           title=f'{title} view: i={i} ({ori_names[codes[0]]}+)')
    fig.suptitle(suptitle)
    fig.subplots_adjust(0.1, 0.1, 0.95, 0.85)
    return fig

imshow_mri(data, t1, vox, {'Scanner RAS': xyz_ras}, 'MRI slice')


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
MRI coordinate frames
Let's start out by looking at the sample subject MRI. Following standard
FreeSurfer convention, we look at :file:T1.mgz, which gets created from the
original MRI :file:sample/mri/orig/001.mgz when you run the FreeSurfer
command recon-all <https://surfer.nmr.mgh.harvard.edu/fswiki/recon-all>_.
Here we use :mod:nibabel to load the T1 image, and the resulting object's
:meth:~nibabel.spatialimages.SpatialImage.orthoview method to view it.
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
subjects_dir = os.path.join(data_path, 'subjects')
subject = 'sample'
t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz')
t1 = nibabel.load(t1_fname)
t1.orthoview()


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
Notice that the axes in the
:meth:~nibabel.spatialimages.SpatialImage.orthoview figure are labeled
L-R, S-I, and P-A. These reflect the standard RAS (right-anterior-superior)
coordinate system that is widely used in MRI imaging. If you are unfamiliar
with RAS coordinates, see the excellent nibabel tutorial
:doc:nibabel:coordinate_systems.
Nibabel already takes care of some coordinate frame transformations under the
hood, so let's do it manually so we understand what is happening. First let's
get our data as a 3D array and note that it's already a standard size:
Can you write Python code for it?

data = np.asarray(t1.dataobj)
print(data.shape)


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
These data are voxel intensity values. Here they are unsigned integers in the
range 0-255, though in general they can be floating point values. A value
data[i, j, k] at a given index triplet (i, j, k) corresponds to some
real-world physical location (x, y, z) in space. To get its physical
location, first we have to choose what coordinate frame we're going to use.
For example, we could choose a geographical coordinate
frame, with origin is at the center of the earth, Z axis through the north
pole, X axis through the prime meridian (zero degrees longitude), and Y axis
orthogonal to these forming a right-handed coordinate system. This would not
be a very useful choice for defining the physical locations of the voxels
during the MRI acquisition for analysis, but you could nonetheless figure out
the transformation that related the (i, j, k) to this coordinate frame.
Instead, each scanner defines a more practical, native coordinate system that
it uses during acquisition, usually related to the physical orientation of
the scanner itself and/or the subject within it. During acquisition the
relationship between the voxel indices (i, j, k) and the physical
location (x, y, z) in the scanner's native coordinate frame is saved in
the image's affine transformation.
.. sidebar:: Under the hood
``mne.transforms.apply_trans`` effectively does a matrix multiplication
(i.e., :func:`numpy.dot`), with a little extra work to handle the shape
mismatch (the affine has shape ``(4, 4)`` because it includes a
*translation*, which is applied separately).

We can use :mod:nibabel to examine this transformation, keeping in mind
that it processes everything in units of millimeters, unlike MNE where things
are always in SI units (meters).
This allows us to take an arbitrary voxel or slice of data and know where it
is in the scanner's native physical space (x, y, z) (in mm) by applying
the affine transformation to the voxel coordinates.
Can you write Python code for it?

print(t1.affine)
vox = np.array([122, 119, 102])
xyz_ras = apply_trans(t1.affine, vox)
print('Our voxel has real-world coordinates {}, {}, {} (mm)'
      .format(*np.round(xyz_ras, 3)))


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
This is the method used by :func:mne.viz.plot_bem to show the BEM surfaces.
Cortical alignment (spherical)
A critical function provided by FreeSurfer is spherical surface alignment
of cortical surfaces, maximizing sulcal-gyral alignment. FreeSurfer first
expands the cortical surface to a sphere, then aligns it optimally with
fsaverage. Because the vertex ordering is preserved when expanding to a
sphere, a given vertex in the source (sample) mesh can be mapped easily
to the same location in the destination (fsaverage) mesh, and vice-versa.
Can you write Python code for it?

renderer_kwargs = dict(bgcolor='w', smooth_shading=False)
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 400), scene=False, **renderer_kwargs)
curvs = [
    (mne.surface.read_curvature(os.path.join(
        subjects_dir, subj, 'surf', 'rh.curv'),
        binary=False) > 0).astype(float)
    for subj in ('sample', 'fsaverage') for _ in range(2)]
fnames = [os.path.join(subjects_dir, subj, 'surf', surf)
          for subj in ('sample', 'fsaverage')
          for surf in ('rh.white', 'rh.sphere')]
y_shifts = [-450, -150, 450, 150]
z_shifts = [-40, 0, -30, 0]
for name, y_shift, z_shift, curv in zip(fnames, y_shifts, z_shifts, curvs):
    this_rr, this_tri = mne.read_surface(name)
    this_rr += [0, y_shift, z_shift]
    renderer.mesh(*this_rr.T, triangles=this_tri, color=None, scalars=curv,
                  colormap='copper_r', vmin=-0.2, vmax=1.2)
zero = [0., 0., 0.]
width = 50.
y = np.sort(y_shifts)
y = (y[1:] + y[:-1]) / 2. - width / 2.
renderer.quiver3d(zero, y, zero,
                  zero, [1] * 3, zero, 'k', width, 'arrow')
view_kwargs['focalpoint'] = (0., 0., 0.)
mne.viz.set_3d_view(figure=renderer.figure, distance=1000, **view_kwargs)
renderer.show()


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
We can also plot the mesh on top of an MRI slice. The mesh surfaces are
defined in millimeters in the MRI (FreeSurfer surface RAS) coordinate frame,
so we can convert them to voxels by applying the inverse of the Torig
transform:
Can you write Python code for it?

rr_vox = apply_trans(np.linalg.inv(Torig), rr_mm)
fig = imshow_mri(data, t1, vox, {'Scanner RAS': xyz_ras}, 'MRI slice')
# Based on how imshow_mri works, the "X" here is the last dim of the MRI vol,
# the "Y" is the middle dim, and the "Z" is the first dim, so now that our
# points are in the correct coordinate frame, we need to ask matplotlib to
# do a tricontour slice like:
fig.axes[0].tricontour(rr_vox[:, 2], rr_vox[:, 1], tris, rr_vox[:, 0],
                       levels=[vox[0]], colors='r', linewidths=1.0,
                       zorder=1)


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
We can also take the digitization point from the MEG data, which is in the
"head" coordinate frame.
Let's look at the nasion in the head coordinate frame:
Can you write Python code for it?

info = mne.io.read_info(
    os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif'))
nasion_head = [d for d in info['dig'] if
               d['kind'] == FIFF.FIFFV_POINT_CARDINAL and
               d['ident'] == FIFF.FIFFV_POINT_NASION][0]
print(nasion_head)  # note it's in "head" coordinates


I am working on the file "0.21/_downloads/ae9cc85c6d8aba1f86c6e34f8a59cbb7/plot_background_freesurfer_mne.ipynb".
The first task is:
You can see that the fsaverage (purple) mesh is uniformly spaced, and the
mesh for subject "sample" (in cyan) has been deformed along the spherical
surface by
FreeSurfer. This deformation is designed to optimize the sulcal-gyral
alignment.
Surface decimation
These surfaces have a lot of vertices, and in general we only need to use
a subset of these vertices for creating source spaces. A uniform sampling can
easily be achieved by subsampling in the spherical space. To do this, we
use a recursively subdivided icosahedron or octahedron. For example, let's
load a standard oct-6 source space, and at the same zoom level as before
visualize how it subsampled the dense mesh:
Can you write Python code for it?

src = mne.read_source_spaces(os.path.join(subjects_dir, 'sample', 'bem',
                                          'sample-oct-6-src.fif'))
print(src)

blue = '#4477AA'
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 800), scene=False, **renderer_kwargs)
rr_sph, _ = mne.read_surface(fnames[0])
for tris, color in [(src[1]['tris'], cyan), (src[1]['use_tris'], blue)]:
    renderer.mesh(*rr_sph.T, triangles=tris, color=color,
                  representation='wireframe')
mne.viz.set_3d_view(figure=renderer.figure, distance=20, **view_kwargs)
renderer.show()


I am working on the file "0.21/_downloads/b6ed91fbff318e8f41327003eca14299/plot_read_and_write_raw_data.ipynb".
The first task is:
Reading and writing raw files
In this example, we read a raw file. Plot a segment of MEG data
restricted to MEG channels. And save these data in a new
raw file.
Can you write Python code for it?

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

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis_raw.fif'

raw = mne.io.read_raw_fif(fname)

# Set up pick list: MEG + STI 014 - bad channels
want_meg = True
want_eeg = False
want_stim = False
include = ['STI 014']
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bad channels + 2 more

picks = mne.pick_types(raw.info, meg=want_meg, eeg=want_eeg, stim=want_stim,
                       include=include, exclude='bads')

some_picks = picks[:5]  # take 5 first
start, stop = raw.time_as_index([0, 15])  # read the first 15s of data
data, times = raw[some_picks, start:(stop + 1)]

# save 150s of MEG data in FIF file
raw.save('sample_audvis_meg_trunc_raw.fif', tmin=0, tmax=150, picks=picks,
         overwrite=True)


I am working on the file "0.21/_downloads/b6ed91fbff318e8f41327003eca14299/plot_read_and_write_raw_data.ipynb".
The first task is:
Show MEG data
Can you write Python code for it?


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
If you prefer untransformed power estimates, you can pass dB=False. It is
also possible to normalize the power estimates by dividing by the total power
across all frequencies, by passing normalize=True. See the docstring of
:meth:~mne.Epochs.plot_psd_topomap for details.
Plotting Epochs as an image map
A convenient way to visualize many epochs simultaneously is to plot them as
an image map, with each row of pixels in the image representing a single
epoch, the horizontal axis representing time, and each pixel's color
representing the signal value at that time sample for that epoch. Of course,
this requires either a separate image map for each channel, or some way of
combining information across channels. The latter is possible using the
:meth:~mne.Epochs.plot_image method; the former can be achieved with the
:meth:~mne.Epochs.plot_image method (one channel at a time) or with the
:meth:~mne.Epochs.plot_topo_image method (all sensors at once).
By default, the image map generated by :meth:~mne.Epochs.plot_image will be
accompanied by a scalebar indicating the range of the colormap, and a time
series showing the average signal across epochs and a bootstrapped 95%
confidence band around the mean. :meth:~mne.Epochs.plot_image is a highly
customizable method with many parameters, including customization of the
auxiliary colorbar and averaged time series subplots. See the docstrings of
:meth:~mne.Epochs.plot_image and mne.viz.plot_compare_evokeds (which is
used to plot the average time series) for full details. Here we'll show the
mean across magnetometers for all epochs with an auditory stimulus:
Can you write Python code for it?


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Just as we saw in the tut-section-raw-plot-proj section, we can plot
the projectors present in an :class:~mne.Epochs object using the same
:meth:~mne.Epochs.plot_projs_topomap method. Since the original three
empty-room magnetometer projectors were inherited from the
:class:~mne.io.Raw file, and we added two ECG projectors for each sensor
type, we should see nine projector topomaps:
Can you write Python code for it?


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Note that these field maps illustrate aspects of the signal that have
already been removed (because projectors in :class:~mne.io.Raw data are
applied by default when epoching, and because we called
:meth:~mne.Epochs.apply_proj after adding additional ECG projectors from
file). You can check this by examining the 'active' field of the
projectors:
Can you write Python code for it?

print(all(proj['active'] for proj in epochs.info['projs']))


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting Epochs as time series
.. sidebar:: Interactivity in pipelines and scripts
To use the interactive features of the :meth:`~mne.Epochs.plot` method
when running your code non-interactively, pass the ``block=True``
parameter, which halts the Python interpreter until the figure window is
closed. That way, any channels or epochs that you mark as "bad" will be
taken into account in subsequent processing steps.

To visualize epoched data as time series (one time series per channel), the
:meth:mne.Epochs.plot method is available. It creates an interactive window
where you can scroll through epochs and channels, enable/disable any
unapplied :term:SSP projectors <projector> to see how they affect the
signal, and even manually mark bad channels (by clicking the channel name) or
bad epochs (by clicking the data) for later dropping. Channels marked "bad"
will be shown in light grey color and will be added to
epochs.info['bads']; epochs marked as bad will be indicated as 'USER'
in epochs.drop_log.
Here we'll plot only the "catch" trials from the sample dataset
<sample-dataset>, and pass in our events array so that the button press
responses also get marked (we'll plot them in red, and plot the "face" events
defining time zero for each epoch in blue). We also need to pass in
our event_dict so that the :meth:~mne.Epochs.plot method will know what
we mean by "buttonpress" — this is because subsetting the conditions by
calling epochs['face'] automatically purges the dropped entries from
epochs.event_id:
Can you write Python code for it?

catch_trials_and_buttonpresses = mne.pick_events(events, include=[5, 32])
epochs['face'].plot(events=catch_trials_and_buttonpresses, event_id=event_dict,
                    event_colors=dict(buttonpress='red', face='blue'))


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting projectors from an Epochs object
In the plot above we can see heartbeat artifacts in the magnetometer
channels, so before we continue let's load ECG projectors from disk and apply
them to the data:
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)
epochs.add_proj(ecg_projs)
epochs.apply_proj()


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting sensor locations
Just like :class:~mne.io.Raw objects, :class:~mne.Epochs objects
keep track of sensor locations, which can be visualized with the
:meth:~mne.Epochs.plot_sensors method:
Can you write Python code for it?

epochs.plot_sensors(kind='3d', ch_type='all')
epochs.plot_sensors(kind='topomap', ch_type='all')


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting the power spectrum of Epochs
Again, just like :class:~mne.io.Raw objects, :class:~mne.Epochs objects
have a :meth:~mne.Epochs.plot_psd method for plotting the spectral
density_ of the data.
Can you write Python code for it?


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
To create the :class:~mne.Epochs data structure, we'll extract the event
IDs stored in the :term:stim channel, map those integer event IDs to more
descriptive condition labels using an event dictionary, and pass those to the
:class:~mne.Epochs constructor, along with the :class:~mne.io.Raw data
and the desired temporal limits of our epochs, tmin and tmax (for a
detailed explanation of these steps, see tut-epochs-class).
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'face': 5, 'buttonpress': 32}
epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, event_id=event_dict,
                    preload=True)
del raw


I am working on the file "0.21/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
To plot image maps for all EEG sensors, pass an EEG layout as the layout
parameter of :meth:~mne.Epochs.plot_topo_image. Note also here the use of
the sigma parameter, which smooths each image map along the vertical
dimension (across epochs) which can make it easier to see patterns across the
small image maps (by smearing noisy epochs onto their neighbors, while
reinforcing parts of the image where adjacent epochs are similar). However,
sigma can also disguise epochs that have persistent extreme values and
maybe should have been excluded, so it should be used with caution.
Can you write Python code for it?

layout = mne.channels.find_layout(epochs.info, ch_type='eeg')
epochs['auditory/left'].plot_topo_image(layout=layout, fig_facecolor='w',
                                        font_color='k', sigma=1)


I am working on the file "0.21/_downloads/bf3ad991f7c7776e245520709f49cb04/plot_cwt_sensor_connectivity.ipynb".
The first task is:
Compute seed-based time-frequency connectivity in sensor space
Computes the connectivity between a seed-gradiometer close to the visual cortex
and all other gradiometers. The connectivity is computed in the time-frequency
domain using Morlet wavelets and the debiased squared weighted phase lag index
[1]_ is used as connectivity metric.
.. [1] Vinck et al. "An improved index of phase-synchronization for electro-
       physiological data in the presence of volume-conduction, noise and
       sample-size bias" NeuroImage, vol. 55, no. 4, pp. 1548-1565, Apr. 2011.
Can you write Python code for it?

# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne import io
from mne.connectivity import spectral_connectivity, seed_target_indices
from mne.datasets import sample
from mne.time_frequency import AverageTFR

print(__doc__)


I am working on the file "0.21/_downloads/bf3ad991f7c7776e245520709f49cb04/plot_cwt_sensor_connectivity.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'

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

# Add a bad channel
raw.info['bads'] += ['MEG 2443']

# Pick MEG gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=True,
                       exclude='bads')

# Create epochs for left-visual condition
event_id, tmin, tmax = 3, -0.2, 0.5
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)

# Use 'MEG 2343' as seed
seed_ch = 'MEG 2343'
picks_ch_names = [raw.ch_names[i] for i in picks]

# Create seed-target indices for connectivity computation
seed = picks_ch_names.index(seed_ch)
targets = np.arange(len(picks))
indices = seed_target_indices(seed, targets)

# Define wavelet frequencies and number of cycles
cwt_freqs = np.arange(7, 30, 2)
cwt_n_cycles = cwt_freqs / 7.

# Run the connectivity analysis using 2 parallel jobs
sfreq = raw.info['sfreq']  # the sampling frequency
con, freqs, times, _, _ = spectral_connectivity(
    epochs, indices=indices,
    method='wpli2_debiased', mode='cwt_morlet', sfreq=sfreq,
    cwt_freqs=cwt_freqs, cwt_n_cycles=cwt_n_cycles, n_jobs=1)

# Mark the seed channel with a value of 1.0, so we can see it in the plot
con[np.where(indices[1] == seed)] = 1.0

# Show topography of connectivity from seed
title = 'WPLI2 - Visual - Seed %s' % seed_ch

layout = mne.find_layout(epochs.info, 'meg')  # use full layout

tfr = AverageTFR(epochs.info, con, times, freqs, len(epochs))
tfr.plot_topo(fig_facecolor='w', font_color='k', border='k')


I am working on the file "0.21/_downloads/cef7da557456c738c3f4db863a633b34/plot_decoding_spoc_CMC.ipynb".
The first task is:
Continuous Target Decoding with SPoC
Source Power Comodulation (SPoC) [1]_ allows to identify the composition of
orthogonal spatial filters that maximally correlate with a continuous target.
SPoC can be seen as an extension of the CSP for continuous variables.
Here, SPoC is applied to decode the (continuous) fluctuation of an
electromyogram from MEG beta activity using data from
Cortico-Muscular Coherence example of FieldTrip
<http://www.fieldtriptoolbox.org/tutorial/coherence>_
References
.. [1] Dahne, S., et al (2014). SPoC: a novel framework for relating the
       amplitude of neuronal oscillations to behaviorally relevant parameters.
       NeuroImage, 86, 111-122.
Can you write Python code for it?

# Author: Alexandre Barachant <alexandre.barachant@gmail.com>
#         Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt

import mne
from mne import Epochs
from mne.decoding import SPoC
from mne.datasets.fieldtrip_cmc import data_path

from sklearn.pipeline import make_pipeline
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_val_predict

# Define parameters
fname = data_path() + '/SubjectCMC.ds'
raw = mne.io.read_raw_ctf(fname)
raw.crop(50., 250.)  # crop for memory purposes

# Filter muscular activity to only keep high frequencies
emg = raw.copy().pick_channels(['EMGlft']).load_data()
emg.filter(20., None, fir_design='firwin')

# Filter MEG data to focus on beta band
raw.pick_types(meg=True, ref_meg=True, eeg=False, eog=False).load_data()
raw.filter(15., 30., fir_design='firwin')

# Build epochs as sliding windows over the continuous raw file
events = mne.make_fixed_length_events(raw, id=1, duration=.250)

# Epoch length is 1.5 second
meg_epochs = Epochs(raw, events, tmin=0., tmax=1.500, baseline=None,
                    detrend=1, decim=8)
emg_epochs = Epochs(emg, events, tmin=0., tmax=1.500, baseline=None)

# Prepare classification
X = meg_epochs.get_data()
y = emg_epochs.get_data().var(axis=2)[:, 0]  # target is EMG power

# Classification pipeline with SPoC spatial filtering and Ridge Regression
spoc = SPoC(n_components=2, log=True, reg='oas', rank='full')
clf = make_pipeline(spoc, Ridge())
# Define a two fold cross-validation
cv = KFold(n_splits=2, shuffle=False)

# Run cross validaton
y_preds = cross_val_predict(clf, X, y, cv=cv)

# Plot the True EMG power and the EMG power predicted from MEG data
fig, ax = plt.subplots(1, 1, figsize=[10, 4])
times = raw.times[meg_epochs.events[:, 0] - raw.first_samp]
ax.plot(times, y_preds, color='b', label='Predicted EMG')
ax.plot(times, y, color='r', label='True EMG')
ax.set_xlabel('Time (s)')
ax.set_ylabel('EMG Power')
ax.set_title('SPoC MEG...


I am working on the file "0.21/_downloads/cef7da557456c738c3f4db863a633b34/plot_decoding_spoc_CMC.ipynb".
The first task is:
Plot the contributions to the detected components (i.e., the forward model)
Can you write Python code for it?


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
Apply morph to (Vector) SourceEstimate
The morph will be applied to the source estimate data, by giving it as the
first argument to the morph we computed above.
Can you write Python code for it?


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
Load example data
Can you write Python code for it?

# Read stc from file
stc = mne.read_source_estimate(fname_stc, subject='sample')


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
Morph surface source estimate
This example demonstrates how to morph an individual subject's
:class:mne.SourceEstimate to a common reference space. We achieve this using
:class:mne.SourceMorph. Pre-computed data will be morphed based on
a spherical representation of the cortex computed using the spherical
registration of FreeSurfer <tut-freesurfer-mne>
(https://surfer.nmr.mgh.harvard.edu/fswiki/SurfaceRegAndTemplates) [1]_. This
transform will be used to morph the surface vertices of the subject towards the
reference vertices. Here we will use 'fsaverage' as a reference space (see
https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage).
The transformation will be applied to the surface source estimate. A plot
depicting the successful morph will be created for the spherical and inflated
surface representation of 'fsaverage', overlaid with the morphed surface
source estimate.
References
.. [1] Greve D. N., Van der Haegen L., Cai Q., Stufflebeam S., Sabuncu M.
       R., Fischl B., Brysbaert M.
       A Surface-based Analysis of Language Lateralization and Cortical
       Asymmetry. Journal of Cognitive Neuroscience 25(9), 1477-1492, 2013.

Note

For background information about morphing see `ch_morph`.

Can you write Python code for it?

# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD (3-clause)
import os
import os.path as op

import mne
from mne.datasets import sample

print(__doc__)


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
Plot results
Can you write Python code for it?

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

# As spherical surface
brain = stc_fsaverage.plot(surface='sphere', **surfer_kwargs)

# Add title
brain.add_text(0.1, 0.9, 'Morphed to fsaverage (spherical)', 'title',
               font_size=16)


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
Reading and writing SourceMorph from and to disk
An instance of SourceMorph can be saved, by calling
:meth:morph.save <mne.SourceMorph.save>.
This method allows for specification of a filename under which the morph
will be save in ".h5" format. If no file extension is provided, "-morph.h5"
will be appended to the respective defined filename::
>>> morph.save('my-file-name')

Reading a saved source morph can be achieved by using
:func:mne.read_source_morph::
>>> morph = mne.read_source_morph('my-file-name-morph.h5')

Once the environment is set up correctly, no information such as
subject_from or subjects_dir must be provided, since it can be
inferred from the data and use morph to 'fsaverage' by default. SourceMorph
can further be used without creating an instance and assigning it to a
variable. Instead :func:mne.compute_source_morph and
:meth:mne.SourceMorph.apply can be
easily chained into a handy one-liner. Taking this together the shortest
possible way to morph data directly would be:
Can you write Python code for it?

stc_fsaverage = mne.compute_source_morph(stc,
                                         subjects_dir=subjects_dir).apply(stc)


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
Setup paths
Can you write Python code for it?

data_path = sample.data_path()
sample_dir = op.join(data_path, 'MEG', 'sample')
subjects_dir = op.join(data_path, 'subjects')
fname_src = op.join(subjects_dir, 'sample', 'bem', 'sample-oct-6-src.fif')
fname_fwd = op.join(sample_dir, 'sample_audvis-meg-oct-6-fwd.fif')
fname_fsaverage_src = os.path.join(subjects_dir, 'fsaverage', 'bem',
                                   'fsaverage-ico-5-src.fif')

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


I am working on the file "0.21/_downloads/d52b5321a00f5cf4d4be975019fb541b/plot_morph_surface_stc.ipynb".
The first task is:
We also need to specify the set of vertices to morph to. This can be done
using the spacing parameter, but for consistency it's better to pass the
src_to parameter.

Note

Since the default values of :func:`mne.compute_source_morph` are
     ``spacing=5, subject_to='fsaverage'``, in this example
     we could actually omit the ``src_to`` and ``subject_to`` arguments
     below. The ico-5 ``fsaverage`` source space contains the
     special values ``[np.arange(10242)] * 2``, but in general this will
     not be true for other spacings or other subjects. Thus it is recommended
     to always pass the destination ``src`` for consistency.

Initialize SourceMorph for SourceEstimate
Can you write Python code for it?

src_to = mne.read_source_spaces(fname_fsaverage_src)
print(src_to[0]['vertno'])  # special, np.arange(10242)
morph = mne.compute_source_morph(stc, subject_from='sample',
                                 subject_to='fsaverage', src_to=src_to,
                                 subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/d5764d6befb13ad52368247a508e45f6/plot_3d_to_2d.ipynb".
The first task is:
Load data
First we'll load a sample ECoG dataset which we'll use for generating
a 2D snapshot.
Can you write Python code for it?

mat = loadmat(path_data)
ch_names = mat['ch_names'].tolist()
elec = mat['elec']  # electrode coordinates in meters
# Now we make a montage stating that the sEEG contacts are in head
# coordinate system (although they are in MRI). This is compensated
# by the fact that below we do not specicty a trans file so the Head<->MRI
# transform is the identity.
montage = mne.channels.make_dig_montage(ch_pos=dict(zip(ch_names, elec)),
                                        coord_frame='head')
info = mne.create_info(ch_names, 1000., 'ecog').set_montage(montage)
print('Created %s channel positions' % len(ch_names))


I am working on the file "0.21/_downloads/d5764d6befb13ad52368247a508e45f6/plot_3d_to_2d.ipynb".
The first task is:
Manually creating 2D electrode positions
If we don't have the 3D electrode positions then we can still create a
2D representation of the electrodes. Assuming that you can see the electrodes
on the 2D image, we can use :class:mne.viz.ClickableImage to open the image
interactively. You can click points on the image and the x/y coordinate will
be stored.
We'll open an image file, then use ClickableImage to
return 2D locations of mouse clicks (or load a file already created).
Then, we'll return these xy positions as a layout for use with plotting topo
maps.
Can you write Python code for it?

# This code opens the image so you can click on it. Commented out
# because we've stored the clicks as a layout file already.

# # The click coordinates are stored as a list of tuples
# im = plt.imread('./brain.png')
# click = ClickableImage(im)
# click.plot_clicks()

# # Generate a layout from our clicks and normalize by the image
# print('Generating and saving layout...')
# lt = click.to_layout()
# lt.save(op.join(layout_path, layout_name))  # To save if we want

# # We've already got the layout, load it
lt = mne.channels.read_layout(layout_name, path=layout_path, scale=False)
x = lt.pos[:, 0] * float(im.shape[1])
y = (1 - lt.pos[:, 1]) * float(im.shape[0])  # Flip the y-position
fig, ax = plt.subplots()
ax.imshow(im)
ax.scatter(x, y, s=120, color='r')
plt.autoscale(tight=True)
ax.set_axis_off()
plt.show()


I am working on the file "0.21/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
Applying DICS spatial filters separately to the CSD computed using the
baseline and the CSD computed during the ERS activity.
Can you write Python code for it?

baseline_source_power, freqs = apply_dics_csd(csd_baseline, filters)
beta_source_power, freqs = apply_dics_csd(csd_ers, filters)


I am working on the file "0.21/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
Compute source power using DICS beamformer
Compute a Dynamic Imaging of Coherent Sources (DICS)
:footcite:GrossEtAl2001 filter from
single-trial activity to estimate source power across a frequency band. This
example demonstrates how to source localize the event-related synchronization
(ERS) of beta band activity in this dataset: somato-dataset
Can you write Python code for it?

# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#         Roman Goj <roman.goj@gmail.com>
#         Denis Engemann <denis.engemann@gmail.com>
#         Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
import os.path as op

import numpy as np
import mne
from mne.datasets import somato
from mne.time_frequency import csd_morlet
from mne.beamformer import make_dics, apply_dics_csd

print(__doc__)


I am working on the file "0.21/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
Reading the raw data and creating epochs:
Can you write Python code for it?

data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
                    'sub-{}_task-{}_meg.fif'.format(subject, task))

# Use a shorter segment of raw just for speed here
raw = mne.io.read_raw_fif(raw_fname)
raw.crop(0, 120)  # one minute for speed (looks similar to using all ~800 sec)

# Read epochs
events = mne.find_events(raw)

epochs = mne.Epochs(raw, events, event_id=1, tmin=-1.5, tmax=2, preload=True)
del raw

# Paths to forward operator and FreeSurfer subject directory
fname_fwd = op.join(data_path, 'derivatives', 'sub-{}'.format(subject),
                    'sub-{}_task-{}-fwd.fif'.format(subject, task))
subjects_dir = op.join(data_path, 'derivatives', 'freesurfer', 'subjects')


I am working on the file "0.21/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
To compute the source power for a frequency band, rather than each frequency
separately, we average the CSD objects across frequencies.
Can you write Python code for it?

csd = csd.mean()
csd_baseline = csd_baseline.mean()
csd_ers = csd_ers.mean()


I am working on the file "0.21/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
We are interested in the beta band. Define a range of frequencies, using a
log scale, from 12 to 30 Hz.
Can you write Python code for it?

freqs = np.logspace(np.log10(12), np.log10(30), 9)


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Finally let's compute the inverse and apply it:
Can you write Python code for it?

inv = mne.minimum_norm.make_inverse_operator(
    evoked.info, fwd, cov, verbose=True)
stc = mne.minimum_norm.apply_inverse(evoked, inv)
stc.plot(subjects_dir=subjects_dir, initial_time=0.1)


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Getting a source estimate
New we have all of the components we need to compute a forward solution,
but first we should sanity check that everything is well aligned:
Can you write Python code for it?

plot_alignment(evoked.info, trans=trans, show_axes=True, surfaces='head-dense',
               subject='sample', subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Getting our MRI voxel EEG locations to head (and MRI surface RAS) coords
Let's load our :class:~mne.channels.DigMontage using
:func:mne.channels.read_custom_montage, making note of the fact that
we stored our locations in Freesurfer surface RAS (MRI) coordinates.
.. collapse:: |question| What if my electrodes are in MRI voxels?
    :class: info
If you have voxel coordinates in MRI voxels, you can transform these to
FreeSurfer surface RAS (called "mri" in MNE) coordinates using the
transformations that FreeSurfer computes during reconstruction.
``nibabel`` calls this transformation the ``vox2ras_tkr`` transform
and operates in millimeters, so we can load it, convert it to meters,
and then apply it::

    >>> pos_vox = ...  # loaded from a file somehow
    >>> img = nibabel.load(fname_T1)
    >>> vox2mri_t = img.header.get_vox2ras_tkr()  # voxel -> mri trans
    >>> pos_mri = mne.transforms.apply_trans(vox2mri_t, pos_vox)
    >>> pos_mri /= 1000.  # mm -> m

You can also verify that these are correct (or manually convert voxels
to MRI coords) by looking at the points in Freeview or tkmedit.
Can you write Python code for it?

dig_montage = read_custom_montage(fname_mon, head_size=None, coord_frame='mri')
dig_montage.plot()


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Now we can actually compute the forward:
Can you write Python code for it?

fwd = mne.make_forward_solution(
    evoked.info, trans=trans, src=fname_src, bem=fname_bem, verbose=True)


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Now we can do standard sensor-space operations like make joint plots of
evoked data.
Can you write Python code for it?

raw.set_eeg_reference(projection=True)
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events)
cov = mne.compute_covariance(epochs, tmax=0.)
evoked = epochs['1'].average()  # trigger 1 in auditory/left
evoked.plot_joint()


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Prerequisites
For this we will assume that you have:

raw EEG data
your subject's MRI reconstrcted using FreeSurfer
an appropriate boundary element model (BEM)
an appropriate source space (src)
your EEG electrodes in Freesurfer surface RAS coordinates, stored
  in one of the formats :func:mne.channels.read_custom_montage supports

Let's set the paths to these files for the sample dataset, including
a modified sample MRI showing the electrode locations plus a .elc
file corresponding to the points in MRI coords (these were synthesized
<https://gist.github.com/larsoner/0ac6fad57e31cb2d9caa77350a9ff366>__,
and thus are stored as part of the misc dataset).
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
bem_dir = op.join(subjects_dir, 'sample', 'bem')
fname_bem = op.join(bem_dir, 'sample-5120-5120-5120-bem-sol.fif')
fname_src = op.join(bem_dir, 'sample-oct-6-src.fif')

misc_path = mne.datasets.misc.data_path()
fname_T1_electrodes = op.join(misc_path, 'sample_eeg_mri', 'T1_electrodes.mgz')
fname_mon = op.join(misc_path, 'sample_eeg_mri', 'sample_mri_montage.elc')


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Visualizing the MRI
Let's take our MRI-with-eeg-locations and adjust the affine to put the data
in MNI space, and plot using :func:nilearn.plotting.plot_glass_brain,
which does a maximum intensity projection (easy to see the fake electrodes).
This plotting function requires data to be in MNI space.
Because img.affine gives the voxel-to-world (RAS) mapping, if we apply a
RAS-to-MNI transform to it, it becomes the voxel-to-MNI transformation we
need. Thus we create a "new" MRI image in MNI coordinates and plot it as:
Can you write Python code for it?

img = nibabel.load(fname_T1_electrodes)  # original subject MRI w/EEG
ras_mni_t = mne.transforms.read_ras_mni_t('sample', subjects_dir)  # from FS
mni_affine = np.dot(ras_mni_t['trans'], img.affine)  # vox->ras->MNI
img_mni = nibabel.Nifti1Image(img.dataobj, mni_affine)  # now in MNI coords!
plot_glass_brain(img_mni, cmap='hot_black_bone', threshold=0., black_bg=True,
                 resampling_interpolation='nearest', colorbar=True)


I am working on the file "0.21/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
We can then get our transformation from the MRI coordinate frame (where our
points are defined) to the head coordinate frame from the object.
Can you write Python code for it?

trans = compute_native_head_t(dig_montage)
print(trans)  # should be mri->head, as the "native" space here is MRI


I am working on the file "0.21/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
And this can be visualized using :meth:stc.plot <mne.SourceEstimate.plot>:
Can you write Python code for it?

brain = stc.plot(hemi='split', views=('lat', 'med'), initial_time=0.1,
                 subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Decoding over time
This strategy consists in fitting a multivariate predictive model on each
time instant and evaluating its performance at the same instant on new
epochs. The :class:mne.decoding.SlidingEstimator will take as input a
pair of features $X$ and targets $y$, where $X$ has
more than 2 dimensions. For decoding over time the data $X$
is the epochs data of shape n_epochs x n_channels x n_times. As the
last dimension of $X$ is the time, an estimator will be fit
on every time instant.
This approach is analogous to SlidingEstimator-based approaches in fMRI,
where here we are interested in when one can discriminate experimental
conditions and therefore figure out when the effect of interest happens.
When working with linear models as estimators, this approach boils
down to estimating a discriminative spatial filter for each time instant.
Temporal decoding
We'll use a Logistic Regression for a binary classification as machine
learning model.
Can you write Python code for it?

# We will train the classifier on all left visual vs auditory trials on MEG

clf = make_pipeline(StandardScaler(), LogisticRegression(solver='lbfgs'))

time_decod = SlidingEstimator(clf, n_jobs=1, scoring='roc_auc', verbose=True)
scores = cross_val_multiscore(time_decod, X, y, cv=5, n_jobs=1)

# Mean scores across cross-validation splits
scores = np.mean(scores, axis=0)

# Plot
fig, ax = plt.subplots()
ax.plot(epochs.times, scores, label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.set_xlabel('Times')
ax.set_ylabel('AUC')  # Area Under the Curve
ax.legend()
ax.axvline(.0, color='k', linestyle='-')
ax.set_title('Sensor space decoding')


I am working on the file "0.21/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Plot the full (generalization) matrix:
Can you write Python code for it?

fig, ax = plt.subplots(1, 1)
im = ax.imshow(scores, interpolation='lanczos', origin='lower', cmap='RdBu_r',
               extent=epochs.times[[0, -1, 0, -1]], vmin=0., vmax=1.)
ax.set_xlabel('Testing Time (s)')
ax.set_ylabel('Training Time (s)')
ax.set_title('Temporal generalization')
ax.axvline(0, color='k')
ax.axhline(0, color='k')
plt.colorbar(im, ax=ax)


I am working on the file "0.21/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Projecting sensor-space patterns to source space
If you use a linear classifier (or regressor) for your data, you can also
project these to source space. For example, using our evoked_time_gen
from before:
Can you write Python code for it?

cov = mne.compute_covariance(epochs, tmax=0.)
del epochs
fwd = mne.read_forward_solution(
    data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif')
inv = mne.minimum_norm.make_inverse_operator(
    evoked_time_gen.info, fwd, cov, loose=0.)
stc = mne.minimum_norm.apply_inverse(evoked_time_gen, inv, 1. / 9., 'dSPM')
del fwd, inv


I am working on the file "0.21/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Temporal generalization
Temporal generalization is an extension of the decoding over time approach.
It consists in evaluating whether the model estimated at a particular
time instant accurately predicts any other time instant. It is analogous to
transferring a trained model to a distinct learning problem, where the
problems correspond to decoding the patterns of brain activity recorded at
distinct time instants.
The object to for Temporal generalization is
:class:mne.decoding.GeneralizingEstimator. It expects as input $X$
and $y$ (similarly to :class:~mne.decoding.SlidingEstimator) but
generates predictions from each model for all time instants. The class
:class:~mne.decoding.GeneralizingEstimator is generic and will treat the
last dimension as the one to be used for generalization testing. For
convenience, here, we refer to it as different tasks. If $X$
corresponds to epochs data then the last dimension is time.
This runs the analysis used in :footcite:KingEtAl2014 and further detailed
in :footcite:KingDehaene2014:
Can you write Python code for it?

# define the Temporal generalization object
time_gen = GeneralizingEstimator(clf, n_jobs=1, scoring='roc_auc',
                                 verbose=True)

scores = cross_val_multiscore(time_gen, X, y, cv=5, n_jobs=1)

# Mean scores across cross-validation splits
scores = np.mean(scores, axis=0)

# Plot the diagonal (it's exactly the same as the time-by-time decoding above)
fig, ax = plt.subplots()
ax.plot(epochs.times, np.diag(scores), label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.set_xlabel('Times')
ax.set_ylabel('AUC')
ax.legend()
ax.axvline(.0, color='k', linestyle='-')
ax.set_title('Decoding MEG sensors over time')


I am working on the file "0.21/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
You can retrieve the spatial filters and spatial patterns if you explicitly
use a LinearModel
Can you write Python code for it?

clf = make_pipeline(StandardScaler(),
                    LinearModel(LogisticRegression(solver='lbfgs')))
time_decod = SlidingEstimator(clf, n_jobs=1, scoring='roc_auc', verbose=True)
time_decod.fit(X, y)

coef = get_coef(time_decod, 'patterns_', inverse_transform=True)
evoked_time_gen = mne.EvokedArray(coef, epochs.info, tmin=epochs.times[0])
joint_kwargs = dict(ts_args=dict(time_unit='s'),
                    topomap_args=dict(time_unit='s'))
evoked_time_gen.plot_joint(times=np.arange(0., .500, .100), title='patterns',
                           **joint_kwargs)


I am working on the file "0.21/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
The iterative reweighted TF-MxNE solver is a distributed inverse method
based on the TF-MxNE solver, which promotes focal (sparse) sources [1]_.
The benefit of this approach is that:

it is spatio-temporal without assuming stationarity (sources properties
    can vary over time),
activations are localized in space, time and frequency in one step,
the solver uses non-convex penalties in the TF domain, which results in a
    solution less biased towards zero than when simple TF-MxNE is used,
using a multiscale dictionary allows to capture short transient
    activations along with slower brain waves [2]_.
Can you write Python code for it?

# Author: Mathurin Massias <mathurin.massias@gmail.com>
#         Yousra Bekhti <yousra.bekhti@gmail.com>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#         Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import os.path as op

import mne
from mne.datasets import somato
from mne.inverse_sparse import tf_mixed_norm, make_stc_from_dipoles
from mne.viz import plot_sparse_source_estimates

print(__doc__)


I am working on the file "0.21/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Generate stc from dipoles
Can you write Python code for it?

stc = make_stc_from_dipoles(dipoles, forward['src'])

plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1),
                             opacity=0.1, fig_name="irTF-MxNE (cond %s)"
                             % condition)


I am working on the file "0.21/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Load somatosensory MEG data
Can you write Python code for it?

data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
                    'sub-{}_task-{}_meg.fif'.format(subject, task))
fwd_fname = op.join(data_path, 'derivatives', 'sub-{}'.format(subject),
                    'sub-{}_task-{}-fwd.fif'.format(subject, task))

condition = 'Unknown'

# Read evoked
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
reject = dict(grad=4000e-13, eog=350e-6)
picks = mne.pick_types(raw.info, meg=True, eog=True)

event_id, tmin, tmax = 1, -1., 3.
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    reject=reject, preload=True)
evoked = epochs.filter(1, None).average()
evoked = evoked.pick_types(meg=True)
evoked.crop(tmin=0.008, tmax=0.2)

# Compute noise covariance matrix
cov = mne.compute_covariance(epochs, rank='info', tmax=0.)

# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


I am working on the file "0.21/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Run iterative reweighted multidict TF-MxNE solver
Can you write Python code for it?

alpha, l1_ratio = 20, 0.05
loose, depth = 1, 0.95
# Use a multiscale time-frequency dictionary
wsize, tstep = [4, 16], [2, 4]

n_tfmxne_iter = 10
# Compute TF-MxNE inverse solution with dipole output
dipoles, residual = tf_mixed_norm(
    evoked, forward, cov, alpha=alpha, l1_ratio=l1_ratio,
    n_tfmxne_iter=n_tfmxne_iter, loose=loose,
    depth=depth, tol=1e-3,
    wsize=wsize, tstep=tstep, return_as_dipoles=True,
    return_residual=True)

# Crop to remove edges
for dip in dipoles:
    dip.crop(tmin=-0.05, tmax=0.3)
evoked.crop(tmin=-0.05, tmax=0.3)
residual.crop(tmin=-0.05, tmax=0.3)


I am working on the file "0.21/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Show the evoked response and the residual for gradiometers
Can you write Python code for it?

ylim = dict(grad=[-300, 300])
evoked.pick_types(meg='grad')
evoked.plot(titles=dict(grad='Evoked Response: Gradiometers'), ylim=ylim,
            proj=True)

residual.pick_types(meg='grad')
residual.plot(titles=dict(grad='Residuals: Gradiometers'), ylim=ylim,
              proj=True)


I am working on the file "0.21/_downloads/e31a3c546b89121086d731bfb81c98aa/plot_receptive_field_mtrf.ipynb".
The first task is:
Create and fit a receptive field model
We will construct an encoding model to find the linear relationship between
a time-delayed version of the speech envelope and the EEG signal. This allows
us to make predictions about the response to new stimuli.
Can you write Python code for it?

# Define the delays that we will use in the receptive field
tmin, tmax = -.2, .4

# Initialize the model
rf = ReceptiveField(tmin, tmax, sfreq, feature_names=['envelope'],
                    estimator=1., scoring='corrcoef')
# We'll have (tmax - tmin) * sfreq delays
# and an extra 2 delays since we are inclusive on the beginning / end index
n_delays = int((tmax - tmin) * sfreq) + 2

n_splits = 3
cv = KFold(n_splits)

# Prepare model data (make time the first dimension)
speech = speech.T
Y, _ = raw[:]  # Outputs for the model
Y = Y.T

# Iterate through splits, fit the model, and predict/test on held-out data
coefs = np.zeros((n_splits, n_channels, n_delays))
scores = np.zeros((n_splits, n_channels))
for ii, (train, test) in enumerate(cv.split(speech)):
    print('split %s / %s' % (ii + 1, n_splits))
    rf.fit(speech[train], Y[train])
    scores[ii] = rf.score(speech[test], Y[test])
    # coef_ is shape (n_outputs, n_features, n_delays). we only have 1 feature
    coefs[ii] = rf.coef_[:, 0, :]
times = rf.delays_ / float(rf.sfreq)

# Average scores and coefficients across CV splits
mean_coefs = coefs.mean(axis=0)
mean_scores = scores.mean(axis=0)

# Plot mean prediction scores across all channels
fig, ax = plt.subplots()
ix_chs = np.arange(n_channels)
ax.plot(ix_chs, mean_scores)
ax.axhline(0, ls='--', color='r')
ax.set(title="Mean prediction score", xlabel="Channel", ylabel="Score ($r$)")
mne.viz.tight_layout()


I am working on the file "0.21/_downloads/e31a3c546b89121086d731bfb81c98aa/plot_receptive_field_mtrf.ipynb".
The first task is:
Investigate model coefficients
Finally, we will look at how the decoding model coefficients are distributed
across the scalp. We will attempt to recreate figure 5_ from
:footcite:CrosseEtAl2016. The
decoding model weights reflect the channels that contribute most toward
reconstructing the stimulus signal, but are not directly interpretable in a
neurophysiological sense. Here we also look at the coefficients obtained
via an inversion procedure :footcite:HaufeEtAl2014, which have a more
straightforward
interpretation as their value (and sign) directly relates to the stimulus
signal's strength (and effect direction).
Can you write Python code for it?

time_plot = (-.140, -.125)  # To average between two timepoints.
ix_plot = np.arange(np.argmin(np.abs(time_plot[0] - times)),
                    np.argmin(np.abs(time_plot[1] - times)))
fig, ax = plt.subplots(1, 2)
mne.viz.plot_topomap(np.mean(mean_coefs[:, ix_plot], axis=1),
                     pos=info, axes=ax[0], show=False,
                     vmin=-max_coef, vmax=max_coef)
ax[0].set(title="Model coefficients\nbetween delays %s and %s"
          % (time_plot[0], time_plot[1]))

mne.viz.plot_topomap(np.mean(mean_patterns[:, ix_plot], axis=1),
                     pos=info, axes=ax[1],
                     show=False, vmin=-max_patterns, vmax=max_patterns)
ax[1].set(title="Inverse-transformed coefficients\nbetween delays %s and %s"
          % (time_plot[0], time_plot[1]))
mne.viz.tight_layout()

plt.show()


I am working on the file "0.21/_downloads/e31a3c546b89121086d731bfb81c98aa/plot_receptive_field_mtrf.ipynb".
The first task is:
Visualize stimulus reconstruction
To get a sense of our model performance, we can plot the actual and predicted
stimulus envelopes side by side.
Can you write Python code for it?

y_pred = sr.predict(Y[test])
time = np.linspace(0, 2., 5 * int(sfreq))
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(time, speech[test][sr.valid_samples_][:int(5 * sfreq)],
        color='grey', lw=2, ls='--')
ax.plot(time, y_pred[sr.valid_samples_][:int(5 * sfreq)], color='r', lw=2)
ax.legend([lns[0], ln1[0]], ['Envelope', 'Reconstruction'], frameon=False)
ax.set(title="Stimulus reconstruction")
ax.set_xlabel('Time (s)')
mne.viz.tight_layout()


I am working on the file "0.21/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Alternatively, you can plot the PSD for every sensor on its own axes, with
the axes arranged spatially to correspond to sensor locations in space, using
:meth:~mne.io.Raw.plot_psd_topo:
Can you write Python code for it?


I am working on the file "0.21/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Built-in plotting methods for Raw objects
This tutorial shows how to plot continuous data as a time series, how to plot
the spectral density of continuous data, and how to plot the sensor locations
and projectors stored in :class:~mne.io.Raw objects.
   :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 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)
raw.crop(tmax=60).load_data()


I am working on the file "0.21/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Plotting sensor locations from Raw objects
The channel locations in a :class:~mne.io.Raw object can be easily plotted
with the :meth:~mne.io.Raw.plot_sensors method. A brief example is shown
here; notice that channels in raw.info['bads'] are plotted in red. More
details and additional examples are given in the tutorial
tut-sensor-locations.
Can you write Python code for it?


I am working on the file "0.21/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
This plot is also interactive; hovering over each "thumbnail" plot will
display the channel name in the bottom left of the plot window, and clicking
on a thumbnail plot will create a second figure showing a larger version of
the selected channel's spectral density (as if you had called
:meth:~mne.io.Raw.plot_psd on that channel).
By default, :meth:~mne.io.Raw.plot_psd_topo will show only the MEG
channels if MEG channels are present; if only EEG channels are found, they
will be plotted instead:
Can you write Python code for it?


I am working on the file "0.21/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
We've seen in a previous tutorial <tut-raw-class> how to plot data
from a :class:~mne.io.Raw object using :doc:matplotlib
<matplotlib:index>, but :class:~mne.io.Raw objects also have several
built-in plotting methods:

:meth:~mne.io.Raw.plot
:meth:~mne.io.Raw.plot_psd
:meth:~mne.io.Raw.plot_psd_topo
:meth:~mne.io.Raw.plot_sensors
:meth:~mne.io.Raw.plot_projs_topomap

The first three are discussed here in detail; the last two are shown briefly
and covered in-depth in other tutorials.
Interactive data browsing with Raw.plot()
The :meth:~mne.io.Raw.plot method of :class:~mne.io.Raw objects provides
a versatile interface for exploring continuous data. For interactive viewing
and data quality checking, it can be called with no additional parameters:
Can you write Python code for it?


I am working on the file "0.21/_downloads/e71fac7e5d7784759a26529dd6e63da5/plot_whitened.ipynb".
The first task is:
Epochs with whitening
Can you write Python code for it?


I am working on the file "0.21/_downloads/e71fac7e5d7784759a26529dd6e63da5/plot_whitened.ipynb".
The first task is:
Plotting whitened data
This tutorial demonstrates how to plot :term:whitened <whitening> evoked
data.
Data are whitened for many processes, including dipole fitting, source
localization and some decoding algorithms. Viewing whitened data thus gives
a different perspective on the data that these algorithms operate on.
Let's start by loading some data and computing a signal (spatial) covariance
that we'll consider to be noise.
Can you write Python code for it?

import mne
from mne.datasets import sample


I am working on the file "0.21/_downloads/e71fac7e5d7784759a26529dd6e63da5/plot_whitened.ipynb".
The first task is:
Raw data with whitening

Note

In the :meth:`mne.io.Raw.plot` with ``noise_cov`` supplied,
          you can press they "w" key to turn whitening on and off.

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'
raw = mne.io.read_raw_fif(raw_fname, preload=True)

events = mne.find_events(raw, stim_channel='STI 014')
event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
            'visual/right': 4, 'smiley': 5, 'button': 32}
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id=event_id, reject=reject)

# baseline noise cov, not a lot of samples
noise_cov = mne.compute_covariance(epochs, tmax=0., method='shrunk', rank=None,
                                   verbose='error')

# butterfly mode shows the differences most clearly
raw.plot(events=events, butterfly=True)
raw.plot(noise_cov=noise_cov, events=events, butterfly=True)


I am working on the file "0.21/_downloads/e71fac7e5d7784759a26529dd6e63da5/plot_whitened.ipynb".
The first task is:
Topographic plot with whitening
Can you write Python code for it?

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


I am working on the file "0.21/_downloads/e807ecd348331c3d789aa11b874576a5/plot_decoding_time_generalization_conditions.ipynb".
The first task is:
Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in [1]_. It illustrates how one can
fit a linear classifier to identify a discriminatory topography at a given time
instant and subsequently assess whether this linear model can accurately
predict all of the time samples of a second set of conditions.
References
.. [1] King & Dehaene (2014) 'Characterizing the dynamics of mental
       representations: the Temporal Generalization method', Trends In
       Cognitive Sciences, 18(4), 203-210. doi: 10.1016/j.tics.2014.01.002.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

import mne
from mne.datasets import sample
from mne.decoding import GeneralizingEstimator

print(__doc__)

# Preprocess data
data_path = sample.data_path()
# Load and filter data, set up epochs
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
events_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
picks = mne.pick_types(raw.info, meg=True, exclude='bads')  # Pick MEG channels
raw.filter(1., 30., fir_design='firwin')  # Band pass filtering signals
events = mne.read_events(events_fname)
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4}
tmin = -0.050
tmax = 0.400
# decimate to make the example faster to run, but then use verbose='error' in
# the Epochs constructor to suppress warning about decimation causing aliasing
decim = 2
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
                    proj=True, picks=picks, baseline=None, preload=True,
                    reject=dict(mag=5e-12), decim=decim, verbose='error')


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
And we also view the HbR activity for the two conditions.
Can you write Python code for it?

epochs['Tapping/Left'].average(picks='hbr').plot_topomap(
    times=times, **topomap_args)
epochs['Tapping/Right'].average(picks='hbr').plot_topomap(
    times=times, **topomap_args)