I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
It is also possible to compute a vector beamformer, which gives back three
estimates per voxel, corresponding to the three direction components of the
source. This can be achieved by setting
pick_ori='vector' and will yield a :class:volume vector source estimate
<mne.VolVectorSourceEstimate>. So we will compute another set of filters
using the vector beamformer approach:
Can you write Python code for it?

filters_vec = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                        noise_cov=noise_cov, pick_ori='vector',
                        weight_norm='unit-noise-gain', rank=None)
# save a bit of memory
src = forward['src']
del forward


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Morph the output to fsaverage
We can also use volumetric morphing to get the data to fsaverage space. This
is for example necessary when comparing activity across subjects. Here, we
will use the scalar beamformer example.
We pass a :class:mne.SourceMorph as the src argument to
mne.VolSourceEstimate.plot. To save some computational load when applying
the morph, we will crop the stc:
Can you write Python code for it?

fetch_fsaverage(subjects_dir)  # ensure fsaverage src exists
fname_fs_src = subjects_dir + '/fsaverage/bem/fsaverage-vol-5-src.fif'

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

stc_fs.plot(
    src=src_fs, mode='stat_map', initial_time=0.085, subjects_dir=subjects_dir,
    clim=dict(kind='value', pos_lims=lims), verbose=True)


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
On MNI glass brain (orthoview; 2D)
Can you write Python code for it?

stc.plot(mode='glass_brain', clim=dict(kind='value', lims=lims), **kwargs)


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
On MRI slices (orthoview; 2D)
Can you write Python code for it?

stc.plot(mode='stat_map', clim=dict(kind='value', pos_lims=lims), **kwargs)


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Source reconstruction using an LCMV beamformer
This tutorial gives an overview of the beamformer method
and shows how to use an LCMV beamformer to reconstruct source activity.
   :depth: 2
Can you write Python code for it?

# Author: Britta Westner <britta.wstnr@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.beamformer import make_lcmv, apply_lcmv


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Visualize the reconstructed source activity
We can visualize the source estimate in different ways, e.g. as a volume
rendering, an overlay onto the MRI, or as an overlay onto a glass brain.
The plots for the scalar beamformer show brain activity in the right temporal
lobe around 100 ms post stimulus. This is expected given the left-ear
auditory stimulation of the experiment.
Can you write Python code for it?

lims = [0.3, 0.45, 0.6]
kwargs = dict(src=src, subject='sample', subjects_dir=subjects_dir,
              initial_time=0.087, verbose=True)


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Volumetric rendering (3D) with vectors
These plots can also be shown using a volumetric rendering via
:meth:~mne.VolVectorSourceEstimate.plot_3d. Let's try visualizing the
vector beamformer case. Here we get three source time courses out per voxel
(one for each component of the dipole moment: x, y, and z), which appear
as small vectors in the visualization (in the 2D plotters, only the
magnitude can be shown):
Can you write Python code for it?

brain = stc_vec.plot_3d(
    clim=dict(kind='value', lims=lims), hemi='both',
    views=['coronal', 'sagittal', 'axial'], size=(800, 300),
    view_layout='horizontal', show_traces=0.3, **kwargs)


I am working on the file "0.21/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_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.21/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_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.21/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_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[:2]:
    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.21/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Or, we can get an ERP/F plot with :meth:~mne.Evoked.plot or a combined
scalp field maps and ERP/F plot with :meth:~mne.Evoked.plot_joint. Here
we've specified the times for scalp field maps manually, but if not provided
they will be chosen automatically based on peaks in the signal:
Can you write Python code for it?


I am working on the file "0.21/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Overview of artifact detection
This tutorial covers the basics of artifact detection, and introduces the
artifact detection tools available in MNE-Python.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>:
Can you write Python code for it?

import os
import numpy as np
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.crop(0, 60).load_data()  # just use a fraction of data for speed here


I am working on the file "0.21/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_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?


I am working on the file "0.21/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
By default, :func:~mne.viz.plot_evoked_topo will plot all MEG sensors (if
present), so to get EEG sensors you would need to modify the evoked objects
first (e.g., using :func:mne.pick_types).

Note

In interactive sessions, both approaches to topographical plotting allow
    you to click one of the sensor subplots to pop open a larger version of
    the evoked plot at that sensor.

3D Field Maps
The scalp topographies above were all projected into 2-dimensional overhead
views of the field, but it is also possible to plot field maps in 3D. To do
this requires a :term:trans file to transform locations between the
coordinate systems of the MEG device and the head surface (based on the MRI).
You can compute 3D field maps without a trans file, but it will only
work for calculating the field on the MEG helmet from the MEG sensors.
Can you write Python code for it?

subjects_dir = os.path.join(sample_data_folder, 'subjects')
sample_data_trans_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                      'sample_audvis_raw-trans.fif')


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

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


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


I am working on the file "0.21/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Image plots
Like :class:~mne.Epochs, :class:~mne.Evoked objects also have a
:meth:~mne.Evoked.plot_image method, but unlike :meth:epochs.plot_image()
<mne.Epochs.plot_image>, :meth:evoked.plot_image() <mne.Evoked.plot_image>
shows one channel per row instead of one epoch per row. Again, a
picks parameter is available, as well as several other customization
options; see :meth:~mne.Evoked.plot_image for details.
Can you write Python code for it?


I am working on the file "0.21/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
One nice feature of :func:~mne.viz.plot_compare_evokeds is that when
passing evokeds in a dictionary, it allows specifying plot styles based on
/-separated substrings of the dictionary keys (similar to epoch
selection; see tut-section-subselect-epochs). Here, we specify colors
for "aud" and "vis" conditions, and linestyles for "left" and "right"
conditions, and the traces and legend are styled accordingly.
Can you write Python code for it?

mne.viz.plot_compare_evokeds(evks, picks='MEG 1811', colors=dict(aud=0, vis=1),
                             linestyles=dict(left='solid', right='dashed'))


I am working on the file "0.21/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Plotting scalp topographies
In an interactive session, the butterfly plots seen above can be
click-dragged to select a time region, which will pop up a map of the average
field distribution over the scalp for the selected time span. You can also
generate scalp topographies at specific times or time spans using the
:meth:~mne.Evoked.plot_topomap method:
Can you write Python code for it?

times = np.linspace(0.05, 0.13, 5)
evks['aud/left'].plot_topomap(ch_type='mag', times=times, colorbar=True)

fig = evks['aud/left'].plot_topomap(ch_type='mag', times=0.09, average=0.1)
fig.text(0.5, 0.05, 'average from 40-140 ms', ha='center')


I am working on the file "0.21/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Plotting signal traces
.. sidebar:: Butterfly plots
Plots of superimposed sensor timeseries are called "butterfly plots"
   because the positive- and negative-going traces can resemble
   butterfly wings.
The most basic plot of :class:~mne.Evoked objects is a butterfly plot of
each channel type, generated by the :meth:evoked.plot() <mne.Evoked.plot>
method. By default, channels marked as "bad" are suppressed, but you can
control this by passing an empty :class:list to the exclude parameter
(default is exclude='bads'):
Can you write Python code for it?


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

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


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

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


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


I am working on the file "0.21/_downloads/481587b48f7ba7c5e977b66e26948141/plot_psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute LCMV filters with different data covariance matrices
Can you write Python code for it?

# compute LCMV beamformer filters for pre-stimulus interval
filters_pre = make_lcmv(info, forward, cov_pre, reg=0.05,
                        noise_cov=noise_cov,
                        pick_ori=None, rank=None,
                        weight_norm=None,
                        reduce_rank=False,
                        verbose=False)

# compute LCMV beamformer filters for post-stimulus interval
filters_post = make_lcmv(info, forward, cov_post, reg=0.05,
                         noise_cov=noise_cov,
                         pick_ori=None, rank=None,
                         weight_norm=None,
                         reduce_rank=False,
                         verbose=False)


I am working on the file "0.21/_downloads/481587b48f7ba7c5e977b66e26948141/plot_psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute cross-talk functions for LCMV beamformers
Visualise cross-talk functions at one vertex for LCMV beamformers computed
with different data covariance matrices, which affects their cross-talk
functions.
Can you write Python code for it?

# Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, make_lcmv_resolution_matrix
from mne.minimum_norm import get_cross_talk

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects/'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fname_evo = data_path + '/MEG/sample/sample_audvis-ave.fif'
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

# Read raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)

# only pick good EEG/MEG sensors
raw.info['bads'] += ['EEG 053']  # bads + 1 more
picks = mne.pick_types(raw.info, meg=True, eeg=True, exclude='bads')

# Find events
events = mne.find_events(raw)

# event_id = {'aud/l': 1, 'aud/r': 2, 'vis/l': 3, 'vis/r': 4}
event_id = {'vis/l': 3, 'vis/r': 4}

tmin, tmax = -.2, .25  # epoch duration
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
                    picks=picks, baseline=(-.2, 0.), preload=True)

# covariance matrix for pre-stimulus interval
tmin, tmax = -.2, 0.
cov_pre = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax,
                                 method='empirical')

# covariance matrix for post-stimulus interval (around main evoked responses)
tmin, tmax = 0.05, .25
cov_post = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax,
                                  method='empirical')

# read forward solution
forward = mne.read_forward_solution(fname_fwd)
# use forward operator with fixed source orientations
forward = mne.convert_forward_solution(forward, surf_ori=True,
                                       force_fixed=True)

# read noise covariance matrix
noise_cov = mne.read_cov(fname_cov)

# get valid measurement info
raw = raw.pick_types(meg=True, eeg=True, exclude='bads')
info = raw.info

# regularize noise covariance (we used 'empirical' above)
noise_cov =...


I am working on the file "0.21/_downloads/4b8143fc119add305008cc8010a5a81c/plot_resolution_metrics_eegmeg.ipynb".
The first task is:
EEGMEG
Compute resolution matrices, localization error, and spatial deviations
for MNE:
Can you write Python code for it?

rm_emeg = make_inverse_resolution_matrix(forward_emeg, inv_emeg,
                                         method='MNE', lambda2=lambda2)
ple_psf_emeg = resolution_metrics(rm_emeg, inv_emeg['src'],
                                  function='psf', metric='peak_err')
sd_psf_emeg = resolution_metrics(rm_emeg, inv_emeg['src'],
                                 function='psf', metric='sd_ext')
del rm_emeg


I am working on the file "0.21/_downloads/4b8143fc119add305008cc8010a5a81c/plot_resolution_metrics_eegmeg.ipynb".
The first task is:
MEG
Do the same for MEG:
Can you write Python code for it?

rm_meg = make_inverse_resolution_matrix(forward_meg, inv_meg,
                                        method='MNE', lambda2=lambda2)
ple_psf_meg = resolution_metrics(rm_meg, inv_meg['src'],
                                 function='psf', metric='peak_err')
sd_psf_meg = resolution_metrics(rm_meg, inv_meg['src'],
                                function='psf', metric='sd_ext')
del rm_meg


I am working on the file "0.21/_downloads/4b8143fc119add305008cc8010a5a81c/plot_resolution_metrics_eegmeg.ipynb".
The first task is:
These plots show that with respect to peak localization error, adding EEG to
MEG does not bring much benefit. Next let's visualise spatial deviation (SD)
across the whole cortex for PSF:
Can you write Python code for it?

brain_sd_emeg = sd_psf_emeg.plot('sample', 'inflated', 'lh',
                                 subjects_dir=subjects_dir, figure=4,
                                 clim=dict(kind='value', lims=(0, 2, 4)))

brain_sd_emeg.add_text(0.1, 0.9, 'SD PSF EMEG', 'title', font_size=16)

brain_sd_meg = sd_psf_meg.plot('sample', 'inflated', 'lh',
                               subjects_dir=subjects_dir, figure=5,
                               clim=dict(kind='value', lims=(0, 2, 4)))

brain_sd_meg.add_text(0.1, 0.9, 'SD PSF MEG', 'title', font_size=16)

# Subtract the two distributions and plot this difference
diff_sd = sd_psf_emeg - sd_psf_meg

brain_sd_diff = diff_sd.plot('sample', 'inflated', 'lh',
                             subjects_dir=subjects_dir, figure=6,
                             clim=dict(kind='value', pos_lims=(0., .5, 1.)),
                             smoothing_steps=20)

brain_sd_diff.add_text(0.1, 0.9, 'SD EMEG-MEG', 'title', font_size=16)


I am working on the file "0.21/_downloads/4b8143fc119add305008cc8010a5a81c/plot_resolution_metrics_eegmeg.ipynb".
The first task is:
Visualization
Look at peak localisation error (PLE) across the whole cortex for PSF:
Can you write Python code for it?

brain_ple_emeg = ple_psf_emeg.plot('sample', 'inflated', 'lh',
                                   subjects_dir=subjects_dir, figure=1,
                                   clim=dict(kind='value', lims=(0, 2, 4)))

brain_ple_emeg.add_text(0.1, 0.9, 'PLE PSF EMEG', 'title', font_size=16)

brain_ple_meg = ple_psf_meg.plot('sample', 'inflated', 'lh',
                                 subjects_dir=subjects_dir, figure=2,
                                 clim=dict(kind='value', lims=(0, 2, 4)))

brain_ple_meg.add_text(0.1, 0.9, 'PLE PSF MEG', 'title', font_size=16)

# Subtract the two distributions and plot this difference
diff_ple = ple_psf_emeg - ple_psf_meg

brain_ple_diff = diff_ple.plot('sample', 'inflated', 'lh',
                               subjects_dir=subjects_dir, figure=3,
                               clim=dict(kind='value', pos_lims=(0., .5, 1.)),
                               smoothing_steps=20)

brain_ple_diff.add_text(0.1, 0.9, 'PLE EMEG-MEG', 'title', font_size=16)


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


I am working on the file "0.21/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
Creating Evoked objects from Epochs
:class:~mne.Evoked objects typically store an EEG or MEG signal that has
been averaged over multiple :term:epochs, which is a common technique for
estimating stimulus-evoked activity. The data in an :class:~mne.Evoked
object are stored in an :class:array <numpy.ndarray> of shape
(n_channels, n_times) (in contrast to an :class:~mne.Epochs object,
which stores data of shape (n_epochs, n_channels, n_times)). Thus to
create an :class:~mne.Evoked object, we'll start by epoching some raw data,
and then averaging together all the epochs from one condition:
Can you write Python code for it?

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
events = mne.find_events(raw, stim_channel='STI 014')
# we'll skip the "face" and "buttonpress" conditions, to save memory:
event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4}
epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7, event_id=event_dict,
                    preload=True)
evoked = epochs['auditory/left'].average()

del raw  # reduce memory usage


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

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


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

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


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

for evok in evokeds_list:
    print(evok.comment)


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

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


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


I am working on the file "0.21/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
This approach will weight each epoch equally and create a single
:class:~mne.Evoked object. Notice that the printed representation includes
(average, N=145), indicating that the :class:~mne.Evoked object was
created by averaging across 145 epochs. In this case, the event types were
fairly close in number:
Can you write Python code for it?

left_aud = epochs['auditory/left'].average()
right_aud = epochs['auditory/right'].average()
print([evok.nave for evok in (left_aud, right_aud)])


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


I am working on the file "0.21/_downloads/5514ea6c90dde531f8026904a417527e/plot_10_evoked_overview.ipynb".
The first task is:
To select based on time in seconds, the :meth:~mne.Evoked.time_as_index
method can be useful, although beware that depending on the sampling
frequency, the number of samples in a span of given duration may not always
be the same (see the time-as-index section of the
tutorial about Raw data <tut-raw-class> for details).
Selecting, dropping, and reordering channels
By default, when creating :class:~mne.Evoked data from an
:class:~mne.Epochs object, only the "data" channels will be retained:
eog, ecg, stim, and misc channel types will be dropped. You
can control which channel types are retained via the picks parameter of
:meth:epochs.average() <mne.Epochs.average>, by passing 'all' to
retain all channels, or by passing a list of integers, channel names, or
channel types. See the documentation of :meth:~mne.Epochs.average for
details.
If you've already created the :class:~mne.Evoked object, you can use the
:meth:~mne.Evoked.pick, :meth:~mne.Evoked.pick_channels,
:meth:~mne.Evoked.pick_types, and :meth:~mne.Evoked.drop_channels methods
to modify which channels are included in an :class:~mne.Evoked object.
You can also use :meth:~mne.Evoked.reorder_channels for this purpose; any
channel names not provided to :meth:~mne.Evoked.reorder_channels will be
dropped. Note that channel selection methods modify the object in-place, so
in interactive/exploratory sessions you may want to create a
:meth:~mne.Evoked.copy first.
Can you write Python code for it?

evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
print(evoked_eeg.ch_names)

new_order = ['EEG 002', 'MEG 2521', 'EEG 003']
evoked_subset = evoked.copy().reorder_channels(new_order)
print(evoked_subset.ch_names)


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

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


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

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


I am working on the file "0.21/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_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.21/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
If you're working with a :class:~mne.io.Raw object that already has sensor
positions incorporated, you can create a :class:~mne.channels.Layout object
with either the :func:mne.channels.make_eeg_layout function or
(equivalently) the :func:mne.channels.find_layout function.
Can you write Python code for it?

layout_from_raw = mne.channels.make_eeg_layout(raw.info)
# same result as: mne.channels.find_layout(raw.info, ch_type='eeg')
layout_from_raw.plot()


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


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

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


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

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


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

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

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


I am working on the file "0.21/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Alternative functions for PSDs
There are also several functions in MNE that create a PSD using a Raw
object. These are in the :mod:mne.time_frequency module and begin with
psd_*. For example, we'll use a multitaper method to compute the PSD
below.
Can you write Python code for it?

f, ax = plt.subplots()
psds, freqs = psd_multitaper(raw, low_bias=True, tmin=tmin, tmax=tmax,
                             fmin=fmin, fmax=fmax, proj=True, picks=picks,
                             n_jobs=1)
psds = 10 * np.log10(psds)
psds_mean = psds.mean(0)
psds_std = psds.std(0)

ax.plot(freqs, psds_mean, color='k')
ax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,
                color='k', alpha=.5)
ax.set(title='Multitaper PSD', xlabel='Frequency',
       ylabel='Power Spectral Density (dB)')
plt.show()


I am working on the file "0.21/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Compute the power spectral density of raw data
This script shows how to compute the power spectral density (PSD)
of measurements on a raw dataset. It also show the effect of applying SSP
to the data to reduce ECG and EOG artifacts.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#          Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io, read_proj, read_selection
from mne.datasets import sample
from mne.time_frequency import psd_multitaper

print(__doc__)


I am working on the file "0.21/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Load data
We'll load a sample MEG dataset, along with SSP projections that will
allow us to reduce EOG and ECG artifacts. For more information about
reducing artifacts, see the preprocessing section in documentation.
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_eog-proj.fif'

tmin, tmax = 0, 60  # use the first 60s of data

# Setup for reading the raw data (to save memory, crop before loading)
raw = io.read_raw_fif(raw_fname).crop(tmin, tmax).load_data()
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Add SSP projection vectors to reduce EOG and ECG artifacts
projs = read_proj(proj_fname)
raw.add_proj(projs, remove_existing=True)

fmin, fmax = 2, 300  # look at frequencies between 2 and 300Hz
n_fft = 2048  # the FFT size (n_fft). Ideally a power of 2


I am working on the file "0.21/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Plot a cleaned PSD
Next we'll focus the visualization on a subset of channels.
This can be useful for identifying particularly noisy channels or
investigating how the power spectrum changes across channels.
We'll visualize how this PSD changes after applying some standard
filtering techniques. We'll first apply the SSP projections, which is
accomplished with the proj=True kwarg. We'll then perform a notch filter
to remove particular frequency bands.
Can you write Python code for it?

# Pick MEG magnetometers in the Left-temporal region
selection = read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
                       stim=False, exclude='bads', selection=selection)

# Let's just look at the first few channels for demonstration purposes
picks = picks[:4]

plt.figure()
ax = plt.axes()
raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=False, ax=ax, color=(0, 0, 1), picks=picks,
             show=False, average=True)

raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=True, ax=ax, color=(0, 1, 0), picks=picks,
             show=False, average=True)

# And now do the same with SSP + notch filtering
# Pick all channels for notch since the SSP projection mixes channels together
raw.notch_filter(np.arange(60, 241, 60), n_jobs=1, fir_design='firwin')
raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=True, ax=ax, color=(1, 0, 0), picks=picks,
             show=False, average=True)

ax.set_title('Four left-temporal magnetometers')
leg_lines = [line for line in ax.lines if line.get_linestyle() == '-']
plt.legend(leg_lines, ['Without SSP', 'With SSP', 'SSP + Notch'])


I am working on the file "0.21/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Plot the raw PSD
First we'll visualize the raw PSD of our data. We'll do this on all of the
channels first. Note that there are several parameters to the
:meth:mne.io.Raw.plot_psd method, some of which will be explained below.
Can you write Python code for it?

raw.plot_psd(area_mode='range', tmax=10.0, show=False, average=True)


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

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


I am working on the file "0.21/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
It is also possible to combine two Event IDs using :func:mne.merge_events;
the following example will combine Event IDs 1, 2 and 3 into a single event
labelled 1:
Can you write Python code for it?

merged_events = mne.merge_events(events, [1, 2, 3], 1)
print(np.unique(merged_events[:, -1]))


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

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


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


I am working on the file "0.21/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Working with events
This tutorial describes event representation and how event arrays are used to
subselect data.
   :depth: 2
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping the :class:~mne.io.Raw
object to just 60 seconds before loading it into RAM to save memory:
Can you write Python code for it?

import os
import numpy as np
import mne

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


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
And it's actually possible to plot the channel locations using
:func:mne.io.Raw.plot_sensors.
In the case where your data don't have locations you can use one of the
standard :class:Montages <mne.channels.DigMontage> shipped with MNE.
See plot_montage and tut-eeg-fsaverage-source-modeling.
Can you write Python code for it?

raw.plot_sensors()
raw.plot_sensors('3d')  # in 3D


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
By looking at the measurement info you will see that we have now
59 EEG channels and 1 EOG channel
Can you write Python code for it?


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
EEG processing and Event Related Potentials (ERPs)
:depth: 1
Can you write Python code for it?

import mne
from mne.datasets import sample
from mne.channels import combine_channels


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

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

print(epochs)


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

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

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

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


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

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


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Let's reset the EOG channel back to EOG type.
Can you write Python code for it?


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

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

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


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

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

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


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Often, it makes sense to store Evoked objects in a dictionary or a list -
either different conditions, or different subjects.
Can you write Python code for it?

# If they are stored in a list, they can be easily averaged, for example,
# for a grand average across subjects (or conditions).
grand_average = mne.grand_average(all_evokeds)
mne.write_evokeds('/tmp/tmp-ave.fif', all_evokeds)

# If Evokeds objects are stored in a dictionary, they can be retrieved by name.
all_evokeds = dict((cond, epochs[cond].average()) for cond in event_id)
print(all_evokeds['left/auditory'])

# Besides for explicit access, this can be used for example to set titles.
for cond in all_evokeds:
    all_evokeds[cond].plot_joint(title=cond, **joint_kwargs)


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Setting EEG reference
Let's first inspect our Raw object with its original reference that was
applied during the recording of the data.
We define Epochs and compute an ERP for the left auditory condition.
Can you write Python code for it?

reject = dict(eeg=180e-6, eog=150e-6)
event_id, tmin, tmax = {'left/auditory': 1}, -0.2, 0.5
events = mne.read_events(event_fname)
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     reject=reject)

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

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


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

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


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


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

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

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


I am working on the file "0.21/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
This is an equal-weighting difference. If you have imbalanced trial numbers,
you could also consider either equalizing the number of events per
condition (using
epochs.equalize_event_counts <mne.Epochs.equalize_event_counts>) or
use weights proportional to the number of trials averaged together to create
each ~mne.Evoked (by passing weights='nave' to ~mne.combine_evoked).
As an example, first, we create individual ERPs for each condition.
Can you write Python code for it?

aud_l = epochs["auditory/left"].average()
aud_r = epochs["auditory/right"].average()
vis_l = epochs["visual/left"].average()
vis_r = epochs["visual/right"].average()

all_evokeds = [aud_l, aud_r, vis_l, vis_r]
print(all_evokeds)


I am working on the file "0.21/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Beta
Here we also show OPM data, which shows a profile similar to the VectorView
data beneath the sensors.
Can you write Python code for it?

fig_beta, brain_beta = plot_band('vv', 'beta')
fig_beta_opm, brain_beta_opm = plot_band('opm', 'beta')


I am working on the file "0.21/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Compute and apply inverse to PSD estimated using multitaper + Welch.
Group into frequency bands, then normalize each source point and sensor
independently. This makes the value of each sensor point and source location
in each frequency band the percentage of the PSD accounted for by that band.
Can you write Python code for it?

freq_bands = dict(
    delta=(2, 4), theta=(5, 7), alpha=(8, 12), beta=(15, 29), gamma=(30, 45))
topos = dict(vv=dict(), opm=dict())
stcs = dict(vv=dict(), opm=dict())

snr = 3.
lambda2 = 1. / snr ** 2
for kind in kinds:
    noise_cov = mne.compute_raw_covariance(raw_erms[kind])
    inverse_operator = mne.minimum_norm.make_inverse_operator(
        raws[kind].info, forward=fwd[kind], noise_cov=noise_cov, verbose=True)
    stc_psd, sensor_psd = mne.minimum_norm.compute_source_psd(
        raws[kind], inverse_operator, lambda2=lambda2,
        n_fft=n_fft, dB=False, return_sensor=True, verbose=True)
    topo_norm = sensor_psd.data.sum(axis=1, keepdims=True)
    stc_norm = stc_psd.sum()  # same operation on MNE object, sum across freqs
    # Normalize each source point by the total power across freqs
    for band, limits in freq_bands.items():
        data = sensor_psd.copy().crop(*limits).data.sum(axis=1, keepdims=True)
        topos[kind][band] = mne.EvokedArray(
            100 * data / topo_norm, sensor_psd.info)
        stcs[kind][band] = \
            100 * stc_psd.copy().crop(*limits).sum() / stc_norm.data
    del inverse_operator
del fwd, raws, raw_erms


I am working on the file "0.21/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Compute source power spectral density (PSD) of VectorView and OPM data
Here we compute the resting state from raw for data recorded using
a Neuromag VectorView system and a custom OPM system.
The pipeline is meant to mostly follow the Brainstorm [1]
OMEGA resting tutorial pipeline <bst_omega_>.
The steps we use are:

Filtering: downsample heavily.
Artifact detection: use SSP for EOG and ECG.
Source localization: dSPM, depth weighting, cortically constrained.
Frequency: power spectral density (Welch), 4 sec window, 50% overlap.
Standardize: normalize by relative power for each source.
   :depth: 1

Preprocessing
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Luke Bloy <luke.bloy@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import os.path as op

from mne.filter import next_fast_len

import mne

print(__doc__)

data_path = mne.datasets.opm.data_path()
subject = 'OPM_sample'

subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, subject, 'bem')
bem_fname = op.join(subjects_dir, subject, 'bem',
                    subject + '-5120-5120-5120-bem-sol.fif')
src_fname = op.join(bem_dir, '%s-oct6-src.fif' % subject)
vv_fname = data_path + '/MEG/SQUID/SQUID_resting_state.fif'
vv_erm_fname = data_path + '/MEG/SQUID/SQUID_empty_room.fif'
vv_trans_fname = data_path + '/MEG/SQUID/SQUID-trans.fif'
opm_fname = data_path + '/MEG/OPM/OPM_resting_state_raw.fif'
opm_erm_fname = data_path + '/MEG/OPM/OPM_empty_room_raw.fif'
opm_trans_fname = None
opm_coil_def_fname = op.join(data_path, 'MEG', 'OPM', 'coil_def.dat')


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

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


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

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


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

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

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


I am working on the file "0.21/_downloads/638c39682b0791ce4e430e4d2fcc4c45/plot_tf_dics.ipynb".
The first task is:
Time-frequency beamforming based on DICS
Can you write Python code for it?

# Setting frequency bins as in Dalal et al. 2008
freq_bins = [(4, 12), (12, 30), (30, 55), (65, 300)]  # Hz
win_lengths = [0.3, 0.2, 0.15, 0.1]  # s
# Then set FFTs length for each frequency range.
# Should be a power of 2 to be faster.
n_ffts = [256, 128, 128, 128]

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating noise cross-spectral density from empty room noise for each
# frequency bin and the corresponding time window length. To calculate noise
# from the baseline period in the data, change epochs_noise to epochs
noise_csds = []
for freq_bin, win_length, n_fft in zip(freq_bins, win_lengths, n_ffts):
    noise_csd = csd_fourier(epochs_noise, fmin=freq_bin[0], fmax=freq_bin[1],
                            tmin=-win_length, tmax=0, n_fft=n_fft)
    noise_csds.append(noise_csd.sum())

# Computing DICS solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths,
               freq_bins=freq_bins, subtract_evoked=subtract_evoked,
               n_ffts=n_ffts, reg=0.05, label=label, inversion='matrix')

# Plotting source spectrogram for source with maximum activity
# Note that tmin and tmax are set to display a time range that is smaller than
# the one for which beamforming estimates were calculated. This ensures that
# all time bins shown are a result of smoothing across an identical number of
# time windows.
plot_source_spectrogram(stcs, freq_bins, tmin=tmin_plot, tmax=tmax_plot,
                        source_index=None, colorbar=True)


I am working on the file "0.21/_downloads/638c39682b0791ce4e430e4d2fcc4c45/plot_tf_dics.ipynb".
The first task is:
Time-frequency beamforming using DICS
Compute DICS source power [1]_ in a grid of time-frequency windows.
References
.. [1] Dalal et al. Five-dimensional neuroimaging: Localization of the
       time-frequency dynamics of cortical activity.
       NeuroImage (2008) vol. 40 (4) pp. 1686-1700
Can you write Python code for it?

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

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

print(__doc__)

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


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

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

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


I am working on the file "0.21/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
If you want to control which integers are mapped to each unique description
value, you can pass a :class:dict specifying the mapping as the
event_id parameter of :func:~mne.events_from_annotations; this
:class:dict will be returned unmodified as the event_dict.
.. TODO add this when the other tutorial is nailed down:
   Note that this event_dict can be used when creating
   :class:~mne.Epochs from :class:~mne.io.Raw objects, as demonstrated
   in :doc:epoching_tutorial_whatever_its_name_is.
Can you write Python code for it?

custom_mapping = {'rt': 77, 'square': 42}
(events_from_annot,
 event_dict) = mne.events_from_annotations(eeglab_raw, event_id=custom_mapping)
print(event_dict)
print(events_from_annot[:5])


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


I am working on the file "0.21/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
Parsing events from raw data
This tutorial describes how to read experimental events from raw recordings,
and how to convert between the two different representations of events within
MNE-Python (Events arrays and Annotations objects).
   :depth: 1
In the introductory tutorial <overview-tut-events-section> we saw an
example of reading experimental events from a :term:"STIM" channel <stim
channel>; here we'll discuss :term:events and :term:annotations more
broadly, give more detailed information about reading from STIM channels, and
give an example of reading events that are in a marker file or included in the
data file as an embedded array. The tutorials tut-event-arrays and
tut-annotate-raw discuss how to plot, combine, load, save, and
export :term:events and :class:~mne.Annotations (respectively), and the
latter tutorial also covers interactive annotation of :class:~mne.io.Raw
objects.
We'll begin by loading the Python modules we need, and loading the same
example data <sample-dataset> we used in the introductory tutorial
<tut-overview>, but to save memory we'll crop the :class:~mne.io.Raw object
to just 60 seconds before loading it into RAM:
Can you write Python code for it?

import os
import numpy as np
import mne

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


I am working on the file "0.21/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
The Events and Annotations data structures
Generally speaking, both the Events and :class:~mne.Annotations data
structures serve the same purpose: they provide a mapping between times
during an EEG/MEG recording and a description of what happened at those
times. In other words, they associate a when with a what. The main
differences are:

Units: the Events data structure represents the when in terms of
   samples, whereas the :class:~mne.Annotations data structure represents
   the when in seconds.
Limits on the description: the Events data structure represents the
   what as an integer "Event ID" code, whereas the
   :class:~mne.Annotations data structure represents the what as a
   string.
How duration is encoded: Events in an Event array do not have a
   duration (though it is possible to represent duration with pairs of
   onset/offset events within an Events array), whereas each element of an
   :class:~mne.Annotations object necessarily includes a duration (though
   the duration can be zero if an instantaneous event is desired).
Internal representation: Events are stored as an ordinary
   :class:NumPy array <numpy.ndarray>, whereas :class:~mne.Annotations is
   a :class:list-like class defined in MNE-Python.

What is a STIM channel?
A :term:stim channel (short for "stimulus channel") is a channel that does
not receive signals from an EEG, MEG, or other sensor. Instead, STIM channels
record voltages (usually short, rectangular DC pulses of fixed magnitudes
sent from the experiment-controlling computer) that are time-locked to
experimental events, such as the onset of a stimulus or a button-press
response by the subject (those pulses are sometimes called TTL_ pulses,
event pulses, trigger signals, or just "triggers"). In other cases, these
pulses may not be strictly time-locked to an experimental event, but instead
may occur in between trials to indicate the type of stimulus (or experimental
condition) that is about to occur on the upcoming trial.
The DC pulses may be all on one STIM channel (in...
Can you write Python code for it?


I am working on the file "0.21/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
The core data within an :class:~mne.Annotations object is accessible
through three of its attributes: onset, duration, and
description. Here we can see that there were 154 events stored in the
EEGLAB file, they all had a duration of zero seconds, there were two
different types of events, and the first event occurred about 1 second after
the recording began:
Can you write Python code for it?


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

mapping = {1: 'auditory/left', 2: 'auditory/right', 3: 'visual/left',
           4: 'visual/right', 5: 'smiley', 32: 'buttonpress'}
onsets = events[:, 0] / raw.info['sfreq']
durations = np.zeros_like(onsets)  # assumes instantaneous events
descriptions = [mapping[event_id] for event_id in events[:, 2]]
annot_from_events = mne.Annotations(onset=onsets, duration=durations,
                                    description=descriptions,
                                    orig_time=raw.info['meas_date'])
raw.set_annotations(annot_from_events)


I am working on the file "0.21/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
.. KEEP THESE BLOCKS SEPARATE SO FIGURES ARE BIG ENOUGH TO READ
Can you write Python code for it?

# set reference to `EEG 050`
raw_new_ref.set_eeg_reference(ref_channels=['EEG 050'])
raw_new_ref.plot()


I am working on the file "0.21/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Background
EEG measures a voltage (difference in electric potential) between each
electrode and a reference electrode. This means that whatever signal is
present at the reference electrode is effectively subtracted from all the
measurement electrodes. Therefore, an ideal reference signal is one that
captures none of the brain-specific fluctuations in electric potential,
while capturing all of the environmental noise/interference that is being
picked up by the measurement electrodes.
In practice, this means that the reference electrode is often placed in a
location on the subject's body and close to their head (so that any
environmental interference affects the reference and measurement electrodes
similarly) but as far away from the neural sources as possible (so that the
reference signal doesn't pick up brain-based fluctuations). Typical reference
locations are the subject's earlobe, nose, mastoid process, or collarbone.
Each of these has advantages and disadvantages regarding how much brain
signal it picks up (e.g., the mastoids pick up a fair amount compared to the
others), and regarding the environmental noise it picks up (e.g., earlobe
electrodes may shift easily, and have signals more similar to electrodes on
the same side of the head).
Even in cases where no electrode is specifically designated as the reference,
EEG recording hardware will still treat one of the scalp electrodes as the
reference, and the recording software may or may not display it to you (it
might appear as a completely flat channel, or the software might subtract out
the average of all signals before displaying, making it look like there is
no reference).
Setting or changing the reference channel
If you want to recompute your data with a different reference than was used
when the raw data were recorded and/or saved, MNE-Python provides the
:meth:~mne.io.Raw.set_eeg_reference method on :class:~mne.io.Raw objects
as well as the :func:mne.add_reference_channels function. To use an
existing channel as the new reference, use...
Can you write Python code for it?

# code lines below are commented out because the sample data doesn't have
# earlobe or mastoid channels, so this is just for demonstration purposes:

# use a single channel reference (left earlobe)
# raw.set_eeg_reference(ref_channels=['A1'])

# use average of mastoid channels as reference
# raw.set_eeg_reference(ref_channels=['M1', 'M2'])


I am working on the file "0.21/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
By default, :func:~mne.add_reference_channels returns a copy, so we can go
back to our original raw object later. If you wanted to alter the
existing :class:~mne.io.Raw object in-place you could specify
copy=False.
Can you write Python code for it?

# add new reference channel (all zero)
raw_new_ref = mne.add_reference_channels(raw, ref_channels=['EEG 999'])
raw_new_ref.plot()


I am working on the file "0.21/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Creating the average reference as a projector
If using an average reference, it is possible to create the reference as a
:term:projector rather than subtracting the reference from the data
immediately by specifying projection=True:
Can you write Python code for it?


I am working on the file "0.21/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Creating the average reference as a projector has a few advantages:

It is possible to turn projectors on or off when plotting, so it is easy
   to visualize the effect that the average reference has on the data.

If additional channels are marked as "bad" or if a subset of channels are
   later selected, the projector will be re-computed to take these changes
   into account (thus guaranteeing that the signal is zero-mean).

If there are other unapplied projectors affecting the EEG channels (such
   as SSP projectors for removing heartbeat or blink artifacts), EEG
   re-referencing cannot be performed until those projectors are either
   applied or removed; adding the EEG reference as a projector is not subject
   to that constraint. (The reason this wasn't a problem when we applied the
   non-projector average reference to raw_avg_ref above is that the
   empty-room projectors included in the sample data :file:.fif file were
   only computed for the magnetometers.)
Can you write Python code for it?

for title, proj in zip(['Original', 'Average'], [False, True]):
    fig = raw.plot(proj=proj, n_channels=len(raw))
    # make room for title
    fig.subplots_adjust(top=0.9)
    fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold')


I am working on the file "0.21/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Notice that the new reference (EEG 050) is now flat, while the original
reference channel that we added back to the data (EEG 999) has a non-zero
signal. Notice also that EEG 053 (which is marked as "bad" in
raw.info['bads']) is not affected by the re-referencing.
Setting average reference
To set a "virtual reference" that is the average of all channels, you can use
:meth:~mne.io.Raw.set_eeg_reference with ref_channels='average'. Just
as above, this will not affect any channels marked as "bad", nor will it
include bad channels when computing the average. However, it does modify the
:class:~mne.io.Raw object in-place, so we'll make a copy first so we can
still go back to the unmodified :class:~mne.io.Raw object later:
Can you write Python code for it?

# use the average of all channels as reference
raw_avg_ref = raw.copy().set_eeg_reference(ref_channels='average')
raw_avg_ref.plot()


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
By default, :func:~mne.io.read_raw_fif displays some information about the
file it's loading; for example, here it tells us that there are four
"projection items" in the file along with the recorded data; those are
:term:SSP projectors <projector> calculated to remove environmental noise
from the MEG signals, plus a projector to mean-reference the EEG channels;
these are discussed in the tutorial tut-projectors-background.
In addition to the information displayed during loading,
you can get a glimpse of the basic details of a :class:~mne.io.Raw object
by printing it; even more is available by printing its info attribute
(a :class:dictionary-like object <mne.Info> that is preserved across
:class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked
objects). The info data structure keeps track of channel locations,
applied filters, projectors, etc. Notice especially the chs entry,
showing that MNE-Python detects different sensor types and handles each
appropriately. See tut-info-class for more on the :class:~mne.Info
class.
Can you write Python code for it?


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Detecting experimental events
The sample dataset includes several :term:"STIM" channels <stim channel>
that recorded electrical
signals sent from the stimulus delivery computer (as brief DC shifts /
squarewave pulses). These pulses (often called "triggers") are used in this
dataset to mark experimental events: stimulus onset, stimulus type, and
participant response (button press). The individual STIM channels are
combined onto a single channel, in such a way that voltage
levels on that channel can be unambiguously decoded as a particular event
type. On older Neuromag systems (such as that used to record the sample data)
this summation channel was called STI 014, so we can pass that channel
name to the :func:mne.find_events function to recover the timing and
identity of the stimulus events.
Can you write Python code for it?

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


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Estimating evoked responses
Now that we have our conditions in aud_epochs and vis_epochs, we can
get an estimate of evoked responses to auditory versus visual stimuli by
averaging together the epochs in each condition. This is as simple as calling
the :meth:~mne.Epochs.average method on the :class:~mne.Epochs object,
and then using a function from the :mod:mne.viz module to compare the
global field power for each sensor type of the two :class:~mne.Evoked
objects:
Can you write Python code for it?

aud_evoked = aud_epochs.average()
vis_evoked = vis_epochs.average()

mne.viz.plot_compare_evokeds(dict(auditory=aud_evoked, visual=vis_evoked),
                             legend='upper left', show_sensors='upper right')


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Event dictionaries like this one are used when extracting epochs from
continuous data; the / character in the dictionary keys allows pooling
across conditions by requesting partial condition descriptors (i.e.,
requesting 'auditory' will select all epochs with Event IDs 1 and 2;
requesting 'left' will select all epochs with Event IDs 1 and 3). An
example of this is shown in the next section. There is also a convenient
:func:~mne.viz.plot_events function for visualizing the distribution of
events across the duration of the recording (to make sure event detection
worked as expected). Here we'll also make use of the :class:~mne.Info
attribute to get the sampling frequency of the recording (so our x-axis will
be in seconds instead of in samples).
Can you write Python code for it?

fig = mne.viz.plot_events(events, event_id=event_dict, sfreq=raw.info['sfreq'],
                          first_samp=raw.first_samp)


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Evoked objects can also be combined to show contrasts between conditions,
using the mne.combine_evoked function. A simple difference can be
generated by passing weights=[1, -1]. We'll then plot the difference wave
at each sensor using ~mne.Evoked.plot_topo:
Can you write Python code for it?

evoked_diff = mne.combine_evoked([aud_evoked, vis_evoked], weights=[1, -1])
evoked_diff.pick_types(meg='mag').plot_topo(color='r', legend=False)


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Like :class:~mne.io.Raw objects, :class:~mne.Epochs objects also have a
number of built-in plotting methods. One is :meth:~mne.Epochs.plot_image,
which shows each epoch as one row of an image map, with color representing
signal magnitude; the average evoked response and the sensor location are
shown below the image:
Can you write Python code for it?

aud_epochs.plot_image(picks=['MEG 1332', 'EEG 021'])


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
We can also get a more detailed view of each :class:~mne.Evoked object
using other plotting methods such as :meth:~mne.Evoked.plot_joint or
:meth:~mne.Evoked.plot_topomap. Here we'll examine just the EEG channels,
and see the classic auditory evoked N100-P200 pattern over dorso-frontal
electrodes, then plot scalp topographies at some additional arbitrary times:
Can you write Python code for it?

aud_evoked.plot_joint(picks='eeg')
aud_evoked.plot_topomap(times=[0., 0.08, 0.1, 0.12, 0.2], ch_type='eeg')


I am working on the file "0.21/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
We'll also pass the event dictionary as the event_id parameter (so we can
work with easy-to-pool event labels instead of the integer event IDs), and
specify tmin and tmax (the time relative to each event at which to
start and end each epoch). As mentioned above, by default
:class:~mne.io.Raw and :class:~mne.Epochs data aren't loaded into memory
(they're accessed from disk only when needed), but here we'll force loading
into memory using the preload=True parameter so that we can see the
results of the rejection criteria being applied:
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.2, tmax=0.5,
                    reject=reject_criteria, preload=True)


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

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


I am working on the file "0.21/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:

Note

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

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


I am working on the file "0.21/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
If you know that your annotation onsets are relative to some other time, you
can set orig_time before you call :meth:~mne.io.Raw.set_annotations,
and the onset times will get adjusted based on the time difference between
your specified orig_time and raw.info['meas_date'], but without the
additional adjustment for raw.first_samp. orig_time can be specified
in various ways (see the documentation of :class:~mne.Annotations for the
options); here we'll use an ISO 8601_ formatted string, and set it to be 50
seconds later than raw.info['meas_date'].
Can you write Python code for it?

time_format = '%Y-%m-%d %H:%M:%S.%f'
new_orig_time = (meas_date + timedelta(seconds=50)).strftime(time_format)
print(new_orig_time)

later_annot = mne.Annotations(onset=[3, 5, 7],
                              duration=[1, 0.5, 0.25],
                              description=['DDD', 'EEE', 'FFF'],
                              orig_time=new_orig_time)

raw2 = raw.copy().set_annotations(later_annot)
print(later_annot.onset)
print(raw2.annotations.onset)


I am working on the file "0.21/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
Note that iterating, indexing and slicing :class:~mne.Annotations all
return a copy, so changes to an indexed, sliced, or iterated element will not
modify the original :class:~mne.Annotations object.
Can you write Python code for it?

# later_annot WILL be changed, because we're modifying the first element of
# later_annot.onset directly:
later_annot.onset[0] = 99

# later_annot WILL NOT be changed, because later_annot[0] returns a copy
# before the 'onset' field is changed:
later_annot[0]['onset'] = 77

print(later_annot[0]['onset'])


I am working on the file "0.21/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
Notice that orig_time is None, because we haven't specified it. In
those cases, when you add the annotations to a :class:~mne.io.Raw object,
it is assumed that the orig_time matches the time of the first sample of
the recording, so orig_time will be set to match the recording
measurement date (raw.info['meas_date']).
Can you write Python code for it?

raw.set_annotations(my_annot)
print(raw.annotations)

# convert meas_date (a tuple of seconds, microseconds) into a float:
meas_date = raw.info['meas_date']
orig_time = raw.annotations.orig_time
print(meas_date == orig_time)


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

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


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


I am working on the file "0.21/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_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:
Can you write Python code for it?


I am working on the file "0.21/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_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.21/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_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. Pre-computed 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.21/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_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.21/_downloads/7cf7296709bf473b6e7fed6bc98287be/plot_ems_filtering.ipynb".
The first task is:
Compute effect-matched-spatial filtering (EMS)
This example computes the EMS to reconstruct the time course of the
experimental effect as described in [1]_.
This technique is used to create spatial filters based on the difference
between two conditions. By projecting the trial onto the corresponding spatial
filters, surrogate single trials are created in which multi-sensor activity is
reduced to one time series which exposes experimental effects, if present.
We will first plot a trials x times image of the single trials and order the
trials by condition. A second plot shows the average time series for each
condition. Finally a topographic plot is created which exhibits the temporal
evolution of the spatial filters.
References
.. [1] Aaron Schurger, Sebastien Marti, and Stanislas Dehaene, "Reducing
       multi-sensor data to a single time course that reveals experimental
       effects", BMC Neuroscience 2013, 14:122.
Can you write Python code for it?

# Author: Denis Engemann <denis.engemann@gmail.com>
#         Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import EMS, compute_ems
from sklearn.model_selection import StratifiedKFold

print(__doc__)

data_path = sample.data_path()

# Preprocess the data
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_ids = {'AudL': 1, 'VisL': 3}

# Read data and create epochs
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(0.5, 45, fir_design='firwin')
events = mne.read_events(event_fname)

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

epochs = mne.Epochs(raw, events, event_ids, tmin=-0.2, tmax=0.5, picks=picks,
                    baseline=None, reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)
epochs.drop_bad()
epochs.pick_types(meg='grad')

# Setup the data to use it a scikit-learn way:
X = epochs.get_data()  # The MEG data
y = epochs.events[:, 2]  # The conditions indices
n_epochs, n_channels, n_times = X.shape

# Initialize EMS transformer
ems = EMS()

# Initialize the variables of interest
X_transform = np.zeros((n_epochs, n_times))  # Data after EMS transformation
filters = list()  # Spatial filters at each time point

# In the original paper, the cross-validation is a leave-one-out. However,
# we recommend using a Stratified KFold, because leave-one-out tends
# to overfit and cannot be used to estimate the variance of the
# prediction within a given fold.

for train, test in StratifiedKFold(n_splits=5).split(X, y):
    # In the original paper, the z-scoring is applied outside the CV.
    # However, we recommend to apply this preprocessing inside the CV.
    # Note that such scaling should be done separately for each channels if the
    # data...


I am working on the file "0.21/_downloads/7f0f8817512fdcca1eab8f4befa07ff9/plot_metadata_query.ipynb".
The first task is:
Any query that works with DataFrame.query will work for selecting epochs.
Can you write Python code for it?

plot_events = ['smiley', 'button']
query = 'kind in {}'.format(plot_events)
plot_query_results(query)