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

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


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


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating MNE-Python data structures from scratch
This tutorial shows how to create MNE-Python's core data structures using an
existing :class:NumPy array <numpy.ndarray> of (real or synthetic) data.
   :depth: 1
We begin by importing the necessary Python modules:
Can you write Python code for it?


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating ~mne.Epochs objects
To create an ~mne.Epochs object from scratch, you can use the
mne.EpochsArray class constructor, which takes an ~mne.Info object and a
:class:NumPy array <numpy.ndarray> of shape (n_epochs, n_channels,
n_samples). Here we'll create 5 epochs of our 2-channel data, and plot it.
Notice that we have to pass picks='misc' to the ~mne.Epochs.plot
method, because by default it only plots :term:data channels.
Can you write Python code for it?

data = np.array([[0.2 * sine, 1.0 * cosine],
                 [0.4 * sine, 0.8 * cosine],
                 [0.6 * sine, 0.6 * cosine],
                 [0.8 * sine, 0.4 * cosine],
                 [1.0 * sine, 0.2 * cosine]])

simulated_epochs = mne.EpochsArray(data, info)
simulated_epochs.plot(picks='misc', show_scrollbars=False)


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating ~mne.io.Raw objects
.. sidebar:: Units
The expected units for the different channel types are:

- Volts: eeg, eog, seeg, emg, ecg, bio, ecog
- Teslas: mag
- Teslas/meter: grad
- Molar: hbo, hbr
- Amperes: dipole
- Arbitrary units: misc

To create a ~mne.io.Raw object from scratch, you can use the
mne.io.RawArray class constructor, which takes an ~mne.Info object and a
:class:NumPy array <numpy.ndarray> of shape (n_channels, n_samples).
Here, we'll create some sinusoidal data and plot it:
Can you write Python code for it?

times = np.linspace(0, 1, sampling_freq, endpoint=False)
sine = np.sin(20 * np.pi * times)
cosine = np.cos(10 * np.pi * times)
data = np.array([sine, cosine])

info = mne.create_info(ch_names=['10 Hz sine', '5 Hz cosine'],
                       ch_types=['misc'] * 2,
                       sfreq=sampling_freq)

simulated_raw = mne.io.RawArray(data, info)
simulated_raw.plot(show_scrollbars=False, show_scalebars=False)


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
If the channel names follow one of the standard montage naming schemes, their
spatial locations can be automatically added using the
~mne.Info.set_montage method:
Can you write Python code for it?

ch_names = ['Fp1', 'Fp2', 'Fz', 'Cz', 'Pz', 'O1', 'O2']
ch_types = ['eeg'] * 7
info = mne.create_info(ch_names, ch_types=ch_types, sfreq=sampling_freq)
info.set_montage('standard_1020')


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
If we want to simulate having different experimental conditions, we can pass
an event array (and an event ID dictionary) to the constructor. Since our
epochs are 1 second long and have 200 samples/second, we'll put our events
spaced 200 samples apart, and pass tmin=-0.5, so that the events
land in the middle of each epoch (the events are always placed at time=0 in
each epoch).
Can you write Python code for it?

events = np.column_stack((np.arange(0, 1000, sampling_freq),
                          np.zeros(5, dtype=int),
                          np.array([1, 2, 1, 2, 1])))
event_dict = dict(condition_A=1, condition_B=2)
simulated_epochs = mne.EpochsArray(data, info, tmin=-0.5, events=events,
                                   event_id=event_dict)
simulated_epochs.plot(picks='misc', show_scrollbars=False, events=events,
                      event_id=event_dict)


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Since we did not supply an events array, the ~mne.EpochsArray constructor
automatically created one for us, with all epochs having the same event
number:
Can you write Python code for it?


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
You can see in the output above that, by default, the channels are assigned
as type "misc" (where it says chs: 32 MISC). You can assign the channel
type when initializing the ~mne.Info object if you want:
Can you write Python code for it?

ch_names = [f'MEG{n:03}' for n in range(1, 10)] + ['EOG001']
ch_types = ['mag', 'grad', 'grad'] * 3 + ['eog']
info = mne.create_info(ch_names, ch_types=ch_types, sfreq=sampling_freq)
print(info)


I am working on the file "0.22/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
You could also create simulated epochs by using the normal ~mne.Epochs
(not ~mne.EpochsArray) constructor on the simulated ~mne.io.RawArray
object, by creating an events array (e.g., using
mne.make_fixed_length_events) and extracting epochs around those events.
Creating ~mne.Evoked Objects
If you already have data that was averaged across trials, you can use it to
create an ~mne.Evoked object using the ~mne.EvokedArray class
constructor.  It requires an ~mne.Info object and a data array of shape
(n_channels, n_times), and has an optional tmin parameter like
~mne.EpochsArray does. It also has a parameter nave indicating how many
trials were averaged together, and a comment parameter useful for keeping
track of experimental conditions, etc. Here we'll do the averaging on our
NumPy array and use the resulting averaged data to make our ~mne.Evoked.
Can you write Python code for it?

# Create the Evoked object
evoked_array = mne.EvokedArray(data.mean(axis=0), info, tmin=-0.5,
                               nave=data.shape[0], comment='simulated')
print(evoked_array)
evoked_array.plot()


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute inverse solution
We can use this to compute the inverse solution and obtain source time
courses:
Can you write Python code for it?

method = "dSPM"
snr = 3.
lambda2 = 1. / snr ** 2
stc, residual = apply_inverse(evoked, inverse_operator, lambda2,
                              method=method, pick_ori=None,
                              return_residual=True, verbose=True)


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute regularized noise covariance
For more details see tut_compute_covariance.
Can you write Python code for it?

noise_cov = mne.compute_covariance(
    epochs, tmax=0., method=['shrunk', 'empirical'], rank=None, verbose=True)

fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info)


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute the evoked response
Let's just use the MEG channels for simplicity.
Can you write Python code for it?

evoked = epochs.average().pick('meg')
evoked.plot(time_unit='s')
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag',
                    time_unit='s')


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Here we use peak getter to move visualization to the time point of the peak
and draw a marker at the maximum peak vertex.
Can you write Python code for it?

vertno_max, time_max = stc.get_peak(hemi='rh')

subjects_dir = data_path + '/subjects'
surfer_kwargs = dict(
    hemi='rh', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
    initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=10)
brain = stc.plot(**surfer_kwargs)
brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue',
               scale_factor=0.6, alpha=0.5)
brain.add_text(0.1, 0.9, 'dSPM (plus location of maximal activation)', 'title',
               font_size=14)

# The documentation website's movie is generated with:
# brain.save_movie(..., tmin=0.05, tmax=0.15, interpolation='linear',
#                  time_dilation=20, framerate=10, time_viewer=True)


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Inverse modeling: MNE/dSPM on evoked and raw data
Here we first read the forward solution. You will likely need to compute
one for your own data -- see tut-forward for information on how
to do it.
Can you write Python code for it?

fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fwd = mne.read_forward_solution(fname_fwd)


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
It's also a good idea to look at whitened data:
Can you write Python code for it?

evoked.plot_white(noise_cov, time_unit='s')
del epochs, raw  # to save memory


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Next, we make an MEG inverse operator.
Can you write Python code for it?

inverse_operator = make_inverse_operator(
    evoked.info, fwd, noise_cov, loose=0.2, depth=0.8)
del fwd

# You can write it to disk with::
#
#     >>> from mne.minimum_norm import write_inverse_operator
#     >>> write_inverse_operator('sample_audvis-meg-oct-6-inv.fif',
#                                inverse_operator)


I am working on the file "0.22/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Process MEG data
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

raw = mne.io.read_raw_fif(raw_fname)  # already has an average reference
events = mne.find_events(raw, stim_channel='STI 014')

event_id = dict(aud_l=1)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)
raw.info['bads'] = ['MEG 2443', 'EEG 053']
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, events, event_id, tmin, tmax, proj=True,
                    picks=('meg', 'eog'), baseline=baseline, reject=reject)


I am working on the file "0.23/_downloads/00ac060e49528fd74fda09b97366af98/3d_to_2d.ipynb".
The first task is:
How to convert 3D electrode positions to a 2D image.
Sometimes we want to convert a 3D representation of electrodes into a 2D
image. For example, if we are using electrocorticography it is common to
create scatterplots on top of a brain, with each point representing an
electrode.
In this example, we'll show two ways of doing this in MNE-Python. First,
if we have the 3D locations of each electrode then we can use Mayavi to
take a snapshot of a view of the brain. If we do not have these 3D locations,
and only have a 2D image of the electrodes on the brain, we can use the
:class:mne.viz.ClickableImage class to choose our own electrode positions
on the image.
Can you write Python code for it?

# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
from scipy.io import loadmat
import numpy as np
from matplotlib import pyplot as plt
from os import path as op

import mne
from mne.viz import ClickableImage  # noqa
from mne.viz import (plot_alignment, snapshot_brain_montage,
                     set_3d_view)

print(__doc__)

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
path_data = mne.datasets.misc.data_path() + '/ecog/sample_ecog.mat'

# We've already clicked and exported
layout_path = op.join(op.dirname(mne.__file__), 'data', 'image')
layout_name = 'custom_layout.lout'


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

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


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

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

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

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

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


I am working on the file "0.23/_downloads/00ac060e49528fd74fda09b97366af98/3d_to_2d.ipynb".
The first task is:
Project 3D electrodes to a 2D snapshot
Because we have the 3D location of each electrode, we can use the
:func:mne.viz.snapshot_brain_montage function to return a 2D image along
with the electrode positions on that image. We use this in conjunction with
:func:mne.viz.plot_alignment, which visualizes electrode positions.
Can you write Python code for it?

fig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces=['pial'], meg=False)
set_3d_view(figure=fig, azimuth=200, elevation=70)
xy, im = snapshot_brain_montage(fig, montage)

# Convert from a dictionary to array to plot
xy_pts = np.vstack([xy[ch] for ch in info['ch_names']])

# Define an arbitrary "activity" pattern for viz
activity = np.linspace(100, 200, xy_pts.shape[0])

# This allows us to use matplotlib to create arbitrary 2d scatterplots
fig2, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
# fig2.savefig('./brain.png', bbox_inches='tight')  # For ClickableImage


I am working on the file "0.23/_downloads/00e78bba5d10188fcf003ef05e32a6f7/decoding_time_generalization_conditions.ipynb".
The first task is:
Score on the epochs where the stimulus was presented to the right.
Can you write Python code for it?

scores = time_gen.score(X=epochs['Right'].get_data(),
                        y=epochs['Right'].events[:, 2] > 2)


I am working on the file "0.23/_downloads/00e78bba5d10188fcf003ef05e32a6f7/decoding_time_generalization_conditions.ipynb".
The first task is:
We will train the classifier on all left visual vs auditory trials
and test on all right visual vs auditory trials.
Can you write Python code for it?

clf = make_pipeline(StandardScaler(), LogisticRegression(solver='lbfgs'))
time_gen = GeneralizingEstimator(clf, scoring='roc_auc', n_jobs=1,
                                 verbose=True)

# Fit classifiers on the epochs where the stimulus was presented to the left.
# Note that the experimental condition y indicates auditory or visual
time_gen.fit(X=epochs['Left'].get_data(),
             y=epochs['Left'].events[:, 2] > 2)


I am working on the file "0.23/_downloads/029173f022506572bcefa009b440732f/evoked_arrowmap.ipynb".
The first task is:
Plot magnetometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

max_time_idx = np.abs(evoked_mag.data).mean(axis=0).argmax()
plot_arrowmap(evoked_mag.data[:, max_time_idx], evoked_mag.info)

# Since planar gradiometers takes gradients along latitude and longitude,
# they need to be projected to the flatten manifold span by magnetometer
# or radial gradiometers before taking the gradients in the 2D Cartesian
# coordinate system for visualization on the 2D topoplot. You can use the
# ``info_from`` and ``info_to`` parameters to interpolate from
# gradiometer data to magnetometer data.


I am working on the file "0.23/_downloads/029173f022506572bcefa009b440732f/evoked_arrowmap.ipynb".
The first task is:
Since Vectorview 102 system perform sparse spatial sampling of the magnetic
field, data from the Vectorview (info_from) can be projected to the high
density CTF 272 system (info_to) for visualization
Plot gradiometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

path = bst_raw.data_path()
raw_fname = path + ('/MEG/bst_raw/'
                    'subj001_somatosensory_20111109_01_AUX-f.ds')
raw_ctf = mne.io.read_raw_ctf(raw_fname)
raw_ctf_info = mne.pick_info(
    raw_ctf.info, mne.pick_types(raw_ctf.info, meg=True, ref_meg=False))
plot_arrowmap(evoked_grad.data[:, max_time_idx], info_from=evoked_grad.info,
              info_to=raw_ctf_info, scale=6e-10)


I am working on the file "0.23/_downloads/0602f866d20bff8af56294e10dd6854d/10_preprocessing_overview.ipynb".
The first task is:
Here again we can visualize the spatial pattern of the associated field at
various times relative to the peak of the EOG response:
Can you write Python code for it?


I am working on the file "0.23/_downloads/0602f866d20bff8af56294e10dd6854d/10_preprocessing_overview.ipynb".
The first task is:
Low-frequency drifts
Low-frequency drifts are most readily detected by visual inspection using the
basic :meth:~mne.io.Raw.plot method, though it is helpful to plot a
relatively long time span and to disable channel-wise DC shift correction.
Here we plot 60 seconds and show 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, n_channels=len(mag_channels),
         remove_dc=False)


I am working on the file "0.23/_downloads/0602f866d20bff8af56294e10dd6854d/10_preprocessing_overview.ipynb".
The first task is:
Low-frequency drifts are readily removed by high-pass filtering at a fairly
low cutoff frequency (the wavelength of the drifts seen above is probably
around 20 seconds, so in this case a cutoff of 0.1 Hz would probably suppress
most of the drift).
Power line noise
Power line artifacts are easiest to see on plots of the spectrum, so we'll
use :meth:~mne.io.Raw.plot_psd to illustrate.
Can you write Python code for it?

fig = raw.plot_psd(tmax=np.inf, fmax=250, average=True)
# add some arrows at 60 Hz and its harmonics:
for ax in fig.axes[1:]:
    freqs = ax.lines[-1].get_xdata()
    psds = ax.lines[-1].get_ydata()
    for freq in (60, 120, 180, 240):
        idx = np.searchsorted(freqs, freq)
        ax.arrow(x=freqs[idx], y=psds[idx] + 18, dx=0, dy=-12, color='red',
                 width=0.1, head_width=3, length_includes_head=True)


I am working on the file "0.23/_downloads/0602f866d20bff8af56294e10dd6854d/10_preprocessing_overview.ipynb".
The first task is:
Ocular artifacts (EOG)
Similar to the ECG detection and epoching methods described above, MNE-Python
also includes functions for detecting and extracting ocular artifacts:
:func:~mne.preprocessing.find_eog_events and
:func:~mne.preprocessing.create_eog_epochs. Once again we'll use the
higher-level convenience function that automatically finds the artifacts and
extracts them in to an :class:~mne.Epochs object in one step. Unlike the
heartbeat artifacts seen above, ocular artifacts are usually most prominent
in the EEG channels, but we'll still show all three channel types. We'll use
the baseline parameter this time too; note that there are many fewer
blinks than heartbeats, which makes the image plots appear somewhat blocky:
Can you write Python code for it?

eog_epochs = mne.preprocessing.create_eog_epochs(raw, baseline=(-0.5, -0.2))
eog_epochs.plot_image(combine='mean')
eog_epochs.average().plot_joint()


I am working on the file "0.23/_downloads/0602f866d20bff8af56294e10dd6854d/10_preprocessing_overview.ipynb".
The first task is:
The horizontal streaks in the magnetometer image plot reflect the fact that
the heartbeat artifacts are superimposed on low-frequency drifts like the one
we saw in an earlier section; to avoid this you could pass
baseline=(-0.5, -0.2) in the call to
:func:~mne.preprocessing.create_ecg_epochs.
You can also get a quick look at the
ECG-related field pattern across sensors by averaging the ECG epochs together
via the :meth:~mne.Epochs.average method, and then using the
:meth:mne.Evoked.plot_topomap method:
Can you write Python code for it?

avg_ecg_epochs = ecg_epochs.average().apply_baseline((-0.5, -0.2))


I am working on the file "0.23/_downloads/066ec12646ce0d0818ad9b78bc602218/fdr_stats_evoked.ipynb".
The first task is:
Compute statistic
Can you write Python code for it?

T, pval = stats.ttest_1samp(X, 0)
alpha = 0.05

n_samples, n_tests = X.shape
threshold_uncorrected = stats.t.ppf(1.0 - alpha, n_samples - 1)

reject_bonferroni, pval_bonferroni = bonferroni_correction(pval, alpha=alpha)
threshold_bonferroni = stats.t.ppf(1.0 - alpha / n_tests, n_samples - 1)

reject_fdr, pval_fdr = fdr_correction(pval, alpha=alpha, method='indep')
threshold_fdr = np.min(np.abs(T)[reject_fdr])


I am working on the file "0.23/_downloads/066ec12646ce0d0818ad9b78bc602218/fdr_stats_evoked.ipynb".
The first task is:
FDR correction on T-test on sensor data
One tests if the evoked response significantly deviates from 0.
Multiple comparison problem is addressed with
False Discovery Rate (FDR) correction.
Can you write Python code for it?

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

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

import mne
from mne import io
from mne.datasets import sample
from mne.stats import bonferroni_correction, fdr_correction

print(__doc__)


I am working on the file "0.23/_downloads/066ec12646ce0d0818ad9b78bc602218/fdr_stats_evoked.ipynb".
The first task is:
Plot
Can you write Python code for it?

times = 1e3 * epochs.times

plt.close('all')
plt.plot(times, T, 'k', label='T-stat')
xmin, xmax = plt.xlim()
plt.hlines(threshold_uncorrected, xmin, xmax, linestyle='--', colors='k',
           label='p=0.05 (uncorrected)', linewidth=2)
plt.hlines(threshold_bonferroni, xmin, xmax, linestyle='--', colors='r',
           label='p=0.05 (Bonferroni)', linewidth=2)
plt.hlines(threshold_fdr, xmin, xmax, linestyle='--', colors='b',
           label='p=0.05 (FDR)', linewidth=2)
plt.legend()
plt.xlabel("Time (ms)")
plt.ylabel("T-stat")
plt.show()


I am working on the file "0.23/_downloads/066ec12646ce0d0818ad9b78bc602218/fdr_stats_evoked.ipynb".
The first task is:
Read epochs for the channel of interest
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=False, eog=True, include=include,
                       exclude='bads')
event_id = 1
reject = dict(grad=4000e-13, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject)
X = epochs.get_data()  # as 3D matrix
X = X[:, 0, :]  # take only one channel to get a 2D array


I am working on the file "0.23/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
And finally eLORETA:
Can you write Python code for it?

stc = abs(apply_inverse(evoked, inv, lambda2, 'eLORETA', verbose=True))
brain = stc.plot(figure=4, **kwargs)
brain.add_text(0.1, 0.9, 'eLORETA', 'title', font_size=14)
del inv


stc = apply_inverse(evoked, inv, lambda2, 'eLORETA', verbose=True,
                    method_params=dict(eps=1e-4))  # larger eps just for speed
brain = stc.plot(figure=8, **kwargs)
brain.add_text(0.1, 0.9, 'eLORETA', 'title', font_size=14)


I am working on the file "0.23/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
Computing various MNE solutions
This example shows example fixed- and free-orientation source localizations
produced by MNE, dSPM, sLORETA, and eLORETA.
Can you write Python code for it?

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

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

print(__doc__)

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

# Read data (just MEG here for speed, though we could use MEG+EEG)
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname_evoked, condition='Left Auditory',
                          baseline=(None, 0))
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fwd = mne.read_forward_solution(fname_fwd)
cov = mne.read_cov(fname_cov)
# crop for speed in these examples
evoked.crop(0.05, 0.15)


I am working on the file "0.23/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
Free orientation
Now let's not constrain the orientation of the dipoles at all by creating
a free-orientation inverse.
Can you write Python code for it?

inv = make_inverse_operator(evoked.info, fwd, cov, loose=1., depth=0.8,
                            verbose=True)
del fwd


I am working on the file "0.23/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
Next let's use the default noise normalization, dSPM:
Can you write Python code for it?

stc = abs(apply_inverse(evoked, inv, lambda2, 'dSPM', verbose=True))
brain = stc.plot(figure=2, **kwargs)
brain.add_text(0.1, 0.9, 'dSPM', 'title', font_size=14)


stc = apply_inverse(evoked, inv, lambda2, 'dSPM', verbose=True)
brain = stc.plot(figure=6, **kwargs)
brain.add_text(0.1, 0.9, 'dSPM', 'title', font_size=14)


I am working on the file "0.23/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
sLORETA:
Can you write Python code for it?

stc = apply_inverse(evoked, inv, lambda2, 'sLORETA', verbose=True)
brain = stc.plot(figure=7, **kwargs)
brain.add_text(0.1, 0.9, 'sLORETA', 'title', font_size=14)


I am working on the file "0.23/_downloads/0a1bad60270bfbdeeea274fcca0015d2/multidict_reweighted_tfmxne.ipynb".
The first task is:
Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
The iterative reweighted TF-MxNE solver is a distributed inverse method
based on the TF-MxNE solver, which promotes focal (sparse) sources
:footcite:StrohmeierEtAl2015. The benefits of this approach are that:

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

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

import os.path as op

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

print(__doc__)


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

stc = make_stc_from_dipoles(dipoles, forward['src'])
plot_sparse_source_estimates(
    forward['src'], stc, bgcolor=(1, 1, 1), opacity=0.1,
    fig_name=f"irTF-MxNE (cond {evoked.comment})")


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

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

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


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

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


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

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

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


I am working on the file "0.23/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
:class:Montage <mne.channels.DigMontage> objects have a
:meth:~mne.channels.DigMontage.plot method for visualization of the sensor
locations in 3D; 2D projections are also possible by passing
kind='topomap':
Can you write Python code for it?

fig = ten_twenty_montage.plot(kind='3d')
fig.gca().view_init(azim=70, elev=15)
ten_twenty_montage.plot(kind='topomap', show_names=False)


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

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


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

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


I am working on the file "0.23/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
By default a sphere  with an origin in (0, 0, 0) x, y, z coordinates and
radius of 0.095 meters (9.5 cm) is used. You can use a different sphere
radius by passing a single value to sphere argument in any function that
plots channels in 2d (like :meth:~mne.channels.DigMontage.plot that we use
here, but also for example :func:mne.viz.plot_topomap):
Can you write Python code for it?


I am working on the file "0.23/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
If you have previous EEGLAB experience you may prefer its convention to
represent 10-20 head circumference with the head circle. To get EEGLAB-like
channel layout you would have to move the sphere origin a few centimeters
up on the z dimension:
Can you write Python code for it?

biosemi_montage.plot(sphere=(0, 0, 0.035, 0.094))


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


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

Note

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

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

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


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

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


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

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


I am working on the file "0.23/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
To control not only radius, but also the sphere origin, pass a
(x, y, z, radius) tuple to sphere argument:
Can you write Python code for it?

biosemi_montage.plot(show_names=False, sphere=(0.03, 0.02, 0.01, 0.075))


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

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


I am working on the file "0.23/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
From here on, standard inverse imaging methods can be used!
Infant MRI surrogates
We don't have a sample infant dataset for MNE, so let's fake a 10-20 one:
Can you write Python code for it?

ch_names = \
    'Fz Cz Pz Oz Fp1 Fp2 F3 F4 F7 F8 C3 C4 T7 T8 P3 P4 P7 P8 O1 O2'.split()
data = np.random.RandomState(0).randn(len(ch_names), 1000)
info = mne.create_info(ch_names, 1000., 'eeg')
raw = mne.io.RawArray(data, info)


I am working on the file "0.23/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
Get an infant MRI template
To use an infant head model for M/EEG data, you can use
:func:mne.datasets.fetch_infant_template to download an infant template:
Can you write Python code for it?

subject = mne.datasets.fetch_infant_template('6mo', subjects_dir, verbose=True)


I am working on the file "0.23/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
It comes with several helpful built-in files, including a 10-20 montage
in the MRI coordinate frame, which can be used to compute the
MRI<->head transform trans:
Can you write Python code for it?

fname_1020 = op.join(subjects_dir, subject, 'montages', '10-20-montage.fif')
mon = mne.channels.read_dig_fif(fname_1020)
mon.rename_channels(
    {f'EEG{ii:03d}': ch_name for ii, ch_name in enumerate(ch_names, 1)})
trans = mne.channels.compute_native_head_t(mon)
raw.set_montage(mon)
print(trans)


I am working on the file "0.23/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
Load the data
We use here EEG data from the BCI dataset.

Note

See `plot_montage` to view all the standard EEG montages
          available in MNE-Python.

Can you write Python code for it?

raw_fname, = eegbci.load_data(subject=1, runs=[6])
raw = mne.io.read_raw_edf(raw_fname, preload=True)

# Clean channel names to be able to use a standard 1005 montage
new_names = dict(
    (ch_name,
     ch_name.rstrip('.').upper().replace('Z', 'z').replace('FP', 'Fp'))
    for ch_name in raw.ch_names)
raw.rename_channels(new_names)

# Read and set the EEG electrode locations
montage = mne.channels.make_standard_montage('standard_1005')
raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

# Check that the locations of EEG electrodes is correct with respect to MRI
mne.viz.plot_alignment(
    raw.info, src=src, eeg=['original', 'projected'], trans=trans,
    show_axes=True, mri_fiducials=True, dig='fiducials')


I am working on the file "0.23/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
You can ensure everything is as expected by plotting the result:
Can you write Python code for it?

fig = mne.viz.plot_alignment(
    raw.info, subject=subject, subjects_dir=subjects_dir, trans=trans,
    src=src, bem=bem, coord_frame='mri', mri_fiducials=True, show_axes=True,
    surfaces=('white', 'outer_skin', 'inner_skull', 'outer_skull'))
mne.viz.set_3d_view(fig, 25, 70, focalpoint=[0, -0.005, 0.01])


I am working on the file "0.23/_downloads/13f9133d0e7c13dded3c5dd2cf828dd3/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.23/_downloads/13f9133d0e7c13dded3c5dd2cf828dd3/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.23/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Define parameters
Can you write Python code for it?

fname = data_path() + '/SubjectCMC.ds'

# Prepare data
raw = mne.io.read_raw_ctf(fname)
raw.crop(50., 110.).load_data()  # crop for memory purposes
raw.resample(sfreq=250)

raw.pick_types(meg=True, eeg=False, ref_meg=False)

freqs_sig = 9, 12
freqs_noise = 8, 13

ssd = SSD(info=raw.info,
          reg='oas',
          sort_by_spectral_ratio=False,  # False for purpose of example.
          filt_params_signal=dict(l_freq=freqs_sig[0], h_freq=freqs_sig[1],
                                  l_trans_bandwidth=1, h_trans_bandwidth=1),
          filt_params_noise=dict(l_freq=freqs_noise[0], h_freq=freqs_noise[1],
                                 l_trans_bandwidth=1, h_trans_bandwidth=1))
ssd.fit(X=raw.get_data())


I am working on the file "0.23/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Let's also look at the power spectrum of that source and compare it to
to the power spectrum of the source with lowest SNR.
Can you write Python code for it?

below50 = freqs < 50
# for highlighting the freq. band of interest
bandfilt = (freqs_sig[0] <= freqs) & (freqs <= freqs_sig[1])
fig, ax = plt.subplots(1)
ax.loglog(freqs[below50], psd[0, below50], label='max SNR')
ax.loglog(freqs[below50], psd[-1, below50], label='min SNR')
ax.loglog(freqs[below50], psd[:, below50].mean(axis=0), label='mean')
ax.fill_between(freqs[bandfilt], 0, 10000, color='green', alpha=0.15)
ax.set_xlabel('log(frequency)')
ax.set_ylabel('log(power)')
ax.legend()

# We can clearly see that the selected component enjoys an SNR that is
# way above the average power spectrum.


I am working on the file "0.23/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Let's investigate spatial filter with max power ratio.
We will first inspect the topographies.
According to Nikulin et al. 2011 this is done by either inverting the filters
(W^{-1}) or by multiplying the noise cov with the filters Eq. (22) (C_n W)^t.
We rely on the inversion approach here.
Can you write Python code for it?

pattern = mne.EvokedArray(data=ssd.patterns_[:4].T,
                          info=ssd.info)
pattern.plot_topomap(units=dict(mag='A.U.'), time_format='')

# The topographies suggest that we picked up a parietal alpha generator.

# Transform
ssd_sources = ssd.transform(X=raw.get_data())

# Get psd of SSD-filtered signals.
psd, freqs = mne.time_frequency.psd_array_welch(
    ssd_sources, sfreq=raw.info['sfreq'], n_fft=4096)

# Get spec_ratio information (already sorted).
# Note that this is not necessary if sort_by_spectral_ratio=True (default).
spec_ratio, sorter = ssd.get_spectral_ratio(ssd_sources)

# Plot spectral ratio (see Eq. 24 in Nikulin 2011).
fig, ax = plt.subplots(1)
ax.plot(spec_ratio, color='black')
ax.plot(spec_ratio[sorter], color='orange', label='sorted eigenvalues')
ax.set_xlabel("Eigenvalue Index")
ax.set_ylabel(r"Spectral Ratio $\frac{P_f}{P_{sf}}$")
ax.legend()
ax.axhline(1, linestyle='--')

# We can see that the initial sorting based on the eigenvalues
# was already quite good. However, when using few components only
# the sorting might make a difference.


I am working on the file "0.23/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
Also look at the power spectral densities:
Can you write Python code for it?


I am working on the file "0.23/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
CSD can also be computed on Evoked (averaged) data.
Here we epoch and average the data so we can demonstrate that.
Can you write Python code for it?

event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
            'visual/right': 4, 'smiley': 5, 'button': 32}
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=-0.2, tmax=.5,
                    preload=True)
evoked = epochs['auditory'].average()


I am working on the file "0.23/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
Load sample subject data
Can you write Python code for it?

raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
raw = raw.pick_types(meg=False, eeg=True, eog=True, ecg=True, stim=True,
                     exclude=raw.info['bads']).load_data()
events = mne.find_events(raw)
raw.set_eeg_reference(projection=True).apply_proj()


I am working on the file "0.23/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
Plot the raw data and CSD-transformed raw data:
Can you write Python code for it?

raw_csd = mne.preprocessing.compute_current_source_density(raw)
raw.plot()
raw_csd.plot()


I am working on the file "0.23/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
Transform EEG data using current source density (CSD)
This script shows an example of how to use CSD
:footcite:PerrinEtAl1987,PerrinEtAl1989,Cohen2014,KayserTenke2015.
CSD takes the spatial Laplacian of the sensor signal (derivative in both
x and y). It does what a planar gradiometer does in MEG. Computing these
spatial derivatives reduces point spread. CSD transformed data have a sharper
or more distinct topography, reducing the negative impact of volume conduction.
Can you write Python code for it?

# Authors: Alex Rockhill <aprockhill@mailbox.org>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
An advantage of using this numerical representation of an IC to capture a
particular artifact pattern is that it can be saved and used as a template
for future template-matching tasks using ~mne.preprocessing.corrmap
without having to load or recompute the ICA solution that yielded the
template originally. Put another way, when the template is a NumPy array, the
~mne.preprocessing.ICA object containing the template does not need
to be in the list of ICAs provided to ~mne.preprocessing.corrmap.
.. LINKS
https://en.wikipedia.org/wiki/Signal_separation
   https://en.wikipedia.org/wiki/Independence_(probability_theory)
Compute ICA components on Epochs
ICA is now fit to epoched MEG data instead of the raw data.
We assume that the non-stationary EOG artifacts have already been removed.
The sources matching the ECG are automatically found and displayed.

Note

This example is computationally intensive, so it might take a few minutes
    to complete.

Read and preprocess the data. Preprocessing consists of:

MEG channel selection
1-30 Hz band-pass filter
epoching -0.2 to 0.5 seconds with respect to events
rejection based on peak-to-peak amplitude

Note that we don't baseline correct the epochs here – we'll do this after
cleaning with ICA is completed. Baseline correction before ICA is not
recommended by the MNE-Python developers, as it doesn't guarantee optimal
results.
Can you write Python code for it?

filt_raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True).load_data()
filt_raw.filter(1, 30, fir_design='firwin')

# peak-to-peak amplitude rejection parameters
reject = dict(grad=4000e-13, mag=4e-12)
# create longer and more epochs for more artifact exposure
events = mne.find_events(filt_raw, stim_channel='STI 014')
# don't baseline correct epochs
epochs = mne.Epochs(filt_raw, events, event_id=None, tmin=-0.2, tmax=0.5,
                    reject=reject, baseline=None)


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Much better! Now we've captured both ICs that are reflecting the heartbeat
artifact (and as a result, we got two diagnostic plots: one for each IC that
reflects the heartbeat). This demonstrates the value of checking the results
of automated approaches like ~mne.preprocessing.ICA.find_bads_ecg
before accepting them.
Can you write Python code for it?

# clean up memory before moving on
del raw, ica, new_ica


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Note that above we used ~mne.preprocessing.ICA.plot_sources on both
the original ~mne.io.Raw instance and also on an
~mne.Evoked instance of the extracted EOG artifacts. This can be
another way to confirm that ~mne.preprocessing.ICA.find_bads_eog has
identified the correct components.
Using a simulated channel to select ICA components
If you don't have an EOG channel,
~mne.preprocessing.ICA.find_bads_eog has a ch_name parameter that
you can use as a proxy for EOG. You can use a single channel, or create a
bipolar reference from frontal EEG sensors and use that as virtual EOG
channel. This carries a risk however: you must hope that the frontal EEG
channels only reflect EOG and not brain dynamics in the prefrontal cortex (or
you must not care about those prefrontal signals).
For ECG, it is easier: ~mne.preprocessing.ICA.find_bads_ecg can use
cross-channel averaging of magnetometer or gradiometer channels to construct
a virtual ECG channel, so if you have MEG channels it is usually not
necessary to pass a specific channel name.
~mne.preprocessing.ICA.find_bads_ecg also has two options for its
method parameter: 'ctps' (cross-trial phase statistics
:footcite:DammersEtAl2008) and
'correlation' (Pearson correlation between data and ECG channel).
Can you write Python code for it?

ica.exclude = []
# find which ICs match the ECG pattern
ecg_indices, ecg_scores = ica.find_bads_ecg(raw, method='correlation',
                                            threshold='auto')
ica.exclude = ecg_indices

# barplot of ICA component "ECG match" scores
ica.plot_scores(ecg_scores)

# plot diagnostics
ica.plot_properties(raw, picks=ecg_indices)

# plot ICs applied to raw data, with ECG matches highlighted
ica.plot_sources(raw, show_scrollbars=False)

# plot ICs applied to the averaged ECG epochs, with ECG matches highlighted
ica.plot_sources(ecg_evoked)


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Notice that the first subject has 3 different labels for the IC at index 0:
"eog/0/Fpz", "eog", and "blink". The first two were added by
~mne.preprocessing.ICA.find_bads_eog; the "blink" label was added by
the last call to ~mne.preprocessing.corrmap. Notice also that each
subject has at least one IC index labelled "blink", and subject 3 has two
components (0 and 2) labelled "blink" (consistent with the plot of IC sources
above). The labels_ attribute of ~mne.preprocessing.ICA objects
can also be manually edited to annotate the ICs with custom labels. They also
come in handy when plotting:
Can you write Python code for it?

icas[3].plot_components(picks=icas[3].labels_['blink'])
icas[3].exclude = icas[3].labels_['blink']
icas[3].plot_sources(raws[3], show_scrollbars=False)


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Now let's run ~mne.preprocessing.corrmap:
Can you write Python code for it?

# use the first subject as template; use Fpz as proxy for EOG
raw = raws[0]
ica = icas[0]
eog_inds, eog_scores = ica.find_bads_eog(raw, ch_name='Fpz')
corrmap(icas, template=(0, eog_inds[0]))


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Now we get the message At least 1 IC detected for each subject (which is
good). At this point we'll re-run ~mne.preprocessing.corrmap with
parameters label='blink', plot=False to label the ICs from each subject
that capture the blink artifacts (without plotting them again).
Can you write Python code for it?

corrmap(icas, template=(0, eog_inds[0]), threshold=0.9, label='blink',
        plot=False)
print([ica.labels_ for ica in icas])


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Now we'll do the same for the heartbeat artifacts, using
~mne.preprocessing.create_ecg_epochs:
Can you write Python code for it?

ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.apply_baseline(baseline=(None, -0.2))
ecg_evoked.plot_joint()


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Plot the properties of the ECG components:
Can you write Python code for it?


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Repairing artifacts with ICA
This tutorial covers the basics of independent components analysis (ICA) and
shows how ICA can be used for artifact repair; an extended example illustrates
repair of ocular and heartbeat artifacts. For conceptual background on ICA, see
this scikit-learn tutorial
<sphx_glr_auto_examples_decomposition_plot_ica_blind_source_separation.py>.
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>. Because ICA can be computationally
intense, we'll also crop the data to 60 seconds; and to save ourselves from
repeatedly typing mne.preprocessing we'll directly import a few functions
and classes from that submodule:
Can you write Python code for it?

import os
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
                               corrmap)

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


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Some optional parameters that we could have passed to the
~mne.preprocessing.ICA.fit method include decim (to use only
every Nth sample in computing the ICs, which can yield a considerable
speed-up) and reject (for providing a rejection dictionary for maximum
acceptable peak-to-peak amplitudes for each channel type, just like we used
when creating epoched data in the tut-overview tutorial).
Now we can examine the ICs to see what they captured.
~mne.preprocessing.ICA.plot_sources will show the time series of the
ICs. Note that in our call to ~mne.preprocessing.ICA.plot_sources we
can use the original, unfiltered ~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
The first figure shows the template map, while the second figure shows all
the maps that were considered a "match" for the template (including the
template itself). There were only three matches from the four subjects;
notice the output message No maps selected for subject(s) 1, consider a
more liberal threshold.  By default the threshold is set automatically by
trying several values; here it may have chosen a threshold that is too high.
Let's take a look at the ICA sources for each subject:
Can you write Python code for it?

for index, (ica, raw) in enumerate(zip(icas, raws)):
    fig = ica.plot_sources(raw, show_scrollbars=False)
    fig.subplots_adjust(top=0.9)  # make space for title
    fig.suptitle('Subject {}'.format(index))


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
The last of these plots is especially useful: it shows us that the heartbeat
artifact is coming through on two ICs, and we've only caught one of them.
In fact, if we look closely at the output of
~mne.preprocessing.ICA.plot_sources (online, you can right-click →
"view image" to zoom in), it looks like ICA014 has a weak periodic
component that is in-phase with ICA001. It might be worthwhile to re-run
the ICA with more components to see if that second heartbeat artifact
resolves out a little better:
Can you write Python code for it?

# refit the ICA with 30 components this time
new_ica = ICA(n_components=30, max_iter='auto', random_state=97)
new_ica.fit(filt_raw)

# find which ICs match the ECG pattern
ecg_indices, ecg_scores = new_ica.find_bads_ecg(raw, method='correlation',
                                                threshold='auto')
new_ica.exclude = ecg_indices

# barplot of ICA component "ECG match" scores
new_ica.plot_scores(ecg_scores)

# plot diagnostics
new_ica.plot_properties(raw, picks=ecg_indices)

# plot ICs applied to raw data, with ECG matches highlighted
new_ica.plot_sources(raw, show_scrollbars=False)

# plot ICs applied to the averaged ECG epochs, with ECG matches highlighted
new_ica.plot_sources(ecg_evoked)


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
We can also plot some diagnostics of each IC using
~mne.preprocessing.ICA.plot_properties:
Can you write Python code for it?


I am working on the file "0.23/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
We can get a summary of how the ocular artifact manifests across each channel
type using ~mne.preprocessing.create_eog_epochs like we did in the
tut-artifact-overview tutorial:
Can you write Python code for it?

eog_evoked = create_eog_epochs(raw).average()
eog_evoked.apply_baseline(baseline=(None, -0.2))
eog_evoked.plot_joint()


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:

Warning

Forward computation can remove vertices that are too close to (or outside)
   the inner skull surface. For example, here we have gone from 516 to 474
   vertices in use. For many functions, such as
   :func:`mne.compute_source_morph`, it is important to pass ``fwd['src']``
   or ``inv['src']`` so that this removal is adequately accounted for.

Can you write Python code for it?

print(f'Before: {src}')
print(f'After:  {fwd["src"]}')


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
Compute Source Space
The source space defines the position and orientation of the candidate source
locations. There are two types of source spaces:

surface-based source space when the candidates are confined to a
  surface.

volumetric or discrete source space when the candidates are discrete,
  arbitrarily located source points bounded by the surface.

Surface-based source space is computed using
:func:mne.setup_source_space, while volumetric source space is computed
using :func:mne.setup_volume_source_space.
We will now compute a surface-based source space with an 'oct4'
resolution. See setting_up_source_space for details on source space
definition and spacing parameter.

Warning

``'oct4'`` is used here just for speed, for real analyses the recommended
    spacing is ``'oct6'``.

Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct4', add_dist='patch',
                             subjects_dir=subjects_dir)
print(src)


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
Compute forward solution
We can now compute the forward solution.
To reduce computation we'll just compute a single layer BEM (just inner
skull) that can then be used for MEG (not EEG).
We specify if we want a one-layer or a three-layer BEM using the
conductivity parameter.
The BEM solution requires a BEM model which describes the geometry
of the head the conductivities of the different tissues.
Can you write Python code for it?

conductivity = (0.3,)  # for single layer
# conductivity = (0.3, 0.006, 0.3)  # for three layers
model = mne.make_bem_model(subject='sample', ico=4,
                           conductivity=conductivity,
                           subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
Head model and forward computation
The aim of this tutorial is to be a getting started for forward computation.
For more extensive details and presentation of the general
concepts for forward modeling, see ch_forward.
Can you write Python code for it?

import os.path as op
import mne
from mne.datasets import sample
data_path = sample.data_path()

# the raw file containing the channel location + types
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
# The paths to Freesurfer reconstructions
subjects_dir = data_path + '/subjects'
subject = 'sample'


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
Note that the :term:BEM does not involve any use of the trans file. The BEM
only depends on the head geometry and conductivities.
It is therefore independent from the MEG data and the head position.
Let's now compute the forward operator, commonly referred to as the
gain or leadfield matrix.
See :func:mne.make_forward_solution for details on the meaning of each
parameter.
Can you write Python code for it?

fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=bem,
                                meg=True, eeg=False, mindist=5.0, n_jobs=1,
                                verbose=True)
print(fwd)


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
To compute a volume based source space defined with a grid of candidate
dipoles inside the brain (requires the :term:BEM surfaces) you can use the
following.
Can you write Python code for it?

surface = op.join(subjects_dir, subject, 'bem', 'inner_skull.surf')
vol_src = mne.setup_volume_source_space(subject, subjects_dir=subjects_dir,
                                        surface=surface)
print(vol_src)

mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
                 brain_surfaces='white', src=vol_src, orientation='coronal')


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
To extract the numpy array containing the forward operator corresponding to
the source space fwd['src'] with cortical orientation constraint
we can use the following:
Can you write Python code for it?

fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                         use_cps=True)
leadfield = fwd_fixed['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)


I am working on the file "0.23/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
We can explore the content of fwd to access the numpy array that contains
the gain matrix.
Can you write Python code for it?

leadfield = fwd['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)


I am working on the file "0.23/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Back in Python, you can read the fixed .obj files and save them as
FreeSurfer .surf files. For the :func:mne.make_bem_model function to find
them, they need to be saved using their original names in the surf
folder, e.g. bem/inner_skull.surf. Be sure to first backup the original
surfaces in case you make a mistake!
Can you write Python code for it?

# Read the fixed surface
coords, faces = mne.read_surface(op.join(conv_dir, 'inner_skull_fixed.obj'))

# Backup the original surface
shutil.copy(op.join(bem_dir, 'inner_skull.surf'),
            op.join(bem_dir, 'inner_skull_orig.surf'))

# Overwrite the original surface with the fixed version
# In real study you should provide the correct metadata using ``volume_info=``
# This could be accomplished for example with:
#
# _, _, vol_info = mne.read_surface(op.join(bem_dir, 'inner_skull.surf'),
#                                   read_metadata=True)
# mne.write_surface(op.join(bem_dir, 'inner_skull.surf'), coords, faces,
#                   volume_info=vol_info, overwrite=True)


I am working on the file "0.23/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Editing BEM surfaces in Blender
Sometimes when creating a BEM model the surfaces need manual correction because
of a series of problems that can arise (e.g. intersection between surfaces).
Here, we will see how this can be achieved by exporting the surfaces to the 3D
modeling program Blender <https://blender.org>_, editing them, and
re-importing them.
This tutorial is based on https://github.com/ezemikulan/blender_freesurfer by
Ezequiel Mikulan.
   :depth: 2
Can you write Python code for it?

# Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
#          Ezequiel Mikulan <e.mikulan@gmail.com>
#          Manorama Kadwani <manorama.kadwani@gmail.com>
#
# License: BSD (3-clause)

import os
import os.path as op
import shutil
import mne

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, 'sample', 'bem', 'flash')


I am working on the file "0.23/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Exporting surfaces to Blender
In this tutorial, we are working with the MNE-Sample set, for which the
surfaces have no issues. To demonstrate how to fix problematic surfaces, we
are going to manually place one of the inner-skull vertices outside the
outer-skill mesh.
We then convert the surfaces to .obj
<https://en.wikipedia.org/wiki/Wavefront_.obj_file>_ files and create a new
folder called conv inside the FreeSurfer subject folder to keep them in.
Can you write Python code for it?

# Put the converted surfaces in a separate 'conv' folder
conv_dir = op.join(subjects_dir, 'sample', 'conv')
os.makedirs(conv_dir, exist_ok=True)

# Load the inner skull surface and create a problem
# The metadata is empty in this example. In real study, we want to write the
# original metadata to the fixed surface file. Set read_metadata=True to do so.
coords, faces = mne.read_surface(op.join(bem_dir, 'inner_skull.surf'))
coords[0] *= 1.1  # Move the first vertex outside the skull

# Write the inner skull surface as an .obj file that can be imported by
# Blender.
mne.write_surface(op.join(conv_dir, 'inner_skull.obj'), coords, faces,
                  overwrite=True)

# Also convert the outer skull surface.
coords, faces = mne.read_surface(op.join(bem_dir, 'outer_skull.surf'))
mne.write_surface(op.join(conv_dir, 'outer_skull.obj'), coords, faces,
                  overwrite=True)


I am working on the file "0.23/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
High-resolution head
We use :func:mne.read_bem_surfaces to read the head surface files. After
editing, we again output the head file with :func:mne.write_head_bem.
Here we use -head.fif for speed.
Can you write Python code for it?

# If ``-head-dense.fif`` does not exist, you need to run
# ``mne make_scalp_surfaces`` first.
# [0] because a list of surfaces is returned
surf = mne.read_bem_surfaces(op.join(head_dir, 'sample-head.fif'))[0]

# For consistency only
coords = surf['rr']
faces = surf['tris']

# Write the head as an .obj file for editing
mne.write_surface(op.join(conv_dir, 'sample-head.obj'),
                  coords, faces, overwrite=True)

# Usually here you would go and edit your meshes.
#
# Here we just use the same surface as if it were fixed
# Read in the .obj file
coords, faces = mne.read_surface(op.join(conv_dir, 'sample-head.obj'))

# Remember to backup the original head file in advance!
# Overwrite the original head file
#
# mne.write_head_bem(op.join(head_dir, 'sample-head.fif'), coords, faces,
#                    overwrite=True)


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
Also by default, :func:~mne.set_config will set values in both the JSON
file and in :data:os.environ; to set a config variable only in the JSON
file use set_env=False. Here we'll use :func:print statement to confirm
that an environment variable is being created and deleted (we could have used
the Python assert statement <assert> instead, but it doesn't print any
output when it succeeds so it's a little less obvious):
Can you write Python code for it?

mne.set_config('foo', 'bar', set_env=False)
print('foo' in os.environ.keys())
mne.set_config('foo', 'bar')
print('foo' in os.environ.keys())
mne.set_config('foo', None)  # unsetting a key deletes var from environment
print('foo' in os.environ.keys())


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/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.
We begin by importing the necessary Python modules:
Can you write Python code for it?


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
If you're unsure whether a config variable has been set, there is a
convenient way to check it and provide a fallback in case it doesn't exist:
:func:~mne.get_config has a default parameter.
Can you write Python code for it?


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
It is possible to add config variables that are not part of the recognized
list, by passing any arbitrary key to :func:~mne.set_config. This will
yield a warning, however, which is a nice check in cases where you meant to
set a valid key but simply misspelled it:
Can you write Python code for it?


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/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.23/_downloads/1c191178a3423d922910711c4b574821/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.23/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
The logging levels that can be set as config variables are debug,
info, warning, error, and critical. Around 90% of the log
messages in MNE-Python are info messages, so for most users the choice is
between info (tell me what is happening) and warning (tell me only if
something worrisome happens). The debug logging level is intended for
MNE-Python developers.
In an earlier section <config-get-set> we saw how
:func:mne.set_config is used to change the logging level for the current
Python session and all future sessions. To change the logging level only for
the current Python session, you can use :func:mne.set_log_level instead.
The :func:~mne.set_log_level function takes the same five string options
that are used for the MNE_LOGGING_LEVEL config variable; additionally, it
can accept :class:int or :class:bool values that are equivalent to those
strings. The equivalencies are given in this table:
+----------+---------+---------+
| String   | Integer | Boolean |
+==========+=========+=========+
| DEBUG    | 10      |         |
+----------+---------+---------+
| INFO     | 20      | True    |
+----------+---------+---------+
| WARNING  | 30      | False   |
+----------+---------+---------+
| ERROR    | 40      |         |
+----------+---------+---------+
| CRITICAL | 50      |         |
+----------+---------+---------+
With many MNE-Python functions it is possible to change the logging level
temporarily for just that function call, by using the verbose parameter.
To illustrate this, we'll load some sample data with different logging levels
set. First, with log level warning:
Can you write Python code for it?

kit_data_path = os.path.join(os.path.abspath(os.path.dirname(mne.__file__)),
                             'io', 'kit', 'tests', 'data', 'test.sqd')
raw = mne.io.read_raw_kit(kit_data_path, verbose='warning')


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/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.23/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
There are also two convenience modes of :func:~mne.get_config. The first
will return a :class:dict containing all config variables (and their
values) that have been set on your system; this is done by passing
key=None (which is the default, so it can be omitted):
Can you write Python code for it?

print(mne.get_config())  # same as mne.get_config(key=None)


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
This time, we got a few messages about extracting information from the file,
converting that information into the MNE-Python :class:~mne.Info format,
etc. Finally, if we request debug-level information, we get even more
detail:
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/1c191178a3423d922910711c4b574821/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.23/_downloads/1f2e88712289c5315357ca3b8efc1bbb/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.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.23/_downloads/1f2e88712289c5315357ca3b8efc1bbb/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 = mne.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 = 4., 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.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Apply morph to VolSourceEstimate
The morph can be applied to the source estimate data, by giving it as the
first argument to the :meth:morph.apply() <mne.SourceMorph.apply> method.

Note

Volumetric morphing is much slower than surface morphing because the
     volume for each time point is individually resampled and SDR morphed.
     The :meth:`mne.SourceMorph.compute_vol_morph_mat` method can be used
     to compute an equivalent sparse matrix representation by computing the
     transformation for each source point individually. This generally takes
     a few minutes to compute, but can be
     :meth:`saved <mne.SourceMorph.save>` to disk and be reused. The
     resulting sparse matrix operation is very fast (about 400× faster) to
     :meth:`apply <mne.SourceMorph.apply>`. This approach is more efficient
     when the number of time points to be morphed exceeds the number of
     source space points, which is generally in the thousands. This can
     easily occur when morphing many time points and multiple conditions.

Can you write Python code for it?


I am working on the file "0.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Compute example data. For reference see ex-inverse-volume.
Load data:
Can you write Python code for it?

evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)

# Apply inverse operator
stc = apply_inverse(evoked, inverse_operator, 1.0 / 3.0 ** 2, "dSPM")

# To save time
stc.crop(0.09, 0.09)


I am working on the file "0.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Convert morphed VolSourceEstimate into NIfTI
We can convert our morphed source estimate into a NIfTI volume using
:meth:morph.apply(..., output='nifti1') <mne.SourceMorph.apply>.
Can you write Python code for it?

# Create mri-resolution volume of results
img_fsaverage = morph.apply(stc, mri_resolution=2, output='nifti1')


I am working on the file "0.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Get a SourceMorph object for VolSourceEstimate
subject_from can typically be inferred from
:class:src <mne.SourceSpaces>,
and subject_to is  set to 'fsaverage' by default. subjects_dir can be
None when set in the environment. In that case SourceMorph can be initialized
taking src as only argument. See :class:mne.SourceMorph for more
details.
The default parameter setting for zooms will cause the reference volumes
to be resliced before computing the transform. A value of '5' would cause
the function to reslice to an isotropic voxel size of 5 mm. The higher this
value the less accurate but faster the computation will be.
The recommended way to use this is to morph to a specific destination source
space so that different subject_from morphs will go to the same space.`
A standard usage for volumetric data reads:
Can you write Python code for it?

src_fs = mne.read_source_spaces(fname_src_fsaverage)
morph = mne.compute_source_morph(
    inverse_operator['src'], subject_from='sample', subjects_dir=subjects_dir,
    niter_affine=[10, 10, 5], niter_sdr=[10, 10, 5],  # just for speed
    src_to=src_fs, verbose=True)


I am working on the file "0.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Morph volumetric source estimate
This example demonstrates how to morph an individual subject's
:class:mne.VolSourceEstimate to a common reference space. We achieve this
using :class:mne.SourceMorph. Data will be morphed based on
an affine transformation and a nonlinear registration method
known as Symmetric Diffeomorphic Registration (SDR) by
:footcite:AvantsEtAl2008.
Transformation is estimated from the subject's anatomical T1 weighted MRI
(brain) to FreeSurfer's 'fsaverage' T1 weighted MRI (brain)
<https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage>__.
Afterwards the transformation will be applied to the volumetric source
estimate. The result will be plotted, showing the fsaverage T1 weighted
anatomical MRI, overlaid with the morphed volumetric source estimate.
Can you write Python code for it?

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

import nibabel as nib
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.minimum_norm import apply_inverse, read_inverse_operator
from nilearn.plotting import plot_glass_brain

print(__doc__)


I am working on the file "0.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Plot results
Can you write Python code for it?

# Load fsaverage anatomical image
t1_fsaverage = nib.load(fname_t1_fsaverage)

# Plot glass brain (change to plot_anat to display an overlaid anatomical T1)
display = plot_glass_brain(t1_fsaverage,
                           title='subject results to fsaverage',
                           draw_cross=False,
                           annotate=True)

# Add functional data as overlay
display.add_overlay(img_fsaverage, alpha=0.75)


I am working on the file "0.23/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Setup paths
Can you write Python code for it?

sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')

fname_evoked = os.path.join(sample_dir, 'sample_audvis-ave.fif')
fname_inv = os.path.join(sample_dir, 'sample_audvis-meg-vol-7-meg-inv.fif')

fname_t1_fsaverage = os.path.join(subjects_dir, 'fsaverage', 'mri',
                                  'brain.mgz')
fetch_fsaverage(subjects_dir)  # ensure fsaverage src exists
fname_src_fsaverage = subjects_dir + '/fsaverage/bem/fsaverage-vol-5-src.fif'


I am working on the file "0.23/_downloads/2455121b46e43615a45b660a36d0ad93/30_epochs_metadata.ipynb".
The first task is:
Although there's no obvious relationship in this case, such analyses may be
useful for metadata variables that more directly index the time course of
stimulus processing (such as reaction time).
Adding metadata to an Epochs object
You can add a metadata :class:~pandas.DataFrame to any
~mne.Epochs object (or replace existing metadata) simply by
assigning to the :attr:~mne.Epochs.metadata attribute:
Can you write Python code for it?

new_metadata = pd.DataFrame(data=['foo'] * len(epochs), columns=['bar'],
                            index=range(len(epochs)))
epochs.metadata = new_metadata
epochs.metadata.head()


I am working on the file "0.23/_downloads/2455121b46e43615a45b660a36d0ad93/30_epochs_metadata.ipynb".
The first task is:
Notice that in this dataset, each "condition" (A.K.A., each word) occurs only
once, whereas with the sample-dataset dataset each condition (e.g.,
"auditory/left", "visual/right", etc) occurred dozens of times. This makes
the Pandas querying methods especially useful when you want to aggregate
epochs that have different condition names but that share similar stimulus
properties. For example, here we group epochs based on the number of letters
in the stimulus word, and compare the average signal at electrode Pz for
each group:
Can you write Python code for it?

evokeds = dict()
query = 'NumberOfLetters == {}'
for n_letters in epochs.metadata['NumberOfLetters'].unique():
    evokeds[str(n_letters)] = epochs[query.format(n_letters)].average()

mne.viz.plot_compare_evokeds(evokeds, cmap=('word length', 'viridis'),
                             picks='Pz')


I am working on the file "0.23/_downloads/2455121b46e43615a45b660a36d0ad93/30_epochs_metadata.ipynb".
The first task is:
Viewing Epochs metadata
.. sidebar:: Restrictions on metadata DataFrames
Metadata dataframes are less flexible than typical
   :class:Pandas DataFrames <pandas.DataFrame>. For example, the allowed
   data types are restricted to strings, floats, integers, or booleans;
   and the row labels are always integers corresponding to epoch numbers.
   Other capabilities of :class:DataFrames <pandas.DataFrame> such as
   :class:hierarchical indexing <pandas.MultiIndex> are possible while the
   ~mne.Epochs object is in memory, but will not survive saving and
   reloading the ~mne.Epochs object to/from disk.
The metadata attached to ~mne.Epochs objects is stored as a
:class:pandas.DataFrame containing one row for each epoch. The columns of
this :class:~pandas.DataFrame can contain just about any information you
want to store about each epoch; in this case, the metadata encodes
information about the stimulus seen on each trial, including properties of
the visual word form itself (e.g., NumberOfLetters, VisualComplexity)
as well as properties of what the word means (e.g., its Concreteness) and
its prominence in the English lexicon (e.g., WordFrequency). Here are all
the variables; note that in a Jupyter notebook, viewing a
:class:pandas.DataFrame gets rendered as an HTML table instead of the
normal Python output block:
Can you write Python code for it?


I am working on the file "0.23/_downloads/2455121b46e43615a45b660a36d0ad93/30_epochs_metadata.ipynb".
The first task is:
Viewing the metadata values for a given epoch and metadata variable is done
using any of the Pandas indexing <pandas:/reference/indexing.rst>
methods such as :obj:~pandas.DataFrame.loc,
:obj:~pandas.DataFrame.iloc, :obj:~pandas.DataFrame.at,
and :obj:~pandas.DataFrame.iat. Because the
index of the dataframe is the integer epoch number, the name- and index-based
selection methods will work similarly for selecting rows, except that
name-based selection (with :obj:~pandas.DataFrame.loc) is inclusive of the
endpoint:
Can you write Python code for it?

print('Name-based selection with .loc')
print(epochs.metadata.loc[2:4])

print('\nIndex-based selection with .iloc')
print(epochs.metadata.iloc[2:4])


I am working on the file "0.23/_downloads/26b665b81df8d69d2764306260a9ffa9/cluster_stats_evoked.ipynb".
The first task is:
Compute statistic
Can you write Python code for it?

threshold = 6.0
T_obs, clusters, cluster_p_values, H0 = \
    permutation_cluster_test([condition1, condition2], n_permutations=1000,
                             threshold=threshold, tail=1, n_jobs=1,
                             out_type='mask')


I am working on the file "0.23/_downloads/26b665b81df8d69d2764306260a9ffa9/cluster_stats_evoked.ipynb".
The first task is:
Permutation F-test on sensor data with 1D cluster level
One tests if the evoked response is significantly different
between conditions. Multiple comparison problem is addressed
with cluster level permutation test.
Can you write Python code for it?

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

import matplotlib.pyplot as plt

import mne
from mne import io
from mne.stats import permutation_cluster_test
from mne.datasets import sample

print(__doc__)


I am working on the file "0.23/_downloads/26b665b81df8d69d2764306260a9ffa9/cluster_stats_evoked.ipynb".
The first task is:
Read epochs for the channel of interest
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=False, eog=True, include=include,
                       exclude='bads')
event_id = 1
reject = dict(grad=4000e-13, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject)
condition1 = epochs1.get_data()  # as 3D matrix

event_id = 2
epochs2 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject)
condition2 = epochs2.get_data()  # as 3D matrix

condition1 = condition1[:, 0, :]  # take only one channel to get a 2D array
condition2 = condition2[:, 0, :]  # take only one channel to get a 2D array


I am working on the file "0.23/_downloads/26b665b81df8d69d2764306260a9ffa9/cluster_stats_evoked.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'
tmin = -0.2
tmax = 0.5

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

channel = 'MEG 1332'  # include only this channel in analysis
include = [channel]


I am working on the file "0.23/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
(1) Least smoothing (most variance/background fluctuations).
Can you write Python code for it?

n_cycles = freqs / 2.
time_bandwidth = 2.0  # Least possible frequency-smoothing (1 taper)
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth, return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
           title='Sim: Least smoothing, most variance')


I am working on the file "0.23/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
(2) Less frequency smoothing, more time smoothing.
Can you write Python code for it?

n_cycles = freqs  # Increase time-window length to 1 second.
time_bandwidth = 4.0  # Same frequency-smoothing as (1) 3 tapers.
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth, return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
           title='Sim: Less frequency smoothing, more time smoothing')


I am working on the file "0.23/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
Operating on arrays
MNE also has versions of the functions above which operate on numpy arrays
instead of MNE objects. They expect inputs of the shape
(n_epochs, n_channels, n_times). They will also return a numpy array
of shape (n_epochs, n_channels, n_freqs, n_times).
Can you write Python code for it?

power = tfr_array_morlet(epochs.get_data(), sfreq=epochs.info['sfreq'],
                         freqs=freqs, n_cycles=n_cycles,
                         output='avg_power')
# Baseline the output
rescale(power, epochs.times, (0., 0.1), mode='mean', copy=False)
fig, ax = plt.subplots()
x, y = centers_to_edges(epochs.times * 1000, freqs)
mesh = ax.pcolormesh(x, y, power[0], cmap='RdBu_r', vmin=vmin, vmax=vmax)
ax.set_title('TFR calculated on a numpy array')
ax.set(ylim=freqs[[0, -1]], xlabel='Time (ms)')
fig.colorbar(mesh)
plt.tight_layout()

plt.show()


I am working on the file "0.23/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
Simulate data
We'll simulate data with a known spectro-temporal structure.
Can you write Python code for it?

sfreq = 1000.0
ch_names = ['SIM0001', 'SIM0002']
ch_types = ['grad', 'grad']
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)

n_times = 1024  # Just over 1 second epochs
n_epochs = 40
seed = 42
rng = np.random.RandomState(seed)
noise = rng.randn(n_epochs, len(ch_names), n_times)

# Add a 50 Hz sinusoidal burst to the noise and ramp it.
t = np.arange(n_times, dtype=np.float64) / sfreq
signal = np.sin(np.pi * 2. * 50. * t)  # 50 Hz sinusoid signal
signal[np.logical_or(t < 0.45, t > 0.55)] = 0.  # Hard windowing
on_time = np.logical_and(t >= 0.45, t <= 0.55)
signal[on_time] *= np.hanning(on_time.sum())  # Ramping
data = noise + signal

reject = dict(grad=4000)
events = np.empty((n_epochs, 3), dtype=int)
first_event_sample = 100
event_id = dict(sin50hz=1)
for k in range(n_epochs):
    events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz']

epochs = EpochsArray(data=data, info=info, events=events, event_id=event_id,
                     reject=reject)

epochs.average().plot()


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Analyzing regions of interest (ROIs): averaging across channels
Since our sample data is responses to left and right auditory and visual
stimuli, we may want to compare left versus right ROIs. To average across
channels in a region of interest, we first find the channel indices we want.
Looking back at the 2D sensor plot above, we might choose the following for
left and right ROIs:
Can you write Python code for it?

left = ['eeg17', 'eeg18', 'eeg25', 'eeg26']
right = ['eeg23', 'eeg24', 'eeg34', 'eeg35']

left_ix = mne.pick_channels(l_aud.info['ch_names'], include=left)
right_ix = mne.pick_channels(l_aud.info['ch_names'], include=right)


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Comparing conditions
If we wanted to compare our auditory and visual stimuli, a useful function is
mne.viz.plot_compare_evokeds. By default this will combine all channels in
each evoked object using global field power (or RMS for MEG channels); here
instead we specify to combine by averaging, and restrict it to a subset of
channels by passing picks:
Can you write Python code for it?

evokeds = dict(auditory=l_aud, visual=l_vis)
picks = [f'eeg{n}' for n in range(10, 15)]
mne.viz.plot_compare_evokeds(evokeds, picks=picks, combine='mean')


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Considerable customization of these plots is possible, see the docstring of
~mne.Evoked.plot_topomap for details.
There is also a built-in method for combining "butterfly" plots of the
signals with scalp topographies, called ~mne.Evoked.plot_joint. Like
~mne.Evoked.plot_topomap you can specify times for the scalp topographies
or you can let the method choose times automatically, as is done here:
Can you write Python code for it?