I am working on the file "0.20/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
Get epochs from all conditions, average
Can you write Python code for it?

evokeds = []
for cat in raw.acqparser.categories:
    cond = raw.acqparser.get_condition(raw, cat)
    # copy (supported) rejection parameters from DACQ settings
    epochs = mne.Epochs(raw, reject=raw.acqparser.reject,
                        flat=raw.acqparser.flat, **cond)
    evoked = epochs.average()
    evoked.comment = cat['comment']
    evokeds.append(evoked)
# save all averages to an evoked fiff file
# fname_out = 'multimodal-ave.fif'
# mne.write_evokeds(fname_out, evokeds)


I am working on the file "0.20/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
Read raw file
Can you write Python code for it?


I am working on the file "0.20/_downloads/963786e591fc03946ca0f3b819f12772/plot_xdawn_denoising.ipynb".
The first task is:
Epochs are denoised by calling apply, which by default keeps only the
signal subspace corresponding to the first n_components specified in the
Xdawn constructor above.
Can you write Python code for it?

epochs_denoised = xd.apply(epochs)

# Plot image epoch after Xdawn
plot_epochs_image(epochs_denoised['vis_r'], picks=[230], vmin=-500, vmax=500)


I am working on the file "0.20/_downloads/963786e591fc03946ca0f3b819f12772/plot_xdawn_denoising.ipynb".
The first task is:
Now, we estimate a set of xDAWN filters for the epochs (which contain only
the vis_r class).
Can you write Python code for it?

# Estimates signal covariance
signal_cov = compute_raw_covariance(raw, picks=picks)

# Xdawn instance
xd = Xdawn(n_components=2, signal_cov=signal_cov)

# Fit xdawn
xd.fit(epochs)


I am working on the file "0.20/_downloads/963786e591fc03946ca0f3b819f12772/plot_xdawn_denoising.ipynb".
The first task is:
Set parameters and read data
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'
tmin, tmax = -0.1, 0.3
event_id = dict(vis_r=4)

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 20, fir_design='firwin')  # replace baselining with high-pass
events = read_events(event_fname)

raw.info['bads'] = ['MEG 2443']  # set bad channels
picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                   exclude='bads')
# Epoching
epochs = Epochs(raw, events, event_id, tmin, tmax, proj=False,
                picks=picks, baseline=None, preload=True,
                verbose=False)

# Plot image epoch before xdawn
plot_epochs_image(epochs['vis_r'], picks=[230], vmin=-500, vmax=500)


I am working on the file "0.20/_downloads/963786e591fc03946ca0f3b819f12772/plot_xdawn_denoising.ipynb".
The first task is:
XDAWN Denoising
XDAWN filters are trained from epochs, signal is projected in the sources
space and then projected back in the sensor space using only the first two
XDAWN components. The process is similar to an ICA, but is
supervised in order to maximize the signal to signal + noise ratio of the
evoked response.

Warning

As this denoising method exploits the known events to
             maximize SNR of the contrast between conditions it can lead
             to overfitting. To avoid a statistical analysis problem you
             should split epochs used in fit with the ones used in
             apply method.

References
[1] Rivet, B., Souloumiac, A., Attina, V., & Gibert, G. (2009). xDAWN
algorithm to enhance evoked potentials: application to brain-computer
interface. Biomedical Engineering, IEEE Transactions on, 56(8), 2035-2043.
[2] Rivet, B., Cecotti, H., Souloumiac, A., Maby, E., & Mattout, J. (2011,
August). Theoretical analysis of xDAWN algorithm: application to an
efficient sensor selection in a P300 BCI. In Signal Processing Conference,
2011 19th European (pp. 1382-1386). IEEE.
Can you write Python code for it?

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

from mne import (io, compute_raw_covariance, read_events, pick_types, Epochs)
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.viz import plot_epochs_image

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Dipole fits
For computing a dipole fit, we need to load the noise covariance, the BEM
solution, and the coregistration transformation files. Note that for the
other methods, these were already used to generate the inverse operator.
Can you write Python code for it?

fname_cov = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_bem = os.path.join(subjects_dir, 'sample', 'bem',
                         'sample-5120-bem-sol.fif')
fname_trans = os.path.join(data_path, 'MEG', 'sample',
                           'sample_audvis_raw-trans.fif')


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Dipoles are fit independently for each time point, so let us crop our time
series to visualize the dipole fit for the time point of interest.
Can you write Python code for it?

evoked.crop(0.1, 0.1)
dip = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0]


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Finally, we can visualize the dipole.
Can you write Python code for it?


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Note that here we used initial_time=0.1, but we can also browse through
time using time_viewer=True.
In case mayavi is not available, we also offer a matplotlib
backend. Here we use verbose='error' to ignore a warning that not all
vertices were used in plotting.
Can you write Python code for it?

mpl_fig = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                   backend='matplotlib', verbose='error')


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
The SourceEstimate object is in fact a surface source estimate. MNE also
supports volume-based source estimates but more on that later.
We can plot the source estimate using the
:func:stc.plot <mne.SourceEstimate.plot> just as in other MNE
objects. Note that for this visualization to work, you must have mayavi
and pysurfer installed on your machine.
Can you write Python code for it?

initial_time = 0.1
brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                 clim=dict(kind='value', pos_lims=[3, 6, 9]),
                 time_viewer=True)


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
The source estimate is computed using the inverse operator and the
sensor-space data.
Can you write Python code for it?

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
stc = apply_inverse(evoked, inv, lambda2, method)
stc.crop(0.0, 0.2)


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Then, we can load the precomputed inverse operator from a file.
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif'
inv = read_inverse_operator(fname_inv)
src = inv['src']


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Then, we read the stc from file
Can you write Python code for it?

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


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
This is a :class:SourceEstimate <mne.SourceEstimate> object
Can you write Python code for it?


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
This time, we have a different container
(:class:VolSourceEstimate <mne.VolSourceEstimate>) for the source time
course.
Can you write Python code for it?


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
This too comes with a convenient plot method.
Can you write Python code for it?


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Vector Source Estimates
If we choose to use pick_ori='vector' in
:func:apply_inverse <mne.minimum_norm.apply_inverse>
Can you write Python code for it?

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

inv = read_inverse_operator(fname_inv)
stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')
stc.plot(subject='sample', subjects_dir=subjects_dir,
         initial_time=initial_time)


I am working on the file "0.20/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Volume Source Estimates
We can also visualize volume source estimates (used for deep structures).
Let us load the sensor-level evoked data. We select the MEG channels
to keep things simple.
Can you write Python code for it?

evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
evoked.pick_types(meg=True, eeg=False)


I am working on the file "0.20/_downloads/974f822d2280f83b67727ee3355c7c2f/plot_sensor_connectivity.ipynb".
The first task is:
Compute all-to-all connectivity in sensor space
Computes the Phase Lag Index (PLI) between all gradiometers and shows the
connectivity in 3D using the helmet geometry. The left visual stimulation data
are used which produces strong connectvitiy in the right occipital sensors.
Can you write Python code for it?

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

import mne
from mne import io
from mne.connectivity import spectral_connectivity
from mne.datasets import sample
from mne.viz import plot_sensors_connectivity

print(__doc__)


I am working on the file "0.20/_downloads/974f822d2280f83b67727ee3355c7c2f/plot_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 the visual condition
event_id, tmin, tmax = 3, -0.2, 1.5  # need a long enough epoch for 5 cycles
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6))

# Compute connectivity for band containing the evoked response.
# We exclude the baseline period
fmin, fmax = 3., 9.
sfreq = raw.info['sfreq']  # the sampling frequency
tmin = 0.0  # exclude the baseline period
epochs.load_data().pick_types(meg='grad')  # just keep MEG and no EOG now
con, freqs, times, n_epochs, n_tapers = spectral_connectivity(
    epochs, method='pli', mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax,
    faverage=True, tmin=tmin, mt_adaptive=False, n_jobs=1)

# Now, visualize the connectivity in 3D
plot_sensors_connectivity(epochs.info, con[:, :, 0])


I am working on the file "0.20/_downloads/995d3b6a9ece3566320943b2dcc13e22/plot_opm_data.ipynb".
The first task is:
Examine our coordinate alignment for source localization and compute a
forward operator:

Note

The Head<->MRI transform is an identity matrix, as the
          co-registration method used equates the two coordinate
          systems. This mis-defines the head coordinate system
          (which should be based on the LPA, Nasion, and RPA)
          but should be fine for these analyses.

Can you write Python code for it?

bem = mne.read_bem_solution(bem_fname)
trans = None

# To compute the forward solution, we must
# provide our temporary/custom coil definitions, which can be done as::
#
# with mne.use_coil_def(coil_def_fname):
#     fwd = mne.make_forward_solution(
#         raw.info, trans, src, bem, eeg=False, mindist=5.0,
#         n_jobs=1, verbose=True)

fwd = mne.read_forward_solution(fwd_fname)

with mne.use_coil_def(coil_def_fname):
    fig = mne.viz.plot_alignment(
        raw.info, trans, subject, subjects_dir, ('head', 'pial'), bem=bem)

mne.viz.set_3d_view(figure=fig, azimuth=45, elevation=60, distance=0.4,
                    focalpoint=(0.02, 0, 0.04))


I am working on the file "0.20/_downloads/995d3b6a9ece3566320943b2dcc13e22/plot_opm_data.ipynb".
The first task is:
Optically pumped magnetometer (OPM) data
In this dataset, electrical median nerve stimulation was delivered to the
left wrist of the subject. Somatosensory evoked fields were measured using
nine QuSpin SERF OPMs placed over the right-hand side somatomotor area.
Here we demonstrate how to localize these custom OPM data in MNE.
Can you write Python code for it?

import os.path as op

import numpy as np
import mne

data_path = mne.datasets.opm.data_path()
subject = 'OPM_sample'
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_SEF_raw.fif')
bem_fname = op.join(subjects_dir, subject, 'bem',
                    subject + '-5120-5120-5120-bem-sol.fif')
fwd_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_sample-fwd.fif')
coil_def_fname = op.join(data_path, 'MEG', 'OPM', 'coil_def.dat')


I am working on the file "0.20/_downloads/995d3b6a9ece3566320943b2dcc13e22/plot_opm_data.ipynb".
The first task is:
Perform minimum-norm localization
Due to the small number of sensors, there will be some leakage of activity
to areas with low/no sensitivity. Constraining the source space to
areas we are sensitive to might be a good idea.
Can you write Python code for it?

inverse_operator = mne.minimum_norm.make_inverse_operator(
    evoked.info, fwd, cov)

method = "MNE"
snr = 3.
lambda2 = 1. / snr ** 2
stc = mne.minimum_norm.apply_inverse(
    evoked, inverse_operator, lambda2, method=method,
    pick_ori=None, verbose=True)

# Plot source estimate at time of best dipole fit
brain = stc.plot(hemi='rh', views='lat', subjects_dir=subjects_dir,
                 initial_time=dip_opm.times[idx],
                 clim=dict(kind='percent', lims=[99, 99.9, 99.99]))


I am working on the file "0.20/_downloads/995d3b6a9ece3566320943b2dcc13e22/plot_opm_data.ipynb".
The first task is:
Prepare data for localization
First we filter and epoch the data:
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(None, 90, h_trans_bandwidth=10.)
raw.notch_filter(50., notch_widths=1)

# Set epoch rejection threshold a bit larger than for SQUIDs
reject = dict(mag=2e-10)
tmin, tmax = -0.5, 1

# Find Median nerve stimulator trigger
event_id = dict(Median=257)
events = mne.find_events(raw, stim_channel='STI101', mask=257, mask_type='and')
picks = mne.pick_types(raw.info, meg=True, eeg=False)
# we use verbose='error' to suppress warning about decimation causing aliasing
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, verbose='error',
                    reject=reject, picks=picks, proj=False, decim=4)
evoked = epochs.average()
evoked.plot()
cov = mne.compute_covariance(epochs, tmax=0.)


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:

Note

Before applying SSP (or any artifact repair strategy), be sure to observe
    the artifacts in your data to make sure you choose the right repair tool.
    Sometimes the right tool is no tool at all — if the artifacts are small
    enough you may not even need to repair them to get good analysis results.
    See `tut-artifact-overview` for guidance on detecting and
    visualizing various types of artifact.

What is SSP?
Signal-space projection (SSP) :footcite:UusitaloIlmoniemi1997 is a
technique for removing noise from EEG
and MEG signals by :term:projecting <projector> the signal onto a
lower-dimensional subspace. The subspace is chosen by calculating the average
pattern across sensors when the noise is present, treating that pattern as
a "direction" in the sensor space, and constructing the subspace to be
orthogonal to the noise direction (for a detailed walk-through of projection
see tut-projectors-background).
The most common use of SSP is to remove noise from MEG signals when the noise
comes from environmental sources (sources outside the subject's body and the
MEG system, such as the electromagnetic fields from nearby electrical
equipment) and when that noise is stationary (doesn't change much over the
duration of the recording). However, SSP can also be used to remove
biological artifacts such as heartbeat (ECG) and eye movement (EOG)
artifacts. Examples of each of these are given below.
Example: Environmental noise reduction from empty-room recordings
The example data <sample-dataset> was recorded on a Neuromag system,
which stores SSP projectors for environmental noise removal in the system
configuration (so that reasonably clean raw data can be viewed in real-time
during acquisition). For this reason, all the :class:~mne.io.Raw data in
the example dataset already includes SSP projectors, which are noted in the
output when loading the data:
Can you write Python code for it?

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


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Creating the empty-room projectors
We create the SSP vectors using :func:~mne.compute_proj_raw, and control
the number of projectors with parameters n_grad and n_mag. Once
created, the field pattern of the projectors can be easily visualized with
:func:~mne.viz.plot_projs_topomap. We include the parameter
vlim='joint' so that the colormap is computed jointly for all projectors
of a given channel type; this makes it easier to compare their relative
smoothness. Note that for the function to know the types of channels in a
projector, you must also provide the corresponding :class:~mne.Info object:
Can you write Python code for it?

empty_room_projs = mne.compute_proj_raw(empty_room_raw, n_grad=3, n_mag=3)
mne.viz.plot_projs_topomap(empty_room_projs, colorbar=True, vlim='joint',
                           info=empty_room_raw.info)


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Just like with the empty-room and ECG projectors, we can visualize the scalp
distribution:
Can you write Python code for it?


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Just like with the empty-room projectors, we can visualize the scalp
distribution:
Can you write Python code for it?


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Notice that the empty room recording itself has the system-provided SSP
projectors in it — we'll remove those from the empty room file too.
Can you write Python code for it?


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Notice that the gradiometer-based projectors seem to reflect problems with
individual sensor units rather than a global noise source (indeed, planar
gradiometers are much less sensitive to distant sources). This is the reason
that the system-provided noise projectors are computed only for
magnetometers. Comparing the system-provided projectors to the
subject-specific ones, we can see they are reasonably similar (though in a
different order) and the left-right component seems to have changed
polarity.
Can you write Python code for it?

fig, axs = plt.subplots(2, 3)
for idx, _projs in enumerate([system_projs, empty_room_projs[3:]]):
    mne.viz.plot_projs_topomap(_projs, axes=axs[idx], colorbar=True,
                               vlim='joint', info=empty_room_raw.info)


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Now we repeat the plot from above (with empty room and ECG projectors) and
compare it to a plot with empty room, ECG, and EOG projectors, to see how
well the ocular artifacts have been repaired:
Can you write Python code for it?

for title in ('Without', 'With'):
    if title == 'With':
        raw.add_proj(eog_projs)
    fig = raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} EOG projectors'.format(title), size='xx-large',
                 weight='bold')


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Plotting the ERP/F using evoked.plot() or evoked.plot_joint() with
and without projectors applied can also be informative.
Example: EOG and ECG artifact repair
Visualizing the artifacts
As mentioned in the ICA tutorial <tut-artifact-ica>, an important
first step is visualizing the artifacts you want to repair. Here they are in
the raw data:
Can you write Python code for it?

# pick some channels that clearly show heartbeats and blinks
regexp = r'(MEG [12][45][123]1|EEG 00.)'
artifact_picks = mne.pick_channels_regexp(raw.ch_names, regexp=regexp)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks))


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Repairing artifacts with SSP
This tutorial covers the basics of signal-space projection (SSP) and shows
how SSP can be used for artifact repair; extended examples illustrate use
of SSP for environmental noise reduction, and for repair of ocular and
heartbeat artifacts.
   :depth: 2
We begin as always by importing the necessary Python modules. To save ourselves
from repeatedly typing mne.preprocessing we'll directly import a couple
functions from that submodule:
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import (create_eog_epochs, create_ecg_epochs,
                               compute_proj_ecg, compute_proj_eog)


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
The effect is sometimes easier to see on averaged data. Here we use an
interactive feature of :func:mne.Evoked.plot_topomap to turn projectors on
and off to see the effect on the data. Of course, the interactivity won't
work on the tutorial website, but you can download the tutorial and try it
locally:
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
event_id = {'auditory/left': 1}

# NOTE: appropriate rejection criteria are highly data-dependent
reject = dict(mag=4000e-15,     # 4000 fT
              grad=4000e-13,    # 4000 fT/cm
              eeg=150e-6,       # 150 µV
              eog=250e-6)       # 250 µV

# time range where we expect to see the auditory N100: 50-150 ms post-stimulus
times = np.linspace(0.05, 0.15, 5)

epochs = mne.Epochs(raw, events, event_id, proj='delayed', reject=reject)
fig = epochs.average().plot_topomap(times, proj='interactive')


I am working on the file "0.20/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
The first line of output tells us that
:func:~mne.preprocessing.compute_proj_ecg found three existing projectors
already in the :class:~mne.io.Raw object, and will include those in the
list of projectors that it returns (appending the new ECG projectors to the
end of the list). If you don't want that, you can change that behavior with
the boolean no_proj parameter. Since we've already run the computation,
we can just as easily separate out the ECG projectors by indexing the list of
projectors:
Can you write Python code for it?


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
And visualize power is relative to the baseline:
Can you write Python code for it?

stc_data /= stc_base
brain = stc_data.plot(subject='sample', subjects_dir=subjects_dir,
                      clim=dict(kind='percent', lims=(50, 90, 98)))


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
Apply inverse operator to covariance
Finally, we can construct an inverse using the empty-room noise covariance:
Can you write Python code for it?

# Read the forward solution and compute the inverse operator
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fwd = mne.read_forward_solution(fname_fwd)

# make an MEG inverse operator
info = evoked.info
inverse_operator = make_inverse_operator(info, fwd, noise_cov,
                                         loose=0.2, depth=0.8)


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
Compute and plot covariances
In addition to the empty-room covariance above, we compute two additional
covariances:

Baseline covariance, which captures signals not of interest in our
   analysis (e.g., sensor noise, environmental noise, physiological
   artifacts, and also resting-state-like brain activity / "noise").
Data covariance, which captures our activation of interest (in addition
   to noise sources).
Can you write Python code for it?

base_cov = mne.compute_covariance(
    epochs, tmin=-0.2, tmax=0, method=['shrunk', 'empirical'], rank=None,
    verbose=True)
data_cov = mne.compute_covariance(
    epochs, tmin=0., tmax=0.2, method=['shrunk', 'empirical'], rank=None,
    verbose=True)

fig_noise_cov = mne.viz.plot_cov(noise_cov, epochs.info, show_svd=False)
fig_base_cov = mne.viz.plot_cov(base_cov, epochs.info, show_svd=False)
fig_data_cov = mne.viz.plot_cov(data_cov, epochs.info, show_svd=False)


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
Compute empty-room covariance
First we compute an empty-room covariance, which captures noise from the
sensors and environment.
Can you write Python code for it?

raw_empty_room_fname = op.join(
    data_path, 'MEG', 'sample', 'ernoise_raw.fif')
raw_empty_room = mne.io.read_raw_fif(raw_empty_room_fname)
raw_empty_room.crop(0, 60)
raw_empty_room.info['bads'] = ['MEG 2443']
raw_empty_room.info['projs'] = raw.info['projs']
noise_cov = mne.compute_raw_covariance(
    raw_empty_room, method=['empirical', 'shrunk'])
del raw_empty_room


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
Compute source power estimate by projecting the covariance with MNE
We can apply the MNE inverse operator to a covariance matrix to obtain
an estimate of source power. This is computationally more efficient than first
estimating the source timecourses and then computing their power.
Can you write Python code for it?

# Author: Denis A. Engemann <denis-alexander.engemann@inria.fr>
#         Luke Bloy <luke.bloy@gmail.com>
#
# License: BSD (3-clause)

import os.path as op
import numpy as np

import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse_cov

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
Epoch the data
Can you write Python code for it?

raw.info['bads'] = ['MEG 2443', 'EEG 053']
raw.load_data().filter(4, 12)
events = mne.find_events(raw, stim_channel='STI 014')
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)
tmin, tmax = -0.2, 0.5
baseline = (None, 0)  # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw.copy().filter(4, 12), events, event_id, tmin, tmax,
                    proj=True, picks=('meg', 'eog'), baseline=None,
                    reject=reject, preload=True)
del raw


I am working on the file "0.20/_downloads/9ae38deb3b38617e0444984e7140c666/plot_mne_cov_power.ipynb".
The first task is:
Project our data and baseline covariance to source space:
Can you write Python code for it?

stc_data = apply_inverse_cov(data_cov, evoked.info, inverse_operator,
                             nave=len(epochs), method='dSPM', verbose=True)
stc_base = apply_inverse_cov(base_cov, evoked.info, inverse_operator,
                             nave=len(epochs), method='dSPM', verbose=True)


I am working on the file "0.20/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Compute label time series and do envelope correlation
Can you write Python code for it?

epochs.apply_hilbert()  # faster to do in sensor space
stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)
corr = envelope_correlation(stcs, verbose=True)


I am working on the file "0.20/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Here we do some things in the name of speed, such as crop (which will
hurt SNR) and downsample. Then we compute SSP projectors and apply them.
Can you write Python code for it?

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, crop_to).load_data().pick_types(meg=True, eeg=False).resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw)  # compute before band-pass of interest


I am working on the file "0.20/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Now we band-pass filter our data and create epochs.
Can you write Python code for it?

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
                    baseline=None, reject=dict(mag=8e-13), preload=True)
del raw


I am working on the file "0.20/_downloads/a0b8e095ddf79d437494061b36af56fb/plot_resolution_metrics.ipynb".
The first task is:
MNE
Compute resolution matrices, peak localisation error (PLE) for point spread
functions (PSFs), spatial deviation (SD) for PSFs:
Can you write Python code for it?

rm_mne = make_inverse_resolution_matrix(forward, inverse_operator,
                                        method='MNE', lambda2=lambda2)
ple_mne_psf = resolution_metrics(rm_mne, inverse_operator['src'],
                                 function='psf', metric='peak_err')
sd_mne_psf = resolution_metrics(rm_mne, inverse_operator['src'],
                                function='psf', metric='sd_ext')
del rm_mne


I am working on the file "0.20/_downloads/a0b8e095ddf79d437494061b36af56fb/plot_resolution_metrics.ipynb".
The first task is:
These plots show that  dSPM has generally lower peak localization error (red
color) than MNE in deeper brain areas, but higher error (blue color) in more
superficial areas.
Next we'll visualise spatial deviation (SD) across the whole cortex for PSF:
Can you write Python code for it?

brain_sd_mne = sd_mne_psf.plot('sample', 'inflated', 'lh',
                               subjects_dir=subjects_dir, figure=4,
                               clim=dict(kind='value', lims=(0, 2, 4)))
brain_sd_mne.add_text(0.1, 0.9, 'SD MNE', 'title', font_size=16)

brain_sd_dspm = sd_dspm_psf.plot('sample', 'inflated', 'lh',
                                 subjects_dir=subjects_dir, figure=5,
                                 clim=dict(kind='value', lims=(0, 2, 4)))
brain_sd_dspm.add_text(0.1, 0.9, 'SD dSPM', 'title', font_size=16)

# Subtract the two distributions and plot this difference
diff_sd = sd_mne_psf - sd_dspm_psf

brain_sd_diff = diff_sd.plot('sample', 'inflated', 'lh',
                             subjects_dir=subjects_dir, figure=6,
                             clim=dict(kind='value', pos_lims=(0., 1., 2.)))
brain_sd_diff.add_text(0.1, 0.9, 'SD MNE-dSPM', 'title', font_size=16)


I am working on the file "0.20/_downloads/a0b8e095ddf79d437494061b36af56fb/plot_resolution_metrics.ipynb".
The first task is:
Visualize results
Visualise peak localisation error (PLE) across the whole cortex for PSF
Can you write Python code for it?

brain_ple_mne = ple_mne_psf.plot('sample', 'inflated', 'lh',
                                 subjects_dir=subjects_dir, figure=1,
                                 clim=dict(kind='value', lims=(0, 2, 4)))
brain_ple_mne.add_text(0.1, 0.9, 'PLE MNE', 'title', font_size=16)

brain_ple_dspm = ple_dspm_psf.plot('sample', 'inflated', 'lh',
                                   subjects_dir=subjects_dir, figure=2,
                                   clim=dict(kind='value', lims=(0, 2, 4)))
brain_ple_dspm.add_text(0.1, 0.9, 'PLE dSPM', 'title', font_size=16)

# Subtract the two distributions and plot this difference
diff_ple = ple_mne_psf - ple_dspm_psf

brain_ple_diff = diff_ple.plot('sample', 'inflated', 'lh',
                               subjects_dir=subjects_dir, figure=3,
                               clim=dict(kind='value', pos_lims=(0., 1., 2.)))
brain_ple_diff.add_text(0.1, 0.9, 'PLE MNE-dSPM', 'title', font_size=16)


I am working on the file "0.20/_downloads/a0b8e095ddf79d437494061b36af56fb/plot_resolution_metrics.ipynb".
The first task is:
dSPM
Do the same for dSPM:
Can you write Python code for it?

rm_dspm = make_inverse_resolution_matrix(forward, inverse_operator,
                                         method='dSPM', lambda2=lambda2)
ple_dspm_psf = resolution_metrics(rm_dspm, inverse_operator['src'],
                                  function='psf', metric='peak_err')
sd_dspm_psf = resolution_metrics(rm_dspm, inverse_operator['src'],
                                 function='psf', metric='sd_ext')
del rm_dspm


I am working on the file "0.20/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
Discarding dipole orientation information
Often, further analysis of the data does not need information about the
orientation of the dipoles, but rather their magnitudes. The pick_ori
parameter of the :func:mne.minimum_norm.apply_inverse function allows you
to specify whether to return the full vector solution ('vector') or
rather the magnitude of the vectors (None, the default) or only the
activity in the direction perpendicular to the cortex ('normal').
Can you write Python code for it?

# Only retain vector magnitudes
stc = apply_inverse(left_auditory, inv, pick_ori=None)

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


I am working on the file "0.20/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
Fixed dipole orientations
While the source space defines the position of the dipoles, the inverse
operator defines the possible orientations of them. One of the options is to
assign a fixed orientation. Since the neural currents from which MEG and EEG
signals originate flows mostly perpendicular to the cortex [1]_, restricting
the orientation of the dipoles accordingly places a useful restriction on the
source estimate.
By specifying fixed=True when calling
:func:mne.minimum_norm.make_inverse_operator, the dipole orientations are
fixed to be orthogonal to the surface of the cortex, pointing outwards. Let's
visualize this:
Can you write Python code for it?

fig = mne.viz.create_3d_figure(size=(600, 400))

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

# Show the dipoles as arrows pointing along the surface normal
fig = mne.viz.plot_dipole_locations(dipoles=dipoles, trans=trans,
                                    mode='arrow', subject=subject,
                                    subjects_dir=subjects_dir,
                                    coord_frame='head',
                                    scale=7e-4, fig=fig)

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


I am working on the file "0.20/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
The direction of the estimated current is now restricted to two directions:
inward and outward. In the plot, blue areas indicate current flowing inwards
and red areas indicate current flowing outwards. Given the curvature of the
cortex, groups of dipoles tend to point in the same direction: the direction
of the electromagnetic field picked up by the sensors.
Loose dipole orientations
Forcing the source dipoles to be strictly orthogonal to the cortex makes the
source estimate sensitive to the spacing of the dipoles along the cortex,
since the curvature of the cortex changes within each ~10 square mm patch.
Furthermore, misalignment of the MEG/EEG and MRI coordinate frames is more
critical when the source dipole orientations are strictly constrained [2]_.
To lift the restriction on the orientation of the dipoles, the inverse
operator has the ability to place not one, but three dipoles at each
location defined by the source space. These three dipoles are placed
orthogonally to form a Cartesian coordinate system. Let's visualize this:
Can you write Python code for it?

fig = mne.viz.create_3d_figure(size=(600, 400))

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

# Show the three dipoles defined at each location in the source space
fig = mne.viz.plot_alignment(subject=subject, subjects_dir=subjects_dir,
                             trans=trans, fwd=fwd,
                             surfaces='white', coord_frame='head', fig=fig)

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


I am working on the file "0.20/_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.20/_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.20/_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.20/_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.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Configuring MNE-Python
This tutorial covers how to configure MNE-Python to suit your local system and
your analysis preferences.
   :depth: 1
We begin by importing the necessary Python modules:
Can you write Python code for it?


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Getting and setting configuration variables
Configuration variables are read and written using the functions
:func:mne.get_config and :func:mne.set_config. To read a specific
configuration variable, pass its name to :func:~mne.get_config as the
key parameter (key is the first parameter so you can pass it unnamed
if you want):
Can you write Python code for it?


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
However it is not a good idea to directly edit files in the :file:.mne
directory; use the getting and setting functions described in the
previous section <config-get-set>.
If for some reason you want to load the configuration from a different
location, you can pass the home_dir parameter to
:func:~mne.get_config_path, specifying the parent directory of the
:file:.mne directory where the configuration file you wish to load is
stored.
Using environment variables
For compatibility with :doc:MNE-C <../../install/mne_c>, MNE-Python
also reads and writes environment variables_ to specify configuration. This
is done with the same functions that read and write the JSON configuration,
and is controlled with the parameters use_env and set_env. By
default, :func:~mne.get_config will check :data:os.environ before
checking the MNE-Python JSON file; to check only the JSON file use
use_env=False. To demonstrate, here's an environment variable that is not
specific to MNE-Python (and thus is not in the JSON config file):
Can you write Python code for it?

# make sure it's not in the JSON file (no error means our assertion held):
assert mne.get_config('PATH', use_env=False) is None
# but it *is* in the environment:
print(mne.get_config('PATH'))


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Let's delete that config variable we just created. To unset a config
variable, use :func:~mne.set_config with value=None. Since we're still
dealing with an unrecognized key (as far as MNE-Python is concerned) we'll
still get a warning, but the key will be unset:
Can you write Python code for it?

mne.set_config('MNEE_USE_CUUDAA', None)
assert 'MNEE_USE_CUUDAA' not in mne.get_config('')


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Logging
One important configuration variable is MNE_LOGGING_LEVEL. Throughout the
module, messages are generated describing the actions MNE-Python is taking
behind-the-scenes. How you set MNE_LOGGING_LEVEL determines how many of
those messages you see. The default logging level on a fresh install of
MNE-Python is info:
Can you write Python code for it?


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
No messages were generated, because none of the messages were of severity
"warning" or worse. Next, we'll load the same file with log level info
(the default level):
Can you write Python code for it?

raw = mne.io.read_raw_kit(kit_data_path, verbose='info')


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
The second convenience mode will return a :class:tuple of all the keys that
MNE-Python recognizes and uses, regardless of whether they've been set on
your system. This is done by passing an empty string '' as the key:
Can you write Python code for it?


I am working on the file "0.20/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Where configurations are stored
MNE-Python stores configuration variables in a JSON_ file. By default, this
file is located in :file:{%USERPROFILE%}\\.mne\\mne-python.json on Windows
and :file:{$HOME}/.mne/mne-python.json on Linux or macOS. You can get the
full path to the config file with :func:mne.get_config_path.
Can you write Python code for it?


I am working on the file "0.20/_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.20/_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.20/_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.
Here the classifier is 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.20/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Compute confusion matrix using ROC-AUC
Can you write Python code for it?

confusion = np.zeros((len(classes), len(classes)))
for ii, train_class in enumerate(classes):
    for jj in range(ii, len(classes)):
        confusion[ii, jj] = roc_auc_score(y == train_class, y_pred[:, jj])
        confusion[jj, ii] = confusion[ii, jj]


I am working on the file "0.20/_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.20/_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.20/_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.20/_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.20/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:

Note

If you forget to provide the event dictionary to the :class:`~mne.Epochs`
    constructor, you can add it later by assigning to the ``event_id``
    attribute::

        epochs.event_id = event_dict

Basic visualization of Epochs objects
The :class:~mne.Epochs object can be visualized (and browsed interactively)
using its :meth:~mne.Epochs.plot method:
Can you write Python code for it?


I am working on the file "0.20/_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.20/_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.20/_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.20/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Note that although time shifting respects the sampling frequency (the spacing
between samples), it does not enforce the assumption that there is a sample
occurring at exactly time=0.
Extracting data in other forms
The :meth:~mne.Epochs.get_data method returns the epoched data as a
:class:NumPy array <numpy.ndarray>, of shape (n_epochs, n_channels,
n_times); an optional picks parameter selects a subset of channels by
index, name, or type:
Can you write Python code for it?

eog_data = epochs.get_data(picks='EOG 061')
meg_data = epochs.get_data(picks=['mag', 'grad'])
channel_4_6_8 = epochs.get_data(picks=slice(4, 9, 2))

for name, arr in dict(EOG=eog_data, MEG=meg_data, Slice=channel_4_6_8).items():
    print('{} contains {} channels'.format(name, arr.shape[1]))


I am working on the file "0.20/_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.20/_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.20/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Selection in the time domain
To change the temporal extent of the :class:~mne.Epochs, you can use the
:meth:~mne.Epochs.crop method:
Can you write Python code for it?

shorter_epochs = epochs.copy().crop(tmin=-0.1, tmax=0.1, include_tmax=True)

for name, obj in dict(Original=epochs, Cropped=shorter_epochs).items():
    print('{} epochs has {} time samples'
          .format(name, obj.get_data().shape[-1]))


I am working on the file "0.20/_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.20/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
We can also pool across conditions easily, thanks to how MNE-Python handles
the / character in epoch labels (using what is sometimes called
"tag-based indexing"):
Can you write Python code for it?

# pool across left + right
print(epochs['auditory'])
assert len(epochs['auditory']) == (len(epochs['auditory/left']) +
                                   len(epochs['auditory/right']))
# pool across auditory + visual
print(epochs['left'])
assert len(epochs['left']) == (len(epochs['auditory/left']) +
                               len(epochs['visual/left']))


I am working on the file "0.20/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
You can also pool conditions by passing multiple tags as a list. Note that
MNE-Python will not complain if you ask for tags not present in the object,
as long as it can find some match: the below example is parsed as
(inclusive) 'right' or 'bottom', and you can see from the output
that it selects only auditory/right and visual/right.
Can you write Python code for it?


I am working on the file "0.20/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
You'll see from the output that:

all 320 events were used to create epochs

baseline correction was automatically applied (by default, baseline is
  defined as the time span from tmin to 0, but can be customized with
  the baseline parameter)

no additional metadata was provided (see tut-epochs-metadata for
  details)

the projection operators present in the :class:~mne.io.Raw file were
  copied over to the :class:~mne.Epochs object

If we print the :class:~mne.Epochs object, we'll also see a note that the
epochs are not copied into memory by default, and a count of the number of
epochs created for each integer Event ID.
Can you write Python code for it?


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
But here we can get slightly better noise suppression, lower localization
bias, and a better dipole goodness of fit with spatio-temporal (tSSS)
Maxwell filtering:
Can you write Python code for it?

raw.apply_gradient_compensation(0)  # must un-do software compensation first
mf_kwargs = dict(origin=(0., 0., 0.), st_duration=10.)
raw = mne.preprocessing.maxwell_filter(raw, **mf_kwargs)
raw.plot()


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Compare the actual position with the estimated one.
Can you write Python code for it?

expected_pos = np.array([18., 0., 49.])
diff = np.sqrt(np.sum((dip.pos[0] * 1000 - expected_pos) ** 2))
print('Actual pos:     %s mm' % np.array_str(expected_pos, precision=1))
print('Estimated pos:  %s mm' % np.array_str(dip.pos[0] * 1000, precision=1))
print('Difference:     %0.1f mm' % diff)
print('Amplitude:      %0.1f nAm' % (1e9 * dip.amplitude[0]))
print('GOF:            %0.1f %%' % dip.gof[0])


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Let's create some events using this signal by thresholding the sinusoid.
Can you write Python code for it?

events = np.where(np.diff(sinusoid > 0.5) > 0)[1] + raw.first_samp
events = np.vstack((events, np.zeros_like(events), np.ones_like(events))).T


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Let's use a sphere head geometry model <eeg_sphere_model>
and let's see the coordinate alignment and the sphere location.
Can you write Python code for it?

sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=None)

mne.viz.plot_alignment(raw.info, subject='sample',
                       meg='helmet', bem=sphere, dig=True,
                       surfaces=['brain'])
del raw, epochs


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Our choice of tmin and tmax should capture exactly one cycle, so
we can make the unusual choice of baselining using the entire epoch
when creating our evoked data. We also then crop to a single time point
(@t=0) because this is a peak in our signal.
Can you write Python code for it?

tmin = -0.5 / dip_freq
tmax = -tmin
epochs = mne.Epochs(raw, events, event_id=1, tmin=tmin, tmax=tmax,
                    baseline=(None, None))
evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.crop(0., 0.)


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
The CTF software compensation works reasonably well:
Can you write Python code for it?


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
The data were collected with a CTF system at 2400 Hz.
Can you write Python code for it?

data_path = bst_phantom_ctf.data_path(verbose=True)

# Switch to these to use the higher-SNR data:
# raw_path = op.join(data_path, 'phantom_200uA_20150709_01.ds')
# dip_freq = 7.
raw_path = op.join(data_path, 'phantom_20uA_20150603_03.ds')
dip_freq = 23.
erm_path = op.join(data_path, 'emptyroom_20150709_01.ds')
raw = read_raw_ctf(raw_path, preload=True)


I am working on the file "0.20/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
To do a dipole fit, let's use the covariance provided by the empty room
recording.
Can you write Python code for it?

raw_erm = read_raw_ctf(erm_path).apply_gradient_compensation(0)
raw_erm = mne.preprocessing.maxwell_filter(raw_erm, coord_frame='meg',
                                           **mf_kwargs)
cov = mne.compute_raw_covariance(raw_erm)
del raw_erm

dip, residual = fit_dipole(evoked, cov, sphere, verbose=True)


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

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


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

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

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

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


I am working on the file "0.20/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
However, it is not strictly necessary to load the :class:~mne.io.Raw object
in order to view or edit the :class:~mne.Info object; you can extract all
the relevant information into a stand-alone :class:~mne.Info object using
:func:mne.io.read_info:
Can you write Python code for it?

info = mne.io.read_info(sample_data_raw_file)
print(info)


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


I am working on the file "0.20/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
Note that the meg and fnirs parameters of :func:~mne.pick_types
accept strings as well as boolean values, to allow selecting only
magnetometer or gradiometer channels (via meg='mag' or meg='grad') or
to pick only oxyhemoglobin or deoxyhemoglobin channels (via fnirs='hbo'
or fnirs='hbr', respectively).
A third way to pick channels from an :class:~mne.Info object is to apply
regular expression_ matching to the channel names using
:func:mne.pick_channels_regexp. Here the ^ represents the beginning of
the string and . character matches any single character, so both EEG and
EOG channels will be selected:
Can you write Python code for it?


I am working on the file "0.20/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
Obtaining subsets of channels
It is often useful to convert between channel names and the integer indices
identifying rows of the data array where those channels' measurements are
stored. The :class:~mne.Info object is useful for this task; two
convenience functions that rely on the :class:mne.Info object for picking
channels are :func:mne.pick_channels and :func:mne.pick_types.
:func:~mne.pick_channels minimally takes a list of all channel names and a
list of channel names to include; it is also possible to provide an empty
list to include and specify which channels to exclude instead:
Can you write Python code for it?

print(mne.pick_channels(info['ch_names'], include=['MEG 0312', 'EEG 005']))

print(mne.pick_channels(info['ch_names'], include=[],
                        exclude=['MEG 0312', 'EEG 005']))


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

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


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
:meth:~mne.io.Raw.notch_filter also has parameters to control the notch
width, transition bandwidth and other aspects of the filter. See the
docstring for details.
Resampling
EEG and MEG recordings are notable for their high temporal precision, and are
often recorded with sampling rates around 1000 Hz or higher. This is good
when precise timing of events is important to the experimental design or
analysis plan, but also consumes more memory and computational resources when
processing the data. In cases where high-frequency components of the signal
are not of interest and precise timing is not needed (e.g., computing EOG or
ECG projectors on a long recording), downsampling the signal can be a useful
time-saver.
In MNE-Python, the resampling methods (:meth:raw.resample()
<mne.io.Raw.resample>, :meth:epochs.resample() <mne.Epochs.resample> and
:meth:evoked.resample() <mne.Evoked.resample>) apply a low-pass filter to
the signal to avoid aliasing, so you don't need to explicitly filter it
yourself first. This built-in filtering that happens when using
:meth:raw.resample() <mne.io.Raw.resample>, :meth:epochs.resample()
<mne.Epochs.resample>, or :meth:evoked.resample() <mne.Evoked.resample> is
a brick-wall filter applied in the frequency domain at the Nyquist
frequency of the desired new sampling rate. This can be clearly seen in the
PSD plot, where a dashed vertical line indicates the filter cutoff; the
original data had an existing lowpass at around 172 Hz (see
raw.info['lowpass']), and the data resampled from 600 Hz to 200 Hz gets
automatically lowpass filtered at 100 Hz (the Nyquist frequency_ for a
target rate of 200 Hz):
Can you write Python code for it?

raw_downsampled = raw.copy().resample(sfreq=200)

for data, title in zip([raw, raw_downsampled], ['Original', 'Downsampled']):
    fig = data.plot_psd(average=True)
    fig.subplots_adjust(top=0.9)
    fig.suptitle(title)
    plt.setp(fig.axes, xlim=(0, 300))


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Background on filtering
A filter removes or attenuates parts of a signal. Usually, filters act on
specific frequency ranges of a signal — for example, suppressing all
frequency components above or below a certain cutoff value. There are many
ways of designing digital filters; see disc-filtering for a longer
discussion of the various approaches to filtering physiological signals in
MNE-Python.
Repairing artifacts by filtering
Artifacts that are restricted to a narrow frequency range can sometimes
be repaired by filtering the data. Two examples of frequency-restricted
artifacts are slow drifts and power line noise. Here we illustrate how each
of these can be repaired by filtering.
Slow drifts
Low-frequency drifts in raw data can usually be spotted by plotting a fairly
long span of data with the :meth:~mne.io.Raw.plot method, though it is
helpful to disable channel-wise DC shift correction to make slow drifts
more readily visible. Here we plot 60 seconds, showing all the magnetometer
channels:
Can you write Python code for it?

mag_channels = mne.pick_types(raw.info, meg='mag')
raw.plot(duration=60, order=mag_channels, proj=False,
         n_channels=len(mag_channels), remove_dc=False)


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Because resampling involves filtering, there are some pitfalls to resampling
at different points in the analysis stream:

Performing resampling on :class:~mne.io.Raw data (before epoching) will
  negatively affect the temporal precision of Event arrays, by causing
  jitter_ in the event timing. This reduced temporal precision will
  propagate to subsequent epoching operations.

Performing resampling after epoching can introduce edge artifacts on
  every epoch, whereas filtering the :class:~mne.io.Raw object will only
  introduce artifacts at the start and end of the recording (which is often
  far enough from the first and last epochs to have no affect on the
  analysis).

The following section suggests best practices to mitigate both of these
issues.
Best practices
To avoid the reduction in temporal precision of events that comes with
resampling a :class:~mne.io.Raw object, and also avoid the edge artifacts
that come with filtering an :class:~mne.Epochs or :class:~mne.Evoked
object, the best practice is to:

low-pass filter the :class:~mne.io.Raw data at or below
   $\frac{1}{3}$ of the desired sample rate, then

decimate the data after epoching, by either passing the decim
   parameter to the :class:~mne.Epochs constructor, or using the
   :meth:~mne.Epochs.decimate method after the :class:~mne.Epochs have
   been created.

Warning

The recommendation for setting the low-pass corner frequency at
   $\frac{1}{3}$ of the desired sample rate is a fairly safe rule of
   thumb based on the default settings in :meth:`raw.filter()
   <mne.io.Raw.filter>` (which are different from the filter settings used
   inside the :meth:`raw.resample() <mne.io.Raw.resample>` method). If you
   use a customized lowpass filter (specifically, if your transition
   bandwidth is wider than 0.5× the lowpass cutoff), downsampling to 3× the
   lowpass cutoff may still not be enough to avoid `aliasing`_, and
   MNE-Python will not warn you about it (because the :class:`raw.info
  ...
Can you write Python code for it?

current_sfreq = raw.info['sfreq']
desired_sfreq = 90  # Hz
decim = np.round(current_sfreq / desired_sfreq).astype(int)
obtained_sfreq = current_sfreq / decim
lowpass_freq = obtained_sfreq / 3.

raw_filtered = raw.copy().filter(l_freq=None, h_freq=lowpass_freq)
events = mne.find_events(raw_filtered)
epochs = mne.Epochs(raw_filtered, events, decim=decim)

print('desired sampling frequency was {} Hz; decim factor of {} yielded an '
      'actual sampling frequency of {} Hz.'
      .format(desired_sfreq, decim, epochs.info['sfreq']))


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Filtering and resampling data
This tutorial covers filtering and resampling, and gives examples of how
filtering can be used for artifact repair.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>. We'll also crop the data to 60 seconds
(to save memory on the documentation server):
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
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(0, 60).load_data()  # use just 60 seconds of data, to save memory


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
It should be evident that MEG channels are more susceptible to this kind of
interference than EEG that is recorded in the magnetically shielded room.
Removing power-line noise can be done with a notch filter,
applied directly to the :class:~mne.io.Raw object, specifying an array of
frequencies to be attenuated. Since the EEG channels are relatively
unaffected by the power line noise, we'll also specify a picks argument
so that only the magnetometers and gradiometers get filtered:
Can you write Python code for it?

meg_picks = mne.pick_types(raw.info)  # meg=True, eeg=False are the defaults
freqs = (60, 120, 180, 240)
raw_notch = raw.copy().notch_filter(freqs=freqs, picks=meg_picks)
for title, data in zip(['Un', 'Notch '], [raw, raw_notch]):
    fig = data.plot_psd(fmax=250, average=True)
    fig.subplots_adjust(top=0.85)
    fig.suptitle('{}filtered'.format(title), size='xx-large', weight='bold')
    add_arrows(fig.axes[:2])


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Looks like 0.1 Hz was not quite high enough to fully remove the slow drifts.
Notice that the text output summarizes the relevant characteristics of the
filter that was created. If you want to visualize the filter, you can pass
the same arguments used in the call to :meth:raw.filter()
<mne.io.Raw.filter> above to the function :func:mne.filter.create_filter
to get the filter parameters, and then pass the filter parameters to
:func:mne.viz.plot_filter. :func:~mne.filter.create_filter also requires
parameters data (a :class:NumPy array <numpy.ndarray>) and sfreq
(the sampling frequency of the data), so we'll extract those from our
:class:~mne.io.Raw object:
Can you write Python code for it?

filter_params = mne.filter.create_filter(raw.get_data(), raw.info['sfreq'],
                                         l_freq=0.2, h_freq=None)


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Notice that the output is the same as when we applied this filter to the data
using :meth:raw.filter() <mne.io.Raw.filter>. You can now pass the filter
parameters (and the sampling frequency) to :func:~mne.viz.plot_filter to
plot the filter:
Can you write Python code for it?

mne.viz.plot_filter(filter_params, raw.info['sfreq'], flim=(0.01, 5))


I am working on the file "0.20/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Power line noise
Power line noise is an environmental artifact that manifests as persistent
oscillations centered around the AC power line frequency_. Power line
artifacts are easiest to see on plots of the spectrum, so we'll use
:meth:~mne.io.Raw.plot_psd to illustrate. We'll also write a little
function that adds arrows to the spectrum plot to highlight the artifacts:
Can you write Python code for it?

def add_arrows(axes):
    # add some arrows at 60 Hz and its harmonics
    for ax in axes:
        freqs = ax.lines[-1].get_xdata()
        psds = ax.lines[-1].get_ydata()
        for freq in (60, 120, 180, 240):
            idx = np.searchsorted(freqs, freq)
            # get ymax of a small region around the freq. of interest
            y = psds[(idx - 4):(idx + 5)].max()
            ax.arrow(x=freqs[idx], y=y + 18, dx=0, dy=-12, color='red',
                     width=0.1, head_width=3, length_includes_head=True)

fig = raw.plot_psd(fmax=250, average=True)
add_arrows(fig.axes[:2])


I am working on the file "0.20/_downloads/b44431cb3a9d20511482e4da8b41ff49/plot_gamma_map_inverse.ipynb".
The first task is:
Compute a sparse inverse solution using the Gamma-Map empirical Bayesian method
See [1]_ for details.
References
.. [1] D. Wipf, S. Nagarajan
   "A unified Bayesian framework for MEG/EEG source imaging",
   Neuroimage, Volume 44, Number 3, pp. 947-966, Feb. 2009.
   DOI: 10.1016/j.neuroimage.2008.02.059
Can you write Python code for it?

# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne.datasets import sample
from mne.inverse_sparse import gamma_map, make_stc_from_dipoles
from mne.viz import (plot_sparse_source_estimates,
                     plot_dipole_locations, plot_dipole_amplitudes)

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'

# Read the evoked response and crop it
condition = 'Left visual'
evoked = mne.read_evokeds(evoked_fname, condition=condition,
                          baseline=(None, 0))
evoked.crop(tmin=-50e-3, tmax=300e-3)

# Read the forward solution
forward = mne.read_forward_solution(fwd_fname)

# Read noise noise covariance matrix and regularize it
cov = mne.read_cov(cov_fname)
cov = mne.cov.regularize(cov, evoked.info, rank=None)

# Run the Gamma-MAP method with dipole output
alpha = 0.5
dipoles, residual = gamma_map(
    evoked, forward, cov, alpha, xyz_same_gamma=True, return_residual=True,
    return_as_dipoles=True)


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

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


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

ylim = dict(grad=[-120, 120])
evoked.pick_types(meg='grad', exclude='bads')
evoked.plot(titles=dict(grad='Evoked Response Gradiometers'), ylim=ylim,
            proj=True, time_unit='s')

residual.pick_types(meg='grad', exclude='bads')
residual.plot(titles=dict(grad='Residuals Gradiometers'), ylim=ylim,
              proj=True, time_unit='s')


I am working on the file "0.20/_downloads/b44431cb3a9d20511482e4da8b41ff49/plot_gamma_map_inverse.ipynb".
The first task is:
View in 2D and 3D ("glass" brain like 3D plot)
Show the sources as spheres scaled by their strength
Can you write Python code for it?

scale_factors = np.max(np.abs(stc.data), axis=1)
scale_factors = 0.5 * (1 + scale_factors / np.max(scale_factors))

plot_sparse_source_estimates(
    forward['src'], stc, bgcolor=(1, 1, 1),
    modes=['sphere'], opacity=0.1, scale_factors=(scale_factors, None),
    fig_name="Gamma-MAP")


I am working on the file "0.20/_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.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Data channel array consisted of 204 MEG planor gradiometers,
102 axial magnetometers, and 3 stimulus channels. Let's get the events
for the phantom, where each dipole (1-32) gets its own event:
Can you write Python code for it?

events = find_events(raw, 'STI201')
raw.plot(events=events)
raw.info['bads'] = ['MEG1933', 'MEG2421']


I am working on the file "0.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's do some dipole fits. We first compute the noise covariance,
then do the fits for each event_id taking the time instant that maximizes
the global field power.
Can you write Python code for it?

# here we can get away with using method='oas' for speed (faster than "shrunk")
# but in general "shrunk" is usually better
cov = mne.compute_covariance(epochs, tmax=bmax)
mne.viz.plot_evoked_white(epochs['1'].average(), cov)

data = []
t_peak = 0.036  # true for Elekta phantom
for ii in event_id:
    # Avoid the first and last trials -- can contain dipole-switching artifacts
    evoked = epochs[str(ii)][1:-1].average().crop(t_peak, t_peak)
    data.append(evoked.data[:, 0])
evoked = mne.EvokedArray(np.array(data).T, evoked.info, tmin=0.)
del epochs
dip, residual = fit_dipole(evoked, cov, sphere, n_jobs=1)


I am working on the file "0.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's plot the positions and the orientations of the actual and the estimated
dipoles
Can you write Python code for it?

actual_amp = np.ones(len(dip))  # misc amp to create Dipole instance
actual_gof = np.ones(len(dip))  # misc GOF to create Dipole instance
dip_true = \
    mne.Dipole(dip.times, actual_pos, actual_amp, actual_ori, actual_gof)

fig = mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces='inner_skull',
                             coord_frame='head', meg='helmet', show_axes=True)

# Plot the position and the orientation of the actual dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip_true, mode='arrow',
                                    subject=subject, color=(0., 0., 0.),
                                    fig=fig)

# Plot the position and the orientation of the estimated dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip, mode='arrow', subject=subject,
                                    color=(0.2, 1., 0.5), fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=70, elevation=80, distance=0.5)


I am working on the file "0.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Now we can compare to the actual locations, taking the difference in mm:
Can you write Python code for it?

actual_pos, actual_ori = mne.dipole.get_phantom_dipoles()
actual_amp = 100.  # nAm

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, figsize=(6, 7))

diffs = 1000 * np.sqrt(np.sum((dip.pos - actual_pos) ** 2, axis=-1))
print('mean(position error) = %0.1f mm' % (np.mean(diffs),))
ax1.bar(event_id, diffs)
ax1.set_xlabel('Dipole index')
ax1.set_ylabel('Loc. error (mm)')

angles = np.rad2deg(np.arccos(np.abs(np.sum(dip.ori * actual_ori, axis=1))))
print(u'mean(angle error) = %0.1f°' % (np.mean(angles),))
ax2.bar(event_id, angles)
ax2.set_xlabel('Dipole index')
ax2.set_ylabel(u'Angle error (°)')

amps = actual_amp - dip.amplitude / 1e-9
print('mean(abs amplitude error) = %0.1f nAm' % (np.mean(np.abs(amps)),))
ax3.bar(event_id, amps)
ax3.set_xlabel('Dipole index')
ax3.set_ylabel('Amplitude error (nAm)')

fig.tight_layout()
plt.show()


I am working on the file "0.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Now we epoch our data, average it, and look at the first dipole response.
The first peak appears around 3 ms. Because we low-passed at 40 Hz,
we can also decimate our data to save memory.
Can you write Python code for it?

tmin, tmax = -0.1, 0.1
bmax = -0.05  # Avoid capture filter ringing into baseline
event_id = list(range(1, 33))
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=(None, bmax),
                    preload=False)
epochs['1'].average().plot(time_unit='s')


I am working on the file "0.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
The data have strong line frequency (60 Hz and harmonics) and cHPI coil
noise (five peaks around 300 Hz). Here we plot only out to 60 seconds
to save memory:
Can you write Python code for it?


I am working on the file "0.20/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
The data were collected with an Elekta Neuromag VectorView system at 1000 Hz
and low-pass filtered at 330 Hz. Here the medium-amplitude (200 nAm) data
are read to construct instances of :class:mne.io.Raw.
Can you write Python code for it?

data_path = bst_phantom_elekta.data_path(verbose=True)
subject = 'sample'

raw_fname = op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif')
raw = read_raw_fif(raw_fname)


I am working on the file "0.20/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
.. sidebar:: Blocking execution
If you want to build an interactive bad-channel-marking step into an
analysis script, be sure to include the parameter ``block=True`` in your
call to ``raw.plot()`` or ``epochs.plot()``. This will pause the script
while the plot is open, giving you time to mark bad channels before
subsequent analysis or plotting steps are executed. This can be
especially helpful if your script loops over multiple subjects.

You can also interactively toggle whether a channel is marked "bad" in the
plot windows of raw.plot() or epochs.plot() by clicking on the
channel name along the vertical axis (in raw.plot() windows you can also
do this by clicking the channel's trace in the plot area). The bads field
gets updated immediately each time you toggle a channel, and will retain its
modified state after the plot window is closed.
The list of bad channels in the :class:mne.Info object's bads field is
automatically taken into account in dozens of functions and methods across
the MNE-Python codebase. This is done consistently with a parameter
exclude='bads' in the function or method signature. Typically this
exclude parameter also accepts a list of channel names or indices, so if
you want to include the bad channels you can do so by passing
exclude=[] (or some other list of channels to exclude). For example:
Can you write Python code for it?

# default is exclude='bads':
good_eeg = mne.pick_types(raw.info, meg=False, eeg=True)
all_eeg = mne.pick_types(raw.info, meg=False, eeg=True, exclude=[])
print(np.setdiff1d(all_eeg, good_eeg))
print(np.array(raw.ch_names)[np.setdiff1d(all_eeg, good_eeg)])


I am working on the file "0.20/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
Interpolating bad channels
This tutorial covers manual marking of bad channels and reconstructing bad
channels based on good signals at other sensors.
   :depth: 2
As usual we'll start by importing the modules we need, and loading some example
data:
Can you write Python code for it?

import os
from copy import deepcopy
import numpy as np
import mne

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


I am working on the file "0.20/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
Marking bad channels
Sometimes individual channels malfunction and provide data that is too noisy
to be usable. MNE-Python makes it easy to ignore those channels in the
analysis stream without actually deleting the data in those channels. It does
this by
keeping track of the bad channel indices in a list and looking at that list
when doing analysis or plotting tasks. The list of bad channels is stored in
the 'bads' field of the :class:~mne.Info object that is attached to
:class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked objects.
Can you write Python code for it?


I am working on the file "0.20/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
Notice first of all that the channels marked as "bad" are plotted in a light
gray color in a layer behind the other channels, to make it easy to
distinguish them from "good" channels. The plots make it clear that EEG
053 is not picking up scalp potentials at all, and MEG 2443 looks like
it's got a lot more internal noise than its neighbors — its signal is a few
orders of magnitude greater than the other MEG channels, making it a clear
candidate for exclusion.
If you want to change which channels are marked as bad, you can edit
raw.info['bads'] directly; it's an ordinary Python :class:list so the
usual list methods will work:
Can you write Python code for it?

original_bads = deepcopy(raw.info['bads'])
raw.info['bads'].append('EEG 050')               # add a single channel
raw.info['bads'].extend(['EEG 051', 'EEG 052'])  # add a list of channels
bad_chan = raw.info['bads'].pop(-1)  # remove the last entry in the list
raw.info['bads'] = original_bads     # change the whole list at once


I am working on the file "0.20/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
When to look for bad channels
You can start looking for bad channels during the experiment session when the
data is being acquired. If you notice any flat or excessively noisy channels,
you can note them in your experiment log or protocol sheet. If your system
computes online averages, these can be a good way to spot bad channels as
well. After the data has been collected, you can do a more thorough check for
bad channels by browsing the raw data using :meth:mne.io.Raw.plot, with any
projectors or ICA applied. Finally, you can compute offline averages (again
with projectors, ICA, and EEG referencing disabled) to look for channels with
unusual properties. Here's an example of ERP/F plots where the bad channels
were not properly marked:
Can you write Python code for it?

raw2 = raw.copy()
raw2.info['bads'] = []
events = mne.find_events(raw2, stim_channel='STI 014')
epochs = mne.Epochs(raw2, events=events)['2'].average().plot()